├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── backend ├── backend.go └── postgresql.go ├── examples ├── 7days.heise.de.json ├── README.md ├── der-flix.de-schoene-toechter.json ├── der-flix.de.json ├── dilbert.com.json ├── longstoryshort.json ├── nichtlustig.de.json ├── ruthe.de.json ├── smbc-comics.com.json └── zits.json ├── feedme-crawler └── main.go ├── feedme-server └── main.go ├── feedme.go └── scripts └── postgresql_ddl.sql /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean fmt install lint 2 | 3 | clean: 4 | go clean github.com/zimmski/feedme/backend 5 | go clean github.com/zimmski/feedme/feedme-crawler 6 | go clean github.com/zimmski/feedme/feedme-server 7 | fmt: 8 | go tool vet -all=true -v=true . 9 | gofmt -l -w -tabs=true . 10 | install: 11 | go install github.com/zimmski/feedme/backend 12 | go install github.com/zimmski/feedme/feedme-crawler 13 | go install github.com/zimmski/feedme/feedme-server 14 | lint: 15 | golint . 16 | go tool vet -all=true -v=true . 17 | 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # feedme 2 | 3 | feedme is an infrastructure for creating Atom and RSS feeds from any website. It consists of a crawler and a web service. The crawler fetches feed definitions like the website URL and what to fetch from the website out of a database backend, crawls the website, transforms the crawled information into consistent feed items and stores them in the database. The web service generates a valid Atom and RSS feed using these items of a given feed. 4 | 5 | ## Requirements 6 | 7 | * Go 1.2 or higher 8 | * PostgreSQL as the database backend 9 | 10 | ## Set up feedme 11 | 12 | *Please note that the following commands use the users's default PostgreSQL user, database and password. If you want to use different login settings you have to specify them using the corresponding psql, [feedme-crawler](#feedme-crawler) and [feedme-server](#feedme-server) arguments* 13 | 14 | Fetch feedme with the go command and install all dependencies. 15 | 16 | ```bash 17 | go get github.com/zimmski/feedme 18 | cd $GOPATH/src/github.com/zimmski/feedme 19 | go get ./... 20 | ``` 21 | 22 | Initialize the database backend. Make sure that this works without errors. 23 | 24 | ```bash 25 | psql < $GOPATH/src/github.com/zimmski/feedme/scripts/postgresql_ddl.sql 26 | ``` 27 | 28 | Create binaries for the crawler and server. 29 | 30 | ```bash 31 | go install github.com/zimmski/feedme/feedme-crawler 32 | go install github.com/zimmski/feedme/feedme-server 33 | ``` 34 | 35 | *Please note that you could also use just the usual go run to start the crawler or server.* 36 | 37 | Start the server 38 | 39 | ```bash 40 | $GOBIN/feedme-server --enable-logging 41 | ``` 42 | 43 | Insert your feeds with the transformation definitions into the database and execute the crawler for the first time. Make sure that this works without errors. 44 | 45 | ```bash 46 | $GOBIN/feedme-crawler --verbose 47 | ``` 48 | 49 | Test your feeds with your RSS reader or browser by going to http://localhost:9090/, http://localhost:9090/yourfeedname/atom and http://localhost:9090/yourfeedname/rss. If everything works you can run the crawler as cron job to update your feeds automatically. 50 | 51 | ## Add feeds to the database 52 | 53 | Currently there is no UI for modifying feed definitions. You have to insert and update them manually through your favorite PostgreSQL interface. In the folder /examples you can find examples for transformations. 54 | 55 | For example [/examples/dilbert.com.json](/examples/dilbert.com.json) holds the transformation for the divine Dilbert comic. This definition will add the current comic image of the home page of dilbert.com if it does not already exists in the database. 56 | 57 | You can add the dilbert.com feed to your database by issuing the following SQL statement. 58 | 59 | ```SQL 60 | INSERT INTO feeds(name, url, transform) VALUES ('dilbert.com', 'http://dilbert.com/', '{"items": [{"search": "div.STR_Image","do": [{"find": "a","do": [{"attr": "href","do": [{"regex": "/strips/comic/(.+)/","matches": [{"name": "date","type": "string"}]}]}]},{"find": "img","do": [{"attr": "src","do": [{"copy": true,"name": "image","type": "string"}]}]}]}],"transform": {"title": "Strip {{.date}}","uri": "/strips/comic/{{.date}}/","description": " Strip {{.date}}"}}'); 61 | ``` 62 | 63 | The name column of the feeds table must be unique and states the identifying name of the feed for the feed URL of the web service. The url column defines which page should be fetched and transformed for the feed generation. The transform column holds the transform definition. 64 | 65 | ## Transformation (definition) 66 | 67 | A transformation definition uses JSON as its format. The base consists of the two elements items (an array of selectors) and transform (a hash of templates for the feed item fields). 68 | 69 | An empty transformation definition: 70 | 71 | ```json 72 | { 73 | "items": [ 74 | ], 75 | "transform": { 76 | } 77 | } 78 | ``` 79 | 80 | The transform hash holds key-value pairs of templates. For example the following transform hash would assign all found feed items the title "News title", the uri "/the/news/uri" and the description "This just in. An important news.": 81 | 82 | ```json 83 | { 84 | "items": [ 85 | ], 86 | "transform": { 87 | "title": "News title", 88 | "uri": "/the/news/uri", 89 | "description": "This just in. An important news." 90 | } 91 | } 92 | ``` 93 | 94 | A definition for the transform element does not make much sense without items that can be transformed. The items element defines selectors for selecting DOM elements from the feed's URL and also holds definitions on what information should be stored. Stored information can be accessed by the transform element through their identifiers. 95 | 96 | For example 97 | ```json 98 | { 99 | "items": [ 100 | ], 101 | "transform": { 102 | "title": "News {{.title}}", 103 | "uri": "/images/{{.image}}", 104 | "description": "The title {{.title}} belongs to the image {{.image}}." 105 | } 106 | } 107 | ``` 108 | would access the stored informations of title and image for each feed item. 109 | 110 | The following identifiers are defined per default and can be overwritten 111 | 112 | * date - The current date formatted in ISO 8601 113 | 114 | ### Selecting nodes 115 | 116 | Selecting nodes can be nested through their do element and can contain storing nodes. 117 | 118 | **search** 119 | 120 | Search uses a CSS selector to select many elements. 121 | 122 | ```json 123 | { 124 | "search": "CSS selector", 125 | "do": [ 126 | ] 127 | } 128 | ``` 129 | 130 | **find** 131 | 132 | Find uses a CSS selector to select at most one element. 133 | 134 | ```json 135 | { 136 | "find": "CSS selector", 137 | "do": [ 138 | ] 139 | } 140 | ``` 141 | 142 | **attr** 143 | 144 | Attr selects exactly one attribute of the parents element and can only contain storing nodes in its do element. 145 | 146 | ```json 147 | { 148 | "search": "attribute name", 149 | "do": [ 150 | ] 151 | } 152 | ``` 153 | 154 | **text** 155 | 156 | Text extracts the combined text contents of the current node and its children. 157 | 158 | ```json 159 | { 160 | "text": true, 161 | "do": [ 162 | ] 163 | } 164 | ``` 165 | 166 | ### Storing nodes 167 | 168 | **copy** 169 | 170 | Copy copies the attribute value direclty for the feed item transformation. 171 | 172 | ```json 173 | { 174 | "copy": true, 175 | "name": "storing name", 176 | "type": "int or string, which is the type of the value" 177 | } 178 | ``` 179 | 180 | **regex** 181 | 182 | Regex uses its regex string on the parents attribute value to parse it and store matching groups for the feed item transformation. The matches element holds an array of name-type pairs for storing item information and must match the count of the matching groups of the regex. 183 | 184 | ```json 185 | { 186 | "regex": "regex with capturing groups", 187 | "matches": [ 188 | { 189 | "name": "storing name of first match", 190 | "type": "int or string, which is the type of the value" 191 | } 192 | ] 193 | } 194 | ``` 195 | 196 | For example 197 | 198 | ```json 199 | { 200 | "regex": "id=(\\d+)&image=(.+)", 201 | "matches": [ 202 | { 203 | "name": "id", 204 | "type": "int" 205 | }, 206 | { 207 | "name": "image", 208 | "type": "string" 209 | } 210 | ] 211 | } 212 | ``` 213 | 214 | would parse the value of the given attribute and store the parsed values into id and image for transforming the feed items. 215 | 216 | ### Example file 217 | 218 | ```json 219 | { 220 | "items": [ 221 | { 222 | "search": "div.news", 223 | "do": [ 224 | { 225 | "find": "a", 226 | "do": [ 227 | { 228 | "attr": "href", 229 | "do": [ 230 | { 231 | "regex": "id=(\\d+)", 232 | "matches": [ 233 | { 234 | "name": "id", 235 | "type": "int" 236 | } 237 | ] 238 | } 239 | ] 240 | } 241 | ] 242 | }, 243 | { 244 | "find": "img", 245 | "do": [ 246 | { 247 | "attr": "src", 248 | "do": [ 249 | { 250 | "copy": true, 251 | "name": "image", 252 | "type": "string" 253 | } 254 | ] 255 | } 256 | ] 257 | } 258 | ] 259 | } 260 | ], 261 | "transform": { 262 | "title": "News {{.id}}", 263 | "uri": "/news/{{.id}}", 264 | "description": "" 265 | } 266 | } 267 | ``` 268 | 269 | This transformation selects all div.news elements of the fetched page and looks into every div.news element for the first a element and img element. The href attribute of the a element gets parsed by a regex for the news id which is stored with the identifier id. The src attribute of the img element gets copied into the image identifier. 270 | 271 | Every div.news elements represents a feed item as the selection for div.news elements is in the root array of the items transformation. All stored identifiers will be given to the templates of the fields in the transform hash. After inserting their information into the feed item field values the final values are stored into the database. 272 | 273 | ## feedme-crawler 274 | 275 | **CLI arguments** 276 | 277 | ``` 278 | --config= INI config file 279 | --config-write= Write all arguments to an INI config file or to STDOUT with "-" as argument 280 | --feed= Fetch only the feed with this name (can be used more than once) 281 | --list-feeds List all available feed names 282 | --max-idle-conns= Max idle connections of the database (10) 283 | --max-open-conns= Max open connections of the database (10) 284 | -s, --spec= The database connection spec (dbname=feedme sslmode=disable) 285 | --test-file= Instead of fetching feed URLs the content of this file is transformed. The result is not saved into the database 286 | -t, --threads= Thread count for processing (Default is the systems CPU count) 287 | -w, --workers= Worker count for processing feeds (1) 288 | -v, --verbose Print what is going on 289 | 290 | -h, --help Show this help message 291 | ``` 292 | 293 | The crawler fetches per default all defined feeds. By using the --feed argument, which can be used more than once, it is possible to fetch only specific feeds. The --spec argument uses the connection string parameter of the excellent pg package. Please have a look at the [official documentation](http://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters) if you need different settings. 294 | 295 | **Configuration file** 296 | 297 | All CLI arguments can be defined via a INI configuration file which can be initialized via the --config-write argument and then used via the --config argument. 298 | 299 | *Please note that CLI arguments overwrite settings from the configuration file* 300 | 301 | **Environment variables** 302 | ``` 303 | FEEDMESPEC sets the --spec CLI argument through the environment 304 | ``` 305 | *Please note that CLI arguments overwrite settings from the environment and the environment overwrites settings from the configuration file.* 306 | 307 | ## feedme-server 308 | 309 | **CLI arguments** 310 | 311 | ``` 312 | --config= INI config file 313 | --config-write= Write all arguments to an INI config file or to STDOUT with "-" as argument 314 | --enable-logging Enable request logging 315 | --max-idle-conns= Max idle connections of the database (10) 316 | --max-open-conns= Max open connections of the database (10) 317 | -p, --port= HTTP port of the server (9090) 318 | -s, --spec= The database connection spec (dbname=feedme sslmode=disable) 319 | 320 | -h, --help Show this help message 321 | ``` 322 | 323 | The --spec argument uses the connection string parameter of the excellent pg package. Please have a look at the [official documentation](http://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters) if you need different settings. 324 | 325 | **Configuration file** 326 | 327 | All CLI arguments can be defined via a INI configuration file which can be initialized via the --config-write argument and then used via the --config argument. 328 | 329 | **Environment variables** 330 | ``` 331 | FEEDMESPEC sets the --spec CLI argument through the environment 332 | ``` 333 | *Please note that CLI arguments overwrite settings from the environment and the environment overwrites settings from the configuration file.* 334 | 335 | **Routes** 336 | 337 | * / - Displays all feed definitions via JSON. 338 | * /<feed name>/atom - Displays an Atom feed for the given feed. 339 | * /<feed name>/rss - Displays an RSS feed for the given feed. 340 | -------------------------------------------------------------------------------- /backend/backend.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/zimmski/feedme" 7 | ) 8 | 9 | type Backend interface { 10 | Init(params Parameters) error 11 | 12 | CreateItems(feed *feedme.Feed, items []feedme.Item) error 13 | 14 | FindFeed(feedName string) (*feedme.Feed, error) 15 | SearchFeeds(feedNames []string) ([]feedme.Feed, error) 16 | 17 | FindItemByURI(feed *feedme.Feed, uri string) (*feedme.Item, error) 18 | SearchItems(feed *feedme.Feed) ([]feedme.Item, error) 19 | } 20 | 21 | type Parameters struct { 22 | Spec string 23 | MaxIdleConns int 24 | MaxOpenConns int 25 | } 26 | 27 | func NewBackend(name string) (Backend, error) { 28 | if name == "postgresql" { 29 | return NewBackendPostgresql(), nil 30 | } 31 | 32 | return nil, fmt.Errorf("unknown backend \"%s\"", name) 33 | } 34 | -------------------------------------------------------------------------------- /backend/postgresql.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/jmoiron/sqlx" 9 | _ "github.com/lib/pq" 10 | 11 | "github.com/zimmski/feedme" 12 | ) 13 | 14 | type Postgresql struct { 15 | Db *sqlx.DB 16 | } 17 | 18 | func NewBackendPostgresql() Backend { 19 | return new(Postgresql) 20 | } 21 | 22 | func (p *Postgresql) Init(params Parameters) error { 23 | var err error 24 | 25 | p.Db, err = sqlx.Connect("postgres", params.Spec) 26 | if err != nil { 27 | return fmt.Errorf("cannot connect to database: %v", err) 28 | } 29 | 30 | err = p.Db.Ping() 31 | if err != nil { 32 | return fmt.Errorf("cannot ping database: %v", err) 33 | } 34 | 35 | p.Db.SetMaxIdleConns(params.MaxIdleConns) 36 | p.Db.SetMaxOpenConns(params.MaxOpenConns) 37 | 38 | return nil 39 | } 40 | 41 | func (p *Postgresql) CreateItems(feed *feedme.Feed, items []feedme.Item) error { 42 | var err error 43 | 44 | tx, err := p.Db.Begin() 45 | if err != nil { 46 | return err 47 | } 48 | 49 | for _, i := range items { 50 | _, err = tx.Exec("INSERT INTO items(feed, title, uri, description, created) SELECT $1, $2, $3, $4, CURRENT_TIMESTAMP WHERE NOT EXISTS(SELECT id FROM items WHERE feed = $1 AND title = $2 AND uri = $3 AND description = $4)", feed.ID, i.Title, i.URI, i.Description) 51 | if err != nil { 52 | return err 53 | } 54 | } 55 | 56 | err = tx.Commit() 57 | if err != nil { 58 | return err 59 | } 60 | 61 | return nil 62 | } 63 | 64 | func (p *Postgresql) FindFeed(feedName string) (*feedme.Feed, error) { 65 | feed := &feedme.Feed{} 66 | 67 | err := p.Db.Get(feed, "SELECT * FROM feeds WHERE name = $1", feedName) 68 | if err == sql.ErrNoRows { 69 | return nil, nil 70 | } 71 | 72 | return feed, err 73 | } 74 | 75 | func (p *Postgresql) SearchFeeds(feedNames []string) ([]feedme.Feed, error) { 76 | feeds := []feedme.Feed{} 77 | 78 | var params []interface{} 79 | filter := "" 80 | 81 | if feedNames != nil && len(feedNames) != 0 { 82 | a := make([]string, len(feedNames)) 83 | 84 | for i, feedName := range feedNames { 85 | a[i] = fmt.Sprintf("$%d", i+1) 86 | params = append(params, feedName) 87 | } 88 | 89 | filter = "WHERE name IN (" + strings.Join(a, ",") + ")" 90 | } 91 | 92 | err := p.Db.Select(&feeds, "SELECT * FROM feeds "+filter+"ORDER BY name", params...) 93 | if err == sql.ErrNoRows { 94 | return nil, nil 95 | } 96 | 97 | return feeds, err 98 | } 99 | 100 | func (p *Postgresql) FindItemByURI(feed *feedme.Feed, uri string) (*feedme.Item, error) { 101 | item := &feedme.Item{} 102 | 103 | err := p.Db.Get(item, "SELECT * FROM items WHERE feed = $1 AND uri = $2", feed.ID, uri) 104 | if err == sql.ErrNoRows { 105 | return nil, nil 106 | } 107 | 108 | return item, err 109 | } 110 | 111 | func (p *Postgresql) SearchItems(feed *feedme.Feed) ([]feedme.Item, error) { 112 | items := []feedme.Item{} 113 | 114 | err := p.Db.Select(&items, "SELECT * FROM items WHERE feed = $1 ORDER BY created DESC LIMIT 10", feed.ID) 115 | if err == sql.ErrNoRows { 116 | return nil, nil 117 | } 118 | 119 | return items, err 120 | 121 | } 122 | -------------------------------------------------------------------------------- /examples/7days.heise.de.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#archiv_woche ul li", 5 | "do": [ 6 | { 7 | "find": "a", 8 | "do": [ 9 | { 10 | "text": true, 11 | "do": [ 12 | { 13 | "copy": true, 14 | "name": "title", 15 | "type": "string" 16 | } 17 | ] 18 | }, 19 | { 20 | "attr": "href", 21 | "do": [ 22 | { 23 | "copy": true, 24 | "name": "uri", 25 | "type": "string" 26 | } 27 | ] 28 | } 29 | ] 30 | } 31 | ] 32 | } 33 | ], 34 | "transform": { 35 | "title": "{{.title}}", 36 | "uri": "{{.uri}}/", 37 | "description": "{{.title}}" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # feedme examples 2 | 3 | This folder holds examples for different websites. If you like to add one please make a pull request. 4 | 5 | - [7days.heise.de - http://www.heise.de/newsticker/](7days.heise.de.json) 6 | - [der-flix http://www.der-flix.de](der-flix.de.json) 7 | - [der-flix.de-schoene-toechter http://www.der-flix.de/schoene-toechter.html](der-flix.de-schoene-toechter.json) 8 | - [dilbert.com - http://dilbert.com/](dilbert.com.json) 9 | - [long story short - http://www.arcamax.com/thefunnies/longstoryshort/](longstoryshort.json) 10 | - [nichtlustig.de - http://nichtlustig.de/main.html](nichtlustig.de.json) 11 | - [ruthe.de - http://ruthe.de/](ruthe.de.json) 12 | - [smbc-comics.com - http://www.smbc-comics.com/](smbc-comics.com.json) 13 | - [zits - http://www.arcamax.com/thefunnies/zits/](zits.json) 14 | -------------------------------------------------------------------------------- /examples/der-flix.de-schoene-toechter.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#mod_schoenetoechter_gallery", 5 | "do": [ 6 | { 7 | "find": "a", 8 | "do": [ 9 | { 10 | "attr": "href", 11 | "do": [ 12 | { 13 | "regex": "\\?(.+)$", 14 | "matches": [ 15 | { 16 | "name": "link", 17 | "type": "string" 18 | } 19 | ] 20 | } 21 | ] 22 | } 23 | ] 24 | }, 25 | { 26 | "find": "img", 27 | "do": [ 28 | { 29 | "attr": "alt", 30 | "do": [ 31 | { 32 | "regex": "^(.+)$", 33 | "matches": [ 34 | { 35 | "name": "titel", 36 | "type": "string" 37 | } 38 | ] 39 | } 40 | ] 41 | }, 42 | { 43 | "attr": "src", 44 | "do": [ 45 | { 46 | "regex": "^(.+)$", 47 | "matches": [ 48 | { 49 | "name": "image", 50 | "type": "string" 51 | } 52 | ] 53 | } 54 | ] 55 | } 56 | ] 57 | } 58 | ] 59 | } 60 | ], 61 | "transform": { 62 | "title": "{{.titel}}", 63 | "uri": "?{{.link}}}", 64 | "description": " Strip {{.titel}}" 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /examples/der-flix.de.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#mod_heldentage", 5 | "do": [ 6 | { 7 | "find": "img[alt=Heldentag]", 8 | "do": [ 9 | { 10 | "attr": "src", 11 | "do": [ 12 | { 13 | "regex": "Tag_(\\d+).jpg$", 14 | "matches": [ 15 | { 16 | "name": "number", 17 | "type": "string" 18 | } 19 | ] 20 | } 21 | ] 22 | }, 23 | { 24 | "attr": "src", 25 | "do": [ 26 | { 27 | "regex": "^(.+)$", 28 | "matches": [ 29 | { 30 | "name": "image", 31 | "type": "string" 32 | } 33 | ] 34 | } 35 | ] 36 | } 37 | ] 38 | } 39 | ] 40 | } 41 | ], 42 | "transform": { 43 | "title": "Heldentag {{.number}}", 44 | "uri": "http://www.der-flix.de{{.image}}", 45 | "description": "" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /examples/dilbert.com.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "div.comic-item-container", 5 | "do": [ 6 | { 7 | "find": "a.img-comic-link", 8 | "do": [ 9 | { 10 | "attr": "title", 11 | "do": [ 12 | { 13 | "regex": "Click to see the comic strip (.*)", 14 | "matches": [ 15 | { 16 | "name": "title", 17 | "type": "string" 18 | } 19 | ] 20 | } 21 | ] 22 | }, 23 | { 24 | "attr": "href", 25 | "do": [ 26 | { 27 | "regex": "http://dilbert\\.com(.+)", 28 | "matches": [ 29 | { 30 | "name": "uri", 31 | "type": "string" 32 | } 33 | ] 34 | }, 35 | { 36 | "regex": "http://dilbert\\.com/strip/(.+)", 37 | "matches": [ 38 | { 39 | "name": "date", 40 | "type": "string" 41 | } 42 | ] 43 | } 44 | ] 45 | } 46 | ] 47 | }, 48 | { 49 | "find": "img.img-comic", 50 | "do": [ 51 | { 52 | "attr": "src", 53 | "do": [ 54 | { 55 | "copy": true, 56 | "name": "image", 57 | "type": "string" 58 | } 59 | ] 60 | } 61 | ] 62 | } 63 | ] 64 | } 65 | ], 66 | "transform": { 67 | "title": "Strip {{.date}} - {{.title}}", 68 | "uri": "{{.uri}}", 69 | "description": " Strip {{.date}}" 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /examples/longstoryshort.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#comic-zoom", 5 | "do": [ 6 | { 7 | "attr": "src", 8 | "do": [ 9 | { 10 | "copy": true, 11 | "name": "image", 12 | "type": "string" 13 | } 14 | ] 15 | } 16 | ] 17 | } 18 | ], 19 | "transform": { 20 | "title": "Strip {{.date}}", 21 | "uri": "http://www.arcamax.com/{{.image}}}", 22 | "description": " Strip {{.titel}}" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/nichtlustig.de.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "find": "link[rel=image_src]", 5 | "do": [ 6 | { 7 | "attr": "href", 8 | "do": [ 9 | { 10 | "regex": "/(\\d+).jpg", 11 | "matches": [ 12 | { 13 | "name": "date", 14 | "type": "int" 15 | } 16 | ] 17 | } 18 | ] 19 | } 20 | ] 21 | } 22 | ], 23 | "transform": { 24 | "title": "Strip {{.date}}", 25 | "uri": "/toondb/{{.date}}.html", 26 | "description": " Strip {{.date}}" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /examples/ruthe.de.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#cartoon", 5 | "do": [ 6 | { 7 | "find": "a", 8 | "do": [ 9 | { 10 | "attr": "href", 11 | "do": [ 12 | { 13 | "regex": "archiv\/(\\d+)\/", 14 | "matches": [ 15 | { 16 | "name": "id", 17 | "type": "int" 18 | } 19 | ] 20 | } 21 | ] 22 | } 23 | ] 24 | }, 25 | { 26 | "find": "img", 27 | "do": [ 28 | { 29 | "attr": "src", 30 | "do": [ 31 | { 32 | "copy": true, 33 | "name": "image", 34 | "type": "string" 35 | } 36 | ] 37 | } 38 | ] 39 | } 40 | ] 41 | } 42 | ], 43 | "transform": { 44 | "title": "Strip {{.id}}", 45 | "uri": "http://ruthe.de/cartoon/{{.id}}/datum/asc/", 46 | "description": " Strip {{.id}}" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /examples/smbc-comics.com.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#comic", 5 | "do": [ 6 | { 7 | "attr": "src", 8 | "do": [ 9 | { 10 | "copy": true, 11 | "name": "image", 12 | "type": "string" 13 | }, 14 | { 15 | "regex": "/([^/]+)\\.[[:alpha:]]+\\z", 16 | "matches": [ 17 | { 18 | "name": "title", 19 | "type": "string" 20 | } 21 | ] 22 | } 23 | ] 24 | }, 25 | { 26 | "attr": "title", 27 | "do": [ 28 | { 29 | "copy": true, 30 | "name": "title", 31 | "type": "string" 32 | } 33 | ] 34 | } 35 | ] 36 | } 37 | ], 38 | "transform": { 39 | "title": "Strip {{.title}}", 40 | "uri": "{{.image}}", 41 | "description": " Strip {{.title}}" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /examples/zits.json: -------------------------------------------------------------------------------- 1 | { 2 | "items": [ 3 | { 4 | "search": "#comic-zoom", 5 | "do": [ 6 | { 7 | "attr": "src", 8 | "do": [ 9 | { 10 | "copy": true, 11 | "name": "image", 12 | "type": "string" 13 | } 14 | ] 15 | } 16 | ] 17 | } 18 | ], 19 | "transform": { 20 | "title": "Strip {{.date}}", 21 | "uri": "http://www.arcamax.com{{.image}}", 22 | "description": " Strip {{.date}}" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /feedme-crawler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "regexp" 10 | "runtime" 11 | "strconv" 12 | "strings" 13 | "text/template" 14 | "time" 15 | 16 | "github.com/PuerkitoBio/goquery" 17 | "github.com/jessevdk/go-flags" 18 | 19 | "github.com/zimmski/feedme" 20 | "github.com/zimmski/feedme/backend" 21 | ) 22 | 23 | const ( 24 | ReturnOk = iota 25 | ReturnHelp 26 | ) 27 | 28 | var db backend.Backend 29 | var opts struct { 30 | Config func(s string) error `long:"config" description:"INI config file" no-ini:"true"` 31 | ConfigWrite string `long:"config-write" description:"Write all arguments to an INI config file or to STDOUT with \"-\" as argument" no-ini:"true"` 32 | Feeds []string `long:"feed" description:"Fetch only the feed with this name (can be used more than once)"` 33 | ListFeeds bool `long:"list-feeds" description:"List all available feed names" no-ini:"true"` 34 | MaxIdleConns int `long:"max-idle-conns" default:"10" description:"Max idle connections of the database"` 35 | MaxOpenConns int `long:"max-open-conns" default:"10" description:"Max open connections of the database"` 36 | Spec string `short:"s" long:"spec" default:"dbname=feedme sslmode=disable" description:"The database connection spec"` 37 | TestFile string `long:"test-file" description:"Instead of fetching feed URLs the content of this file is transformed. The result is not saved into the database" no-ini:"true"` 38 | Threads int `short:"t" long:"threads" description:"Thread count for processing (Default is the systems CPU count)"` 39 | Workers int `short:"w" long:"workers" default:"1" description:"Worker count for processing feeds"` 40 | Verbose bool `short:"v" long:"verbose" description:"Print what is going on"` 41 | 42 | configFile string 43 | testFile string 44 | } 45 | 46 | func main() { 47 | var err error 48 | 49 | p := flags.NewNamedParser("feedme-crawler", flags.HelpFlag) 50 | p.ShortDescription = "The feedme crawler" 51 | 52 | opts.Config = func(s string) error { 53 | ini := flags.NewIniParser(p) 54 | 55 | opts.configFile = s 56 | 57 | return ini.ParseFile(s) 58 | } 59 | 60 | p.AddGroup("Crawler", "Crawler arguments", &opts) 61 | 62 | _, err = p.ParseArgs(os.Args) 63 | if err != nil { 64 | if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { 65 | panic(err) 66 | } else { 67 | p.WriteHelp(os.Stdout) 68 | 69 | os.Exit(ReturnHelp) 70 | } 71 | } 72 | 73 | if env := os.Getenv("FEEDMESPEC"); env != "" { 74 | opts.Spec = env 75 | } 76 | 77 | if opts.ConfigWrite != "" { 78 | ini := flags.NewIniParser(p) 79 | 80 | var iniOptions flags.IniOptions = flags.IniIncludeComments | flags.IniIncludeDefaults | flags.IniCommentDefaults 81 | 82 | if opts.ConfigWrite == "-" { 83 | (ini.Write(os.Stdout, iniOptions)) 84 | } else { 85 | ini.WriteFile(opts.ConfigWrite, iniOptions) 86 | } 87 | 88 | os.Exit(ReturnOk) 89 | } 90 | 91 | if opts.MaxIdleConns < 0 { 92 | opts.MaxIdleConns = 0 93 | } 94 | 95 | if opts.MaxOpenConns <= 0 { 96 | opts.MaxOpenConns = 1 97 | } 98 | 99 | if opts.Threads <= 0 { 100 | opts.Threads = runtime.NumCPU() 101 | } 102 | 103 | if opts.Workers < 0 { 104 | opts.Workers = 1 105 | } 106 | 107 | runtime.GOMAXPROCS(opts.Threads) 108 | 109 | if opts.TestFile != "" { 110 | c, err := ioutil.ReadFile(opts.TestFile) 111 | if err != nil { 112 | panic(err) 113 | } 114 | 115 | opts.testFile = string(c) 116 | } 117 | 118 | db, err = backend.NewBackend("postgresql") 119 | if err != nil { 120 | panic(err) 121 | } 122 | 123 | err = db.Init(backend.Parameters{ 124 | Spec: opts.Spec, 125 | MaxIdleConns: opts.MaxIdleConns, 126 | MaxOpenConns: opts.MaxOpenConns, 127 | }) 128 | if err != nil { 129 | panic(err) 130 | } 131 | 132 | if opts.ListFeeds { 133 | feeds, err := db.SearchFeeds(nil) 134 | if err != nil { 135 | panic(err) 136 | } 137 | 138 | for _, feed := range feeds { 139 | fmt.Println(feed.Name) 140 | } 141 | } else { 142 | feeds, err := db.SearchFeeds(opts.Feeds) 143 | if err != nil { 144 | panic(err) 145 | } 146 | 147 | feedQueue := make(chan feedme.Feed) 148 | consumeFeeds := make(chan bool, len(feeds)) 149 | 150 | for i := 0; i < opts.Workers; i++ { 151 | go func(id int, feedQueue <-chan feedme.Feed, consumeFeeds chan<- bool) { 152 | for { 153 | select { 154 | case feed, ok := <-feedQueue: 155 | if ok { 156 | err := processFeed(&feed, id) 157 | if err != nil { 158 | logErrorWorker(&feed, id, err.Error()) 159 | } 160 | 161 | consumeFeeds <- true 162 | } else { 163 | return 164 | } 165 | } 166 | } 167 | }(i, feedQueue, consumeFeeds) 168 | } 169 | 170 | for _, feed := range feeds { 171 | feedQueue <- feed 172 | } 173 | 174 | for i := 0; i < len(feeds); i++ { 175 | <-consumeFeeds 176 | } 177 | 178 | close(feedQueue) 179 | } 180 | 181 | os.Exit(ReturnOk) 182 | } 183 | 184 | func processFeed(feed *feedme.Feed, workerID int) error { 185 | var err error 186 | 187 | logVerboseWorker(feed, workerID, "fetch feed %s from %s", feed.Name, feed.URL) 188 | 189 | var raw map[string]*json.RawMessage 190 | err = json.Unmarshal([]byte(feed.Transform), &raw) 191 | if err != nil { 192 | return fmt.Errorf("cannot parse transform JSON: %s", err.Error()) 193 | } 194 | 195 | var transform map[string]string 196 | err = json.Unmarshal(*raw["transform"], &transform) 197 | if err != nil { 198 | return fmt.Errorf("cannot parse transform element: %s", err.Error()) 199 | } 200 | 201 | transformTemplates := make(map[string]*template.Template) 202 | for name, tem := range transform { 203 | transformTemplates[name], err = template.New(name).Parse(tem) 204 | if err != nil { 205 | return fmt.Errorf("cannot create transform template: %s", err.Error()) 206 | } 207 | } 208 | 209 | jsonItems, err := jsonArray(raw["items"]) 210 | if err != nil { 211 | return fmt.Errorf("cannot parse items element: %s", err.Error()) 212 | } 213 | 214 | var doc *goquery.Document 215 | 216 | if opts.TestFile != "" { 217 | logVerboseWorker(feed, workerID, "use test file") 218 | 219 | doc, err = goquery.NewDocumentFromReader(strings.NewReader(opts.testFile)) 220 | if err != nil { 221 | return fmt.Errorf("cannot process test file: %s", err.Error()) 222 | } 223 | } else { 224 | doc, err = goquery.NewDocument(feed.URL) 225 | if err != nil { 226 | return fmt.Errorf("cannot open URL: %s", err.Error()) 227 | } 228 | } 229 | 230 | var items []feedme.Item 231 | 232 | for _, rawTransform := range jsonItems { 233 | itemValues, err := crawlSelect(doc.Selection, rawTransform, nil) 234 | if err != nil { 235 | return fmt.Errorf("cannot transform website: %s", err.Error()) 236 | } 237 | 238 | if len(itemValues[len(itemValues)-1]) == 0 { 239 | logVerboseWorker(feed, workerID, "Nothing to transform") 240 | 241 | continue 242 | } 243 | 244 | for _, itemValue := range itemValues { 245 | feedItem := feedme.Item{} 246 | 247 | if _, ok := itemValue["date"]; !ok { 248 | itemValue["date"] = time.Now().Format("2006-01-02") 249 | } 250 | 251 | for name, t := range transformTemplates { 252 | var out bytes.Buffer 253 | t.Execute(&out, itemValue) 254 | s := out.String() 255 | 256 | switch name { 257 | case "description": 258 | feedItem.Description = s 259 | case "title": 260 | feedItem.Title = s 261 | case "uri": 262 | feedItem.URI = s 263 | default: 264 | return fmt.Errorf("unkown field %s", name) 265 | } 266 | } 267 | 268 | if feedItem.Title != "" && feedItem.URI != "" { 269 | if item, err := db.FindItemByURI(feed, feedItem.URI); err != nil { 270 | logVerboseWorker(feed, workerID, "error finding item %+v in feed %+v: %v", feedItem, feed, err) 271 | } else if item != nil { 272 | logVerboseWorker(feed, workerID, "item %+v already exists", feedItem) 273 | } else { 274 | logVerboseWorker(feed, workerID, "found item %+v", feedItem) 275 | 276 | items = append(items, feedItem) 277 | } 278 | } 279 | } 280 | } 281 | 282 | if opts.TestFile == "" { 283 | err = db.CreateItems(feed, items) 284 | if err != nil { 285 | return fmt.Errorf("cannot insert items into database: %s", err.Error()) 286 | } 287 | } 288 | 289 | return nil 290 | } 291 | 292 | func crawlSelect(element *goquery.Selection, rawTransform map[string]*json.RawMessage, itemValues []map[string]interface{}) ([]map[string]interface{}, error) { 293 | baseSelection := false 294 | 295 | if itemValues == nil { 296 | baseSelection = true 297 | 298 | itemValues = make([]map[string]interface{}, 1) 299 | // TODO finde out why this is needed as itemValues with make of length 1 has already a map shown printed with %+v. But it is nil if it is accessed 300 | itemValues[0] = make(map[string]interface{}) 301 | } 302 | 303 | if rawSelector, ok := rawTransform["search"]; ok { 304 | selector, do, err := jsonSelectNode(rawTransform, rawSelector) 305 | if err != nil { 306 | return nil, err 307 | } 308 | 309 | nodes := element.Find(selector) 310 | 311 | nodes.Each(func(i int, s *goquery.Selection) { 312 | for _, d := range do { 313 | _, err = crawlSelect(s, d, itemValues) 314 | if err != nil { 315 | return 316 | } 317 | } 318 | 319 | if baseSelection && i != nodes.Length()-1 && len(itemValues[len(itemValues)-1]) != 0 { 320 | itemValues = append(itemValues, make(map[string]interface{})) 321 | } 322 | }) 323 | if err != nil { 324 | return nil, err 325 | } 326 | } else if rawSelector, ok := rawTransform["find"]; ok { 327 | selector, do, err := jsonSelectNode(rawTransform, rawSelector) 328 | if err != nil { 329 | return nil, err 330 | } 331 | 332 | s := element.Find(selector) 333 | if s == nil { 334 | return nil, fmt.Errorf("no element %s found", selector) 335 | } 336 | 337 | for _, d := range do { 338 | _, err = crawlSelect(s, d, itemValues) 339 | if err != nil { 340 | return nil, err 341 | } 342 | } 343 | } else if rawSelector, ok := rawTransform["attr"]; ok { 344 | selector, do, err := jsonSelectNode(rawTransform, rawSelector) 345 | if err != nil { 346 | return nil, err 347 | } 348 | 349 | attrValue, ok := element.Attr(selector) 350 | if !ok { 351 | return nil, fmt.Errorf("no attribute %s found", selector) 352 | } 353 | 354 | for _, d := range do { 355 | err = crawlStore(attrValue, d, itemValues[len(itemValues)-1]) 356 | if err != nil { 357 | return nil, err 358 | } 359 | } 360 | } else if _, ok := rawTransform["text"]; ok { 361 | _, do, err := jsonSelectNode(rawTransform, nil) 362 | if err != nil { 363 | return nil, err 364 | } 365 | 366 | text := element.Text() 367 | 368 | for _, d := range do { 369 | err = crawlStore(text, d, itemValues[len(itemValues)-1]) 370 | if err != nil { 371 | return nil, err 372 | } 373 | } 374 | } else { 375 | return nil, fmt.Errorf("do not know how to transform %+v", rawTransform) 376 | } 377 | 378 | return itemValues, nil 379 | } 380 | 381 | func crawlStore(value string, rawTransform map[string]*json.RawMessage, itemValue map[string]interface{}) error { 382 | var err error 383 | 384 | if rawRegex, ok := rawTransform["regex"]; ok { 385 | if _, ok := rawTransform["matches"]; !ok { 386 | return fmt.Errorf("regex node requires a matches attribute") 387 | } 388 | 389 | var transformMatches []map[string]string 390 | err = json.Unmarshal(*rawTransform["matches"], &transformMatches) 391 | if err != nil { 392 | return err 393 | } 394 | 395 | reg, err := jsonString(rawRegex) 396 | if err != nil { 397 | return err 398 | } 399 | 400 | re := regexp.MustCompile(reg) 401 | var matches = re.FindStringSubmatch(value) 402 | 403 | if matches == nil { 404 | return fmt.Errorf("no matches found for %q in %q", reg, value) 405 | } 406 | 407 | if len(matches)-1 != len(transformMatches) { 408 | return fmt.Errorf("unequal match count") 409 | } 410 | 411 | for i := 0; i < len(transformMatches); i++ { 412 | if _, ok := transformMatches[i]["name"]; !ok { 413 | return fmt.Errorf("match needs a name attribute") 414 | } 415 | if _, ok := transformMatches[i]["type"]; !ok { 416 | return fmt.Errorf("match needs a type attribute") 417 | } 418 | 419 | var name = transformMatches[i]["name"] 420 | var typ = transformMatches[i]["type"] 421 | 422 | switch typ { 423 | case "int": 424 | v, _ := strconv.Atoi(matches[i+1]) 425 | 426 | itemValue[name] = v 427 | case "string": 428 | itemValue[name] = matches[i+1] 429 | default: 430 | return fmt.Errorf("unknown type %s", typ) 431 | } 432 | } 433 | } else if _, ok := rawTransform["copy"]; ok { 434 | if _, ok := rawTransform["name"]; !ok { 435 | return fmt.Errorf("copy needs a name attribute") 436 | } 437 | if _, ok := rawTransform["type"]; !ok { 438 | return fmt.Errorf("copy needs a type attribute") 439 | } 440 | 441 | name, err := jsonString(rawTransform["name"]) 442 | if err != nil { 443 | return err 444 | } 445 | 446 | typ, err := jsonString(rawTransform["type"]) 447 | if err != nil { 448 | return err 449 | } 450 | 451 | switch typ { 452 | case "int": 453 | v, _ := strconv.Atoi(value) 454 | 455 | itemValue[name] = v 456 | case "string": 457 | itemValue[name] = value 458 | default: 459 | return fmt.Errorf("unknown type %s", typ) 460 | } 461 | } else { 462 | return fmt.Errorf("do not know how to transform %+v", rawTransform) 463 | } 464 | 465 | return nil 466 | } 467 | 468 | func jsonArray(raw *json.RawMessage) ([]map[string]*json.RawMessage, error) { 469 | var array []map[string]*json.RawMessage 470 | 471 | err := json.Unmarshal(*raw, &array) 472 | if err != nil { 473 | return nil, err 474 | } 475 | 476 | return array, nil 477 | } 478 | 479 | func jsonHash(raw *json.RawMessage) (map[string]*json.RawMessage, error) { 480 | var hash map[string]*json.RawMessage 481 | 482 | err := json.Unmarshal(*raw, &hash) 483 | if err != nil { 484 | return nil, err 485 | } 486 | 487 | return hash, nil 488 | } 489 | 490 | func jsonString(raw *json.RawMessage) (string, error) { 491 | if raw == nil { 492 | return "", nil 493 | } 494 | 495 | var s string 496 | 497 | err := json.Unmarshal(*raw, &s) 498 | if err != nil { 499 | return "", err 500 | } 501 | 502 | return s, nil 503 | } 504 | 505 | func jsonSelectNode(rawTransform map[string]*json.RawMessage, rawSelector *json.RawMessage) (string, []map[string]*json.RawMessage, error) { 506 | selector, err := jsonString(rawSelector) 507 | if err != nil { 508 | return "", nil, err 509 | } 510 | 511 | if _, ok := rawTransform["do"]; !ok { 512 | return "", nil, fmt.Errorf("select node needs a do attribute") 513 | } 514 | 515 | do, err := jsonArray(rawTransform["do"]) 516 | if err != nil { 517 | return "", nil, err 518 | } 519 | 520 | return selector, do, nil 521 | } 522 | 523 | func logError(format string, a ...interface{}) (n int, err error) { 524 | return fmt.Printf("ERROR "+format+"\n", a...) 525 | } 526 | 527 | func logErrorWorker(feed *feedme.Feed, workerID int, format string, a ...interface{}) (n int, err error) { 528 | return logError(fmt.Sprintf("%s [%d] ", feed.Name, workerID)+format, a...) 529 | } 530 | 531 | func logVerbose(format string, a ...interface{}) (n int, err error) { 532 | if !opts.Verbose { 533 | return 0, nil 534 | } 535 | 536 | return fmt.Printf("VERBOSE "+format+"\n", a...) 537 | } 538 | 539 | func logVerboseWorker(feed *feedme.Feed, workerID int, format string, a ...interface{}) (n int, err error) { 540 | return logVerbose(fmt.Sprintf("%s [%d] ", feed.Name, workerID)+format, a...) 541 | } 542 | -------------------------------------------------------------------------------- /feedme-server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | "net/url" 8 | "os" 9 | "reflect" 10 | "regexp" 11 | "strconv" 12 | 13 | "github.com/codegangsta/martini" 14 | "github.com/jessevdk/go-flags" 15 | "github.com/zimmski/feeds" 16 | 17 | "github.com/zimmski/feedme/backend" 18 | ) 19 | 20 | const ( 21 | ReturnOk = iota 22 | ReturnHelp 23 | ) 24 | 25 | type FeedEnum int 26 | 27 | const ( 28 | FeedAtom FeedEnum = iota 29 | FeedRSS 30 | ) 31 | 32 | var opts struct { 33 | Config func(s string) error `long:"config" description:"INI config file" no-ini:"true"` 34 | ConfigWrite string `long:"config-write" description:"Write all arguments to an INI config file or to STDOUT with \"-\" as argument" no-ini:"true"` 35 | Logging bool `long:"enable-logging" description:"Enable request logging"` 36 | MaxIdleConns int `long:"max-idle-conns" default:"10" description:"Max idle connections of the database"` 37 | MaxOpenConns int `long:"max-open-conns" default:"10" description:"Max open connections of the database"` 38 | Port uint `short:"p" long:"port" default:"9090" description:"HTTP port of the server"` 39 | Spec string `short:"s" long:"spec" default:"dbname=feedme sslmode=disable" description:"The database connection spec"` 40 | 41 | configFile string 42 | } 43 | 44 | var db backend.Backend 45 | 46 | func checkError(res http.ResponseWriter, err error) bool { 47 | if err != nil { 48 | panic(err) 49 | } 50 | 51 | return false 52 | } 53 | 54 | func checkNotFound(res http.ResponseWriter, item interface{}) bool { 55 | if item == nil || !reflect.ValueOf(item).Elem().IsValid() { 56 | res.WriteHeader(http.StatusNotFound) 57 | 58 | return true 59 | } 60 | 61 | return false 62 | } 63 | 64 | func handleFeeds(res http.ResponseWriter, req *http.Request) { 65 | var err error 66 | 67 | feeds, err := db.SearchFeeds(nil) 68 | if checkError(res, err) { 69 | return 70 | } 71 | 72 | data, err := json.Marshal(feeds) 73 | if checkError(res, err) { 74 | return 75 | } 76 | 77 | res.WriteHeader(http.StatusOK) 78 | res.Header().Set("Content-Type", "application/json") 79 | res.Write(data) 80 | } 81 | 82 | func getFeedItems(feedName string) (*feeds.Feed, error) { 83 | var err error 84 | 85 | feed, err := db.FindFeed(feedName) 86 | if err != nil { 87 | return nil, err 88 | } 89 | if feed == nil { 90 | return nil, nil 91 | } 92 | 93 | items, err := db.SearchItems(feed) 94 | if err != nil { 95 | return nil, err 96 | } 97 | if items == nil { 98 | return nil, nil 99 | } 100 | 101 | reProtocol := regexp.MustCompile(`[a-zA-Z0-9+\-.]+://`) 102 | 103 | u, err := url.Parse(feed.URL) 104 | if err != nil { 105 | return nil, err 106 | } 107 | u.RawQuery = "" 108 | feedURL := u.String() 109 | if feedURL[len(feedURL)-1] != '/' { 110 | feedURL += "/" 111 | } 112 | u.Path = "" 113 | feedURLWithoutPath := u.String() 114 | 115 | feeder := &feeds.Feed{ 116 | Title: feed.Name, 117 | Link: &feeds.Link{Href: feed.URL}, 118 | } 119 | 120 | for _, i := range items { 121 | if feeder.Updated.IsZero() || feeder.Updated.Before(i.Created) { 122 | feeder.Updated = i.Created 123 | } 124 | 125 | var link string 126 | 127 | if reProtocol.MatchString(i.URI) { 128 | link = i.URI 129 | } else if i.URI[0] == '/' { 130 | link = fmt.Sprintf("%s%s", feedURLWithoutPath, i.URI) 131 | } else { 132 | link = fmt.Sprintf("%s%s", feedURL, i.URI) 133 | } 134 | 135 | feeder.Add(&feeds.Item{ 136 | Id: strconv.Itoa(i.ID), 137 | Title: i.Title, 138 | Link: &feeds.Link{Href: link}, 139 | Description: i.Description, 140 | Created: i.Created, 141 | }) 142 | } 143 | 144 | return feeder, nil 145 | } 146 | 147 | func handleItems(typ FeedEnum, res http.ResponseWriter, req *http.Request, params martini.Params) { 148 | var err error 149 | 150 | feeder, err := getFeedItems(params["feed"]) 151 | if checkError(res, err) { 152 | return 153 | } 154 | if checkNotFound(res, feeder) { 155 | return 156 | } 157 | 158 | var data string 159 | 160 | if typ == FeedAtom { 161 | data, err = feeder.ToAtom() 162 | } else { 163 | data, err = feeder.ToRss() 164 | } 165 | if checkError(res, err) { 166 | return 167 | } 168 | 169 | res.WriteHeader(http.StatusOK) 170 | res.Header().Set("Content-Type", "application/xml") 171 | res.Write([]byte(data)) 172 | } 173 | 174 | func handleItemsAtom(res http.ResponseWriter, req *http.Request, params martini.Params) { 175 | handleItems(FeedAtom, res, req, params) 176 | } 177 | 178 | func handleItemsRss(res http.ResponseWriter, req *http.Request, params martini.Params) { 179 | handleItems(FeedRSS, res, req, params) 180 | } 181 | 182 | func main() { 183 | var err error 184 | 185 | p := flags.NewNamedParser("feedme-server", flags.HelpFlag) 186 | p.ShortDescription = "The feedme server" 187 | 188 | opts.Config = func(s string) error { 189 | ini := flags.NewIniParser(p) 190 | 191 | opts.configFile = s 192 | 193 | return ini.ParseFile(s) 194 | } 195 | 196 | p.AddGroup("Server", "Server arguments", &opts) 197 | 198 | _, err = p.ParseArgs(os.Args) 199 | if err != nil { 200 | if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { 201 | panic(err) 202 | } else { 203 | p.WriteHelp(os.Stdout) 204 | 205 | os.Exit(ReturnHelp) 206 | } 207 | } 208 | 209 | if env := os.Getenv("FEEDMESPEC"); env != "" { 210 | opts.Spec = env 211 | } 212 | 213 | if opts.ConfigWrite != "" { 214 | ini := flags.NewIniParser(p) 215 | 216 | var iniOptions flags.IniOptions = flags.IniIncludeComments | flags.IniIncludeDefaults | flags.IniCommentDefaults 217 | 218 | if opts.ConfigWrite == "-" { 219 | (ini.Write(os.Stdout, iniOptions)) 220 | } else { 221 | ini.WriteFile(opts.ConfigWrite, iniOptions) 222 | } 223 | 224 | os.Exit(ReturnOk) 225 | } 226 | 227 | if opts.MaxIdleConns < 0 { 228 | opts.MaxIdleConns = 0 229 | } 230 | 231 | if opts.MaxOpenConns <= 0 { 232 | opts.MaxOpenConns = 1 233 | } 234 | 235 | db, err = backend.NewBackend("postgresql") 236 | if err != nil { 237 | panic(err) 238 | } 239 | 240 | params := backend.Parameters{ 241 | Spec: opts.Spec, 242 | MaxIdleConns: opts.MaxIdleConns, 243 | MaxOpenConns: opts.MaxOpenConns, 244 | } 245 | 246 | err = db.Init(params) 247 | if err != nil { 248 | panic(err) 249 | } 250 | 251 | ma := martini.New() 252 | 253 | if opts.Logging { 254 | ma.Use(martini.Logger()) 255 | } 256 | ma.Use(martini.Recovery()) 257 | 258 | r := martini.NewRouter() 259 | ma.Action(r.Handle) 260 | 261 | m := martini.ClassicMartini{ 262 | Martini: ma, 263 | Router: r, 264 | } 265 | 266 | m.Get("/", handleFeeds) 267 | m.Get("/:feed/atom", handleItemsAtom) 268 | m.Get("/:feed/rss", handleItemsRss) 269 | 270 | http.ListenAndServe(fmt.Sprintf(":%d", opts.Port), m) 271 | 272 | os.Exit(ReturnOk) 273 | } 274 | -------------------------------------------------------------------------------- /feedme.go: -------------------------------------------------------------------------------- 1 | package feedme 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | // Feed represents a feed 8 | type Feed struct { 9 | ID int `json:"id"` 10 | Name string `json:"name"` 11 | URL string `json:"url"` 12 | Transform string `json:"transform"` 13 | } 14 | 15 | // Item represents an item of a feed 16 | type Item struct { 17 | Feed int 18 | ID int 19 | Title string 20 | URI string 21 | Description string 22 | Created time.Time 23 | } 24 | -------------------------------------------------------------------------------- /scripts/postgresql_ddl.sql: -------------------------------------------------------------------------------- 1 | /* Settings */ 2 | 3 | 4 | /* Drops */ 5 | 6 | DROP TABLE IF EXISTS items; 7 | DROP TABLE IF EXISTS feeds; 8 | 9 | /* Tables */ 10 | 11 | CREATE TABLE feeds ( 12 | id SERIAL, 13 | name TEXT NOT NULL, 14 | url TEXT NOT NULL, 15 | transform TEXT NOT NULL, 16 | PRIMARY KEY(id), 17 | UNIQUE(name) 18 | ); 19 | 20 | CREATE TABLE items ( 21 | feed INTEGER NOT NULL, 22 | id SERIAL, 23 | title TEXT NOT NULL, 24 | uri TEXT NOT NULL, 25 | description TEXT NOT NULL, 26 | created TIMESTAMP NOT NULL, 27 | PRIMARY KEY(id) 28 | ); 29 | 30 | /* new Settings */ 31 | 32 | /* Foreign Keys */ 33 | 34 | ALTER TABLE items 35 | ADD CONSTRAINT items_feed_fk 36 | FOREIGN KEY(feed) 37 | REFERENCES feeds(id) 38 | ON DELETE CASCADE; 39 | 40 | /* Indizes */ 41 | --------------------------------------------------------------------------------