feed2imap-1.2/0000755000175000017500000000000012207251241013416 5ustar terceiroterceirofeed2imap-1.2/COPYING0000644000175000017500000004311011442712411014451 0ustar terceiroterceiro GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. feed2imap-1.2/data/0000755000175000017500000000000012207251241014327 5ustar terceiroterceirofeed2imap-1.2/data/doc/0000755000175000017500000000000012207251241015074 5ustar terceiroterceirofeed2imap-1.2/data/doc/feed2imap/0000755000175000017500000000000012207251241016730 5ustar terceiroterceirofeed2imap-1.2/data/doc/feed2imap/examples/0000755000175000017500000000000012207251241020546 5ustar terceiroterceirofeed2imap-1.2/data/doc/feed2imap/examples/feed2imaprc0000644000175000017500000000711512202270621022654 0ustar terceiroterceiro# Global options: # max-failures: maximum number of failures allowed before they are reported in # normal mode (default 10). By default, failures are only visible in verbose # mode. Most feeds tend to suffer from temporary failures. # dumpdir: (for debugging purposes) directory where all fetched feeds will be # dumped. # debug-updated: (for debugging purposes) if true, display a lot of information # about the "updated-items" algorithm. # include-images: download images and include them in the mail? (true/false) # reupload-if-updated: when an item is updated, and was previously deleted, # reupload it? (true/false, default true) # default-email: default email address in the format foo@example.com # disable-ssl-verification: disable SSL certification when connecting # to IMAPS accounts (true/false) # timeout: time before getting timeout when fetching feeds (default 30) in seconds # # Per-feed options: # name: name of the feed (must be unique) # url: HTTP[S] address where the feed has to be fetched # target: the IMAP URI where to put emails. Should start with imap:// for IMAP, # imaps:// for IMAPS and maildir:// for a path to a local maildir. # min-frequency: (in HOURS) is the minimum frequency with which this particular # feed will be fetched # disable: if set to something, the feed will be ignored # include-images: download images and include them in the mail? (true/false) # reupload-if-updated: when an item is updated, and was previously deleted, # reupload it? (true/false, default true) # always-new: feed2imap tries to use a clever algorithm to determine whether # an item is new or has been updated. It doesn't work well with some web apps # like mediawiki. When this flag is enabled, all items which don't match # exactly a previously downloaded item are considered as new items. # ignore-hash: Some feeds change the content of their items all the time, so # feed2imap detects that they have been updated at each run. When this flag # is enabled, feed2imap ignores the content of an item when determining # whether the item is already known. # dumpdir: (for debugging purposes) directory where all fetched feeds will be # dumped. # Snownews/Liferea scripts support : # execurl: Command to execute that will display the RSS/Atom feed on stdout # filter: Command to execute which will receive the RSS/Atom feed on stdin, # modify it, and output it on stdout. # For more information: http://kiza.kcore.de/software/snownews/snowscripts/ # # # If your login contains an @ character, replace it with %40. Other reserved # characters can be escaped in the same way (see man ascii to get their code) feeds: - name: feed2imap url: http://home.gna.org/feed2imap/feed2imap.rss target: imap://luser:password@imap.apinc.org/INBOX.Feeds.Feed2Imap - name: lucas url: http://www.lucas-nussbaum.net/blog/?feed=rss2 target: imap://luser:password@imap.apinc.org/INBOX.Feeds.Lucas - name: JabberFrWiki url: http://wiki.jabberfr.org/index.php?title=Special:Recentchanges&feed=rss target: imaps://luser:password@imap.apinc.org/INBOX.Feeds.JabberFR always-new: true - name: LeMonde execurl: "wget -q -O /dev/stdout http://www.lemonde.fr/rss/sequence/0,2-3208,1-0,0.xml" filter: "/home/lucas/lemonde_getbody" target: imap://luser:password@imap.apinc.org/INBOX.Feeds.LeMonde # It is also possible to reuse the same string in the target parameter: # target-refix: &target "imap://user:pass@host/rss." # feeds: # - name: test1 # target: [ *target, 'test1' ] # ... # - name: test2 # target: [ *target, 'test2' ] # ... # vim: ft=yaml:sts=2:expandtab feed2imap-1.2/data/man/0000755000175000017500000000000012207251241015102 5ustar terceiroterceirofeed2imap-1.2/data/man/man1/0000755000175000017500000000000012207251241015736 5ustar terceiroterceirofeed2imap-1.2/data/man/man1/feed2imap-cleaner.10000644000175000017500000000301411442712411021262 0ustar terceiroterceiro.TH feed2imap\-cleaner 1 "Jul 25, 2005" .SH NAME feed2imap\-cleaner \- Removes old items from IMAP folders .SH SYNOPSIS \fBfeed2imap\-cleaner\fR [OPTIONS] .SH DESCRIPTION feed2imap\-cleaner deletes old items from IMAP folders specified in the configuration file. The actual query string used to determine whether an item is old is : "SEEN NOT FLAGGED BEFORE (3 days ago)". Which means that an item WON'T be deleted if it satisfies one of the following conditions : .TP 0.2i \(bu It isn't 3 days old ; .TP 0.2i \(bu It hasn't been read yet ; .TP 0.2i \(bu It is flagged (marked as Important, for example). .TP \fB\-d\fR, \fB\-\-dry\-run\fR Don't remove anything, but show what would be removed if run without this option. .TP \fB\-f\fR, \fB\-\-config \fIfile\fB\fR Use another config file (~/.feed2imaprc is the default). .SH BUGS Deletion criterias should probably be more configurable. .SH "SEE ALSO" Homepage : http://home.gna.org/feed2imap/ .PP \fBfeed2imaprc\fR(5), \fBfeed2imap\fR(1) .SH AUTHOR Copyright (C) 2005 Lucas Nussbaum lucas@lucas\-nussbaum.net .PP This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. .PP This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. feed2imap-1.2/data/man/man1/feed2imap.10000644000175000017500000000272611442712411017664 0ustar terceiroterceiro.TH feed2imap 1 "Jul 25, 2005" .SH NAME feed2imap \- clever RSS/ATOM feed aggregator .SH SYNOPSIS \fBfeed2imap\fR [OPTIONS] .SH DESCRIPTION feed2imap is an RSS/Atom feed aggregator. After Downloading feeds (over HTTP or HTTPS), it uploads them to a specified folder of an IMAP mail server. The user can then access the feeds using Mutt, Evolution, Mozilla Thunderbird or even a webmail. .TP \fB\-V\fR, \fB\-\-version\fR Show version information. .TP \fB\-v\fR, \fB\-\-verbose\fR Run in verbose mode. .TP \fB\-c\fR, \fB\-\-rebuild\-cache\fR Rebuilds the cache. Fetches all items and mark them as already seen. Useful if you lose your .feed2imap.cache file. .TP \fB\-f\fR, \fB\-\-config \fIfile\fB\fR Use another config file (~/.feed2imaprc is the default). .SH "SEE ALSO" Homepage : http://home.gna.org/feed2imap/ .PP \fBfeed2imaprc\fR(5), \fBfeed2imap\-cleaner\fR(1), \fBfeed2imap\-dumpconfig\fR(1), \fBfeed2imap\-opmlimport\fR(1) .SH AUTHOR Copyright (C) 2005 Lucas Nussbaum lucas@lucas\-nussbaum.net .PP This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. .PP This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. feed2imap-1.2/data/man/man1/feed2imap-opmlimport.10000644000175000017500000000215011442712411022053 0ustar terceiroterceiro.TH feed2imap\-opmlimport 1 "Jul 25, 2005" .SH NAME feed2imap\-opmlimport \- Convert an OPML subscription list to a feed2imap config file .SH SYNOPSIS \fBfeed2imap\-opmlimport\fR .SH DESCRIPTION feed2imap\-opmlimport reads an OPML subscription list on standard input and outputs a feed2imap configuration file on standard output. The resulting configuration file will require some tweaking. .SH BUGS Should probably accept parameters to be able to change default values. .SH "SEE ALSO" Homepage : http://home.gna.org/feed2imap/ .PP \fBfeed2imaprc\fR(5), \fBfeed2imap\fR(1) .SH AUTHOR Copyright (C) 2005 Lucas Nussbaum lucas@lucas\-nussbaum.net .PP This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. .PP This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. feed2imap-1.2/data/man/man1/feed2imap-dumpconfig.10000644000175000017500000000174411442712411022014 0ustar terceiroterceiro.TH feed2imap\-dumpconfig 1 "Jul 25, 2005" .SH NAME feed2imap\-dumpconfig \- Dump feed2imap config .SH SYNOPSIS \fBfeed2imap\-dumpconfig\fR [OPTIONS] .SH DESCRIPTION feed2imap\-dumpconfig dumps the content of your feed2imaprc to screen. .TP \fB\-f\fR, \fB\-\-config \fIfile\fB\fR Use another config file (~/.feed2imaprc is the default). .SH "SEE ALSO" Homepage : http://home.gna.org/feed2imap/ .PP \fBfeed2imaprc\fR(5), \fBfeed2imap\fR(1) .SH AUTHOR Copyright (C) 2005 Lucas Nussbaum lucas@lucas\-nussbaum.net .PP This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. .PP This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. feed2imap-1.2/data/man/man5/0000755000175000017500000000000012207251241015742 5ustar terceiroterceirofeed2imap-1.2/data/man/man5/feed2imaprc.50000644000175000017500000000235211442712411020214 0ustar terceiroterceiro.TH feed2imaprc 5 "Jul 25, 2005" .SH NAME feed2imaprc \- feed2imap configuration file .SH SYNOPSIS \fBfeed2imaprc\fR is feed2imap's configuration file. It is usually located in \fB~/.feed2imaprc\fR. .SH EXAMPLE See \fB/usr/share/doc/feed2imap/examples/feed2imaprc\fR. .SH "RESERVED CHARACTERS" Some characters are reserved in RFC2396 (URI). If you need to include a reserved character in the login/password part of your target URI, replace it with its hex code. For example, @ can be replaced by %40. .SH BUGS This manpage should probably give more details. However, the example configuration file is very well documented. .SH "SEE ALSO" Homepage : http://home.gna.org/feed2imap/ .PP \fBfeed2imap\fR(1) .SH AUTHOR Copyright (C) 2005 Lucas Nussbaum lucas@lucas\-nussbaum.net .PP This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. .PP This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. feed2imap-1.2/test/0000755000175000017500000000000012207251241014375 5ustar terceiroterceirofeed2imap-1.2/test/maildir/0000755000175000017500000000000012207251241016016 5ustar terceiroterceirofeed2imap-1.2/test/maildir/new/0000755000175000017500000000000012207251241016607 5ustar terceiroterceirofeed2imap-1.2/test/maildir/new/1376320099.18396_7.debian0000644000175000017500000000047512202271166021772 0ustar terceiroterceiroDate: Mon, 12 Aug 2013 17:08:19 +0200 From: Antonio Terceiro To: terceiro@debian.org Subject: a new message Message-ID: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline User-Agent: Mutt/1.5.21 (2010-09-15) This message is new feed2imap-1.2/test/maildir/cur/0000755000175000017500000000000012207251241016607 5ustar terceiroterceirofeed2imap-1.2/test/maildir/cur/1376320022.18396_5.debian:2,FS0000644000175000017500000000051212202271166022423 0ustar terceiroterceiroDate: Mon, 12 Aug 2013 17:07:02 +0200 From: Antonio Terceiro To: terceiro@debian.org Subject: a flagged message Message-ID: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline User-Agent: Mutt/1.5.21 (2010-09-15) This message is flagged. feed2imap-1.2/test/maildir/cur/1376317520.15784_1.debian:2,S0000644000175000017500000000053412202271166022324 0ustar terceiroterceiroDate: Mon, 12 Aug 2013 16:25:20 +0200 From: Antonio Terceiro To: terceiro@debian.org Subject: UTF-8 data: =?iso-8859-1?B?4ent8/o=?= Message-ID: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline User-Agent: Mutt/1.5.21 (2010-09-15) This is a sample email feed2imap-1.2/test/maildir/cur/1376319137.17850_1.debian:2,0000644000175000017500000000051612202271166022203 0ustar terceiroterceiroDate: Mon, 12 Aug 2013 16:52:17 +0200 From: Antonio Terceiro To: terceiro@debian.org Subject: an unread message Message-ID: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline User-Agent: Mutt/1.5.21 (2010-09-15) This message was not read yet feed2imap-1.2/test/tc_maildir.rb0000644000175000017500000000406312202272430017032 0ustar terceiroterceirorequire 'test/unit' require 'fileutils' require 'tmpdir' require 'mocha/setup' require 'feed2imap/maildir' class TestMaildir < Test::Unit::TestCase def setup @tmpdirs = [] end def tear_down @tmpdirs.each do |dir| FileUtils.rm_rf(dir) end end def test_cleanup folder = create_maildir msgs = message_count(folder) maildir_account.cleanup(folder) assert_equal msgs - 1, message_count(folder) end def test_putmail folder = create_maildir msgs = message_count(folder) mail = RMail::Message.new mail.header['Subject'] = 'a message I just created' mail.body = 'to test maildir' maildir_account.putmail(folder, mail) assert_equal msgs + 1, message_count(folder) end def test_updatemail folder = create_maildir path = maildir_account.send( :find_mails, folder, 'regular-message-id@debian.org' ).first assert_not_nil path mail = RMail::Message.new mail.header['Subject'] = 'a different subject' mail.header['Message-ID'] = 'regular-message-id@debian.org' mail.body = 'This is the body of the message' maildir_account.updatemail(folder, mail, 'regular-message-id@debian.org') updated_path = maildir_account.send( :find_mails, folder, 'regular-message-id@debian.org' ).first updated_mail = RMail::Parser.read(File.open(File.join(folder, updated_path))) assert_equal 'a different subject', updated_mail.header['Subject'] end def test_find_mails folder = create_maildir assert_equal 0, maildir_account.send(:find_mails, folder, 'SomeRandomMessageID').size end private def create_maildir parent = Dir.mktmpdir @tmpdirs << parent FileUtils.cp_r('test/maildir', parent) return File.join(parent, 'maildir') end def message_count(folder) Dir.glob(File.join(folder, '**', '*')).reject { |f| File.directory?(f) }.size end def maildir_account @maildir_account ||= begin MaildirAccount.new.tap do |account| account.stubs(:puts) end end end end feed2imap-1.2/test/tc_cache.rb0000755000175000017500000000432611442712411016464 0ustar terceiroterceiro#!/usr/bin/ruby -w $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'test/unit' require 'feed2imap/cache' require 'feedparser' require 'pp' class ItemCacheTest < Test::Unit::TestCase def test_create cache = ItemCache::new assert(! cache.nil?) end def test_cache_lastcheck cache = ItemCache::new assert_equal(Time::at(0), cache.get_last_check('coucou')) t = Time::now cache.set_last_check('coucou', t) assert_equal(t, cache.get_last_check('coucou')) end def test_cache_management c = ItemCache::new assert_equal(0, c.nbchannels) assert_equal(0, c.nbitems) i1 = FeedParser::FeedItem::new i1.title = 'title1' i1.link = 'link1' i1.content = 'content1' i2 = FeedParser::FeedItem::new i2.title = 'title2' i2.link = 'link2' i2.content = 'content2' i3 = FeedParser::FeedItem::new i3.title = 'title3' i3.link = 'link3' i3.content = 'content3' assert_equal([i1, i2], c.get_new_items('id', [i1, i2])[0]) c.commit_cache('id') assert_equal(2, c.nbitems) assert_equal([i3], c.get_new_items('id', [i2, i3])[0]) end def test_cache_management_updated c = ItemCache::new assert_equal(0, c.nbchannels) assert_equal(0, c.nbitems) i1 = FeedParser::FeedItem::new i1.title = 'title1' i1.link = 'link1' i1.content = 'content1' i2 = FeedParser::FeedItem::new i2.title = 'title2' i2.link = 'link2' i2.content = 'content2' news = c.get_new_items('id', [i1, i2])[0] assert_equal([i1, i2], news) idx1 = i1.cacheditem.index assert_equal(0, idx1) idx2 = i2.cacheditem.index assert_equal(1, idx2) c.commit_cache('id') i3 = FeedParser::FeedItem::new i3.title = 'title 1 - updated' i3.link = 'link1' i3.content = 'content1' news, updated = c.get_new_items('id', [i3]) assert_equal([], news) assert_equal([i3], updated) assert_equal(idx1, i3.cacheditem.index) i4 = FeedParser::FeedItem::new i4.title = 'title 1 - updated' i4.link = 'link1' i4.content = 'content1 - modified' news, updated = c.get_new_items('id', [i4]) assert_equal([], news) assert_equal([i4], updated) assert_equal(idx1, i4.cacheditem.index) end end feed2imap-1.2/test/ts_feed2imap.rb0000755000175000017500000000053111442712411017267 0ustar terceiroterceiro#!/usr/bin/ruby -w $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') $:.unshift File.join(File.dirname(__FILE__), '..', 'test') $:.unshift File.join(File.dirname(__FILE__), 'lib') $:.unshift File.join(File.dirname(__FILE__), 'test') require 'feed2imap' require 'tc_cache' require 'tc_config' require 'tc_mail' require 'tc_httpfetcher' feed2imap-1.2/test/tc_config.rb0000755000175000017500000000377112202270621016666 0ustar terceiroterceiro#!/usr/bin/ruby -w $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'test/unit' require 'feed2imap/config' require 'stringio' CONF1 = < 20) end def test_get_http end def test_get_httpnotmodif s = 'aaa' assert_nothing_raised do s = HTTPFetcher::fetch('http://www.lucas-nussbaum.net/feed2imap_tests/notmodified.php', Time::new()) end assert_nil(s) end def test_get_redir1 s = 'aaa' assert_nothing_raised do s = HTTPFetcher::fetch("http://www.lucas-nussbaum.net/feed2imap_tests/redir.php?redir=#{MAXREDIR}", Time::at(0)) end assert_equal('OK', s) end def test_get_redir2 s = '' assert_raise(RuntimeError) do s = HTTPFetcher::fetch("http://www.lucas-nussbaum.net/feed2imap_tests/redir.php?redir=#{MAXREDIR + 1}", Time::at(0)) end end def test_httpauth s = '' assert_nothing_raised do s = HTTPFetcher::fetch("http://aaa:bbb@ensilinx1.imag.fr/~lucas/f2i_redirauth.php", Time::at(0)) end assert_equal("Login: aaa / Password: bbb \n", s) end def test_redirauth s = '' assert_nothing_raised do s = HTTPFetcher::fetch("http://aaa:bbb@ensilinx1.imag.fr/~lucas/f2i_redirauth.php?redir=1", Time::at(0)) end assert_equal("Login: aaa / Password: bbb \n", s) end def test_notfound s = '' assert_raises(RuntimeError) do s = HTTPFetcher::fetch("http://ensilinx1.imag.fr/~lucas/notfound.html", Time::at(0)) end end end feed2imap-1.2/ChangeLog0000644000175000017500000001615411442712411015200 0ustar terceiroterceiroFeed2Imap 1.0 (18/04/2010) ========================== * Removed patch from Haegar as it's no longer needed with the new rubyimap.rb (see discussion in https://gna.org/bugs/?13977) * Support writing to maildirs instead of through IMAP * Use Message-ID instead of X-CacheIndex * Do not use acme.com * Update rubyimap.rb * Provide a way to disable SSL certification verification when connecting to IMAPS accounts Feed2Imap 0.9.4 (27/07/2009) ============================ * Warn (INFO level, so only displayed with feed2imap -v) if fetching a feed takes more than 10s, as this might cause massive delays in feed2imap run times. * Fix encoding of email headers * Only include images once when used several times in the same item * New version of Net::Imap * Use Message-Id instead of X-CacheIndex * Fix MIME formatting when including images * Require ruby-feedparser 0.7, better email formatting * Made it possible to re-use substrings in targets * Fix buffering problem with filters * Added a patch from Haegar to fix problem with dovecot 1.2.1 Feed2Imap 0.9.3 (23/07/2008) ============================ * Check the return code from external commands, and warn if != 0. Fixes Gna bug #10516. * Support for including images in the mails (see include-images config option). Based on a patch by Pavel Avgustinov, and with help from Arnt Gulbrandsen. * Dropped rubymail_patch.rb * Added option to wrap text output. Thanks to Maxime Petazzoni for the patch. * When updating an email, remove the Recent flag. * You need to use ruby-feedparser 0.6 or greater with that release. Feed2Imap 0.9.2 (28/10/2007) ============================ * resynchronized rubyimap.rb with stdlib, and fixed send! -> send. * upload items in reverse order, to upload the older first Closes Gna bug #8986. Thanks go do Rial Juan for the patch. * Don't allow more than 16 fetchers to run at the same time. 16 should be a reasonable default for everybody. Closes Gna #9032. * Reduce the default HTTP timeout to 30s. * Don't update the cache if uploading items failed (should avoid missing some items). * Safer cache writing. Should avoid some cache corruption problems. * Now exits when we receive an IMAP error, instead of trying to recover. We shouldn't receive IMAP errors anyway. Closes Debian #405070. * Fixed content-type-encoding in HTML emails. Reported by Arnt Gulbrandse. Feed2Imap 0.9.1 (15/05/2007) ============================ * Fixed bug with folder creation. Feed2Imap 0.9 (15/05/2007) ============================ * Folder creation moved to upload. This should make feed2imap run slightly faster. * Per-feed dumpdir option (helps debugging) * Now uses Content-Transfer-Encoding: 8bit (thanks Arnt Gulbrandsen ) * Now supports Snowscripts, using the 'execurl' and 'filter' config keywords. For more information, see the example configuration file. * Slightly better option parsing. Thanks to Paul van Tilburg for the patch. * A debug mode was added, and the normal mode was improved, so it is no longer necessary to redirect feed2imap output to /dev/null: transient errors are only reported after they have happened a certain number of times (default 10). * An ignore-hash option was added for feeds whose content change all the time. Feed2Imap 0.8 (28/06/2006) ============================ * Uses the http_proxy environment variable to determine the proxy server if available. (fixes gna bug #5820, all credits go to Boyd Adamson ) * Fixes flocking on Solaris (fixes gna bug #5819). Again, all credits go to Boyd Adamson . * Rewrite of the "find updated and new items" code. It should work much better now. Also, a debug-updated configuration variable was added to make it easier to debug those issues. * New always-new flag in the config file to consider all items as new (for feeds where items are wrongly marked as updated, e.g mediawiki feeds). See example configuration file for more information (fixes Debian bug #366878). * When disconnecting from the IMAP server, don't display an exception in non-verbose mode if the "connection is reset by peer" (fixes Debian bug #367282). * Handling of exceptions in needMIME (fixes gna bug #5872). Feed2Imap 0.7 (17/02/2006) ============================ * Fixes the IMAPS disconnection problem (patch provided by Gael Utard ) (fixes gna bug #2178). * Fixes some issues regarding parallel fetching of feeds. * Now displays the feed creator as sender of emails. (fixes gna bug #5043). * Don't display the password in error messages (fixes debian bug #350370). * Upload mail with the Item's time, not the upload's time (fixes debian bug #350371). Feed2Imap 0.6 (11/01/2006) ============================ * Moved the RSS/Atom parser to a separate library (ruby-feedparser). * Locks the Cache file to avoid concurrent instances of feed2imap. * Issue a warning if the config file is world readable. * Fixed a small bug in Atom feeds parsing. * Fix another bug related to escaped HTML. * Minor fixes. Feed2Imap 0.5 (19/09/2005) ============================ * Fixed a parser problem with items with multiple children in the description. * Mails were upload with \n only, but \r\n are needed. * Feed2Imap can now work without libopenssl. * Fixed a bug in the HTML2Text converter with tags without href. * Reserved characters (eg @) can now be included in the login, password or folder. You just need to escape them. * Feed2Imap is now included in Debian (package name: feed2imap). * Much better handling of feeds with escaped HTML (LinuxFR for example). Feed2Imap 0.4 (25/07/2005) ============================ * now available as a Debian package. * added manpages for everything. * added min-frequency and disable config options. Added doc in example config. * You can now use WordPress's feed:http://something urls in feed2imaprc. * Switched to a real SGML parser for the text version. * Much better output for the text version of emails. * New feed2imap-cleaner to remove old mails seen but not flagged * Feed2Imap version number wasn't displayed in the User-Agent * Better exception handling when parsing errors occur * added feed2imap's RSS feed to the default feeds in the config file Feed2Imap 0.3 (04/06/2005) ============================ * New releases are now advertised using a RSS feed * Cleaner way to manage duplicate IDs (#1773) * Fixed a problem with pseudo-duplicate entries from Mediawiki * Fixed a problem with updated items being seen as updated at each update. * Fixed a problem when the disconnection from the IMAP server failed. reported by Ludovic Gomez Feed2Imap 0.2 (30/04/2005) ============================ * Fixed a problem with feeds with strange caching bugs (old items going away and coming back) * The text version is now encoded in iso-8859-1 instead of utf-8. * The subject is now MIME-encoded in utf-8. It works with mutt & evo. * No longer overwrite mail flags (Read, Important,..) when updating an item. * HTTP fetching is now multithreaded and is much faster (about 300%). * Fetching over HTTPS works. * HTTP fetching is fully unit-tested. Feed2Imap 0.1 (02/04/2005) ========================== * first public release. feed2imap-1.2/README0000644000175000017500000000160411442712411014300 0ustar terceiroterceiro Feed2Imap ------------- by Lucas Nussbaum Currently, all the information is provided on http://home.gna.org/feed2imap Copyright (c) 2005-2010 Lucas Nussbaum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA feed2imap-1.2/setup.rb0000755000175000017500000010652311442712411015116 0ustar terceiroterceiro#!/usr/bin/ruby # # setup.rb # # Copyright (c) 2000-2005 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU LGPL, Lesser General Public License version 2.1. # unless Enumerable.method_defined?(:map) # Ruby 1.4.6 module Enumerable alias map collect end end unless File.respond_to?(:read) # Ruby 1.6 def File.read(fname) open(fname) {|f| return f.read } end end unless Errno.const_defined?(:ENOTEMPTY) # Windows? module Errno class ENOTEMPTY # We do not raise this exception, implementation is not needed. end end end def File.binread(fname) open(fname, 'rb') {|f| return f.read } end # for corrupted Windows' stat(2) def File.dir?(path) File.directory?((path[-1,1] == '/') ? path : path + '/') end class ConfigTable include Enumerable def initialize(rbconfig) @rbconfig = rbconfig @items = [] @table = {} # options @install_prefix = nil @config_opt = nil @verbose = true @no_harm = false end attr_accessor :install_prefix attr_accessor :config_opt attr_writer :verbose def verbose? @verbose end attr_writer :no_harm def no_harm? @no_harm end def [](key) lookup(key).resolve(self) end def []=(key, val) lookup(key).set val end def names @items.map {|i| i.name } end def each(&block) @items.each(&block) end def key?(name) @table.key?(name) end def lookup(name) @table[name] or setup_rb_error "no such config item: #{name}" end def add(item) @items.push item @table[item.name] = item end def remove(name) item = lookup(name) @items.delete_if {|i| i.name == name } @table.delete_if {|name, i| i.name == name } item end def load_script(path, inst = nil) if File.file?(path) MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path end end def savefile '.config' end def load_savefile begin File.foreach(savefile()) do |line| k, v = *line.split(/=/, 2) self[k] = v.strip end rescue Errno::ENOENT setup_rb_error $!.message + "\n#{File.basename($0)} config first" end end def save @items.each {|i| i.value } File.open(savefile(), 'w') {|f| @items.each do |i| f.printf "%s=%s\n", i.name, i.value if i.value? and i.value end } end def load_standard_entries standard_entries(@rbconfig).each do |ent| add ent end end def standard_entries(rbconfig) c = rbconfig rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) if c['rubylibdir'] # V > 1.6.3 libruby = "#{c['prefix']}/lib/ruby" librubyver = c['rubylibdir'] librubyverarch = c['archdir'] siteruby = c['sitedir'] siterubyver = c['sitelibdir'] siterubyverarch = c['sitearchdir'] elsif newpath_p # 1.4.4 <= V <= 1.6.3 libruby = "#{c['prefix']}/lib/ruby" librubyver = "#{c['prefix']}/lib/ruby/#{version}" librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" siteruby = c['sitedir'] siterubyver = "$siteruby/#{version}" siterubyverarch = "$siterubyver/#{c['arch']}" else # V < 1.4.4 libruby = "#{c['prefix']}/lib/ruby" librubyver = "#{c['prefix']}/lib/ruby/#{version}" librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" siterubyver = siteruby siterubyverarch = "$siterubyver/#{c['arch']}" end parameterize = lambda {|path| path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') } if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } makeprog = arg.sub(/'/, '').split(/=/, 2)[1] else makeprog = 'make' end [ ExecItem.new('installdirs', 'std/site/home', 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ {|val, table| case val when 'std' table['rbdir'] = '$librubyver' table['sodir'] = '$librubyverarch' when 'site' table['rbdir'] = '$siterubyver' table['sodir'] = '$siterubyverarch' when 'home' setup_rb_error '$HOME was not set' unless ENV['HOME'] table['prefix'] = ENV['HOME'] table['rbdir'] = '$libdir/ruby' table['sodir'] = '$libdir/ruby' end }, PathItem.new('prefix', 'path', c['prefix'], 'path prefix of target environment'), PathItem.new('bindir', 'path', parameterize.call(c['bindir']), 'the directory for commands'), PathItem.new('libdir', 'path', parameterize.call(c['libdir']), 'the directory for libraries'), PathItem.new('datadir', 'path', parameterize.call(c['datadir']), 'the directory for shared data'), PathItem.new('mandir', 'path', parameterize.call(c['mandir']), 'the directory for man pages'), PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), 'the directory for system configuration files'), PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), 'the directory for local state data'), PathItem.new('libruby', 'path', libruby, 'the directory for ruby libraries'), PathItem.new('librubyver', 'path', librubyver, 'the directory for standard ruby libraries'), PathItem.new('librubyverarch', 'path', librubyverarch, 'the directory for standard ruby extensions'), PathItem.new('siteruby', 'path', siteruby, 'the directory for version-independent aux ruby libraries'), PathItem.new('siterubyver', 'path', siterubyver, 'the directory for aux ruby libraries'), PathItem.new('siterubyverarch', 'path', siterubyverarch, 'the directory for aux ruby binaries'), PathItem.new('rbdir', 'path', '$siterubyver', 'the directory for ruby scripts'), PathItem.new('sodir', 'path', '$siterubyverarch', 'the directory for ruby extentions'), PathItem.new('rubypath', 'path', rubypath, 'the path to set to #! line'), ProgramItem.new('rubyprog', 'name', rubypath, 'the ruby program using for installation'), ProgramItem.new('makeprog', 'name', makeprog, 'the make program to compile ruby extentions'), SelectItem.new('shebang', 'all/ruby/never', 'never', 'shebang line (#!) editing mode'), BoolItem.new('without-ext', 'yes/no', 'no', 'does not compile/install ruby extentions') ] end private :standard_entries def load_multipackage_entries multipackage_entries().each do |ent| add ent end end def multipackage_entries [ PackageSelectionItem.new('with', 'name,name...', '', 'ALL', 'package names that you want to install'), PackageSelectionItem.new('without', 'name,name...', '', 'NONE', 'package names that you do not want to install') ] end private :multipackage_entries ALIASES = { 'std-ruby' => 'librubyver', 'stdruby' => 'librubyver', 'rubylibdir' => 'librubyver', 'archdir' => 'librubyverarch', 'site-ruby-common' => 'siteruby', # For backward compatibility 'site-ruby' => 'siterubyver', # For backward compatibility 'bin-dir' => 'bindir', 'bin-dir' => 'bindir', 'rb-dir' => 'rbdir', 'so-dir' => 'sodir', 'data-dir' => 'datadir', 'ruby-path' => 'rubypath', 'ruby-prog' => 'rubyprog', 'ruby' => 'rubyprog', 'make-prog' => 'makeprog', 'make' => 'makeprog' } def fixup ALIASES.each do |ali, name| @table[ali] = @table[name] end @items.freeze @table.freeze @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ end def parse_opt(opt) m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" m.to_a[1,2] end def dllext @rbconfig['DLEXT'] end def value_config?(name) lookup(name).value? end class Item def initialize(name, template, default, desc) @name = name.freeze @template = template @value = default @default = default @description = desc end attr_reader :name attr_reader :description attr_accessor :default alias help_default default def help_opt "--#{@name}=#{@template}" end def value? true end def value @value end def resolve(table) @value.gsub(%r<\$([^/]+)>) { table[$1] } end def set(val) @value = check(val) end private def check(val) setup_rb_error "config: --#{name} requires argument" unless val val end end class BoolItem < Item def config_type 'bool' end def help_opt "--#{@name}" end private def check(val) return 'yes' unless val case val when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' else setup_rb_error "config: --#{@name} accepts only yes/no for argument" end end end class PathItem < Item def config_type 'path' end private def check(path) setup_rb_error "config: --#{@name} requires argument" unless path path[0,1] == '$' ? path : File.expand_path(path) end end class ProgramItem < Item def config_type 'program' end end class SelectItem < Item def initialize(name, selection, default, desc) super @ok = selection.split('/') end def config_type 'select' end private def check(val) unless @ok.include?(val.strip) setup_rb_error "config: use --#{@name}=#{@template} (#{val})" end val.strip end end class ExecItem < Item def initialize(name, selection, desc, &block) super name, selection, nil, desc @ok = selection.split('/') @action = block end def config_type 'exec' end def value? false end def resolve(table) setup_rb_error "$#{name()} wrongly used as option value" end undef set def evaluate(val, table) v = val.strip.downcase unless @ok.include?(v) setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" end @action.call v, table end end class PackageSelectionItem < Item def initialize(name, template, default, help_default, desc) super name, template, default, desc @help_default = help_default end attr_reader :help_default def config_type 'package' end private def check(val) unless File.dir?("packages/#{val}") setup_rb_error "config: no such package: #{val}" end val end end class MetaConfigEnvironment def initialize(config, installer) @config = config @installer = installer end def config_names @config.names end def config?(name) @config.key?(name) end def bool_config?(name) @config.lookup(name).config_type == 'bool' end def path_config?(name) @config.lookup(name).config_type == 'path' end def value_config?(name) @config.lookup(name).config_type != 'exec' end def add_config(item) @config.add item end def add_bool_config(name, default, desc) @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) end def add_path_config(name, default, desc) @config.add PathItem.new(name, 'path', default, desc) end def set_config_default(name, default) @config.lookup(name).default = default end def remove_config(name) @config.remove(name) end # For only multipackage def packages raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer @installer.packages end # For only multipackage def declare_packages(list) raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer @installer.packages = list end end end # class ConfigTable # This module requires: #verbose?, #no_harm? module FileOperations def mkdir_p(dirname, prefix = nil) dirname = prefix + File.expand_path(dirname) if prefix $stderr.puts "mkdir -p #{dirname}" if verbose? return if no_harm? # Does not check '/', it's too abnormal. dirs = File.expand_path(dirname).split(%r<(?=/)>) if /\A[a-z]:\z/i =~ dirs[0] disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless File.dir?(path) end end def rm_f(path) $stderr.puts "rm -f #{path}" if verbose? return if no_harm? force_remove_file path end def rm_rf(path) $stderr.puts "rm -rf #{path}" if verbose? return if no_harm? remove_tree path end def remove_tree(path) if File.symlink?(path) remove_file path elsif File.dir?(path) remove_tree0 path else force_remove_file path end end def remove_tree0(path) Dir.foreach(path) do |ent| next if ent == '.' next if ent == '..' entpath = "#{path}/#{ent}" if File.symlink?(entpath) remove_file entpath elsif File.dir?(entpath) remove_tree0 entpath else force_remove_file entpath end end begin Dir.rmdir path rescue Errno::ENOTEMPTY # directory may not be empty end end def move_file(src, dest) force_remove_file dest begin File.rename src, dest rescue File.open(dest, 'wb') {|f| f.write File.binread(src) } File.chmod File.stat(src).mode, dest File.unlink src end end def force_remove_file(path) begin remove_file path rescue end end def remove_file(path) File.chmod 0777, path File.unlink path end def install(from, dest, mode, prefix = nil) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix ? prefix + File.expand_path(dest) : dest realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) str = File.binread(from) if diff?(str, realdest) verbose_off { rm_f realdest if File.exist?(realdest) } File.open(realdest, 'wb') {|f| f.write str } File.chmod mode, realdest File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| if prefix f.puts realdest.sub(prefix, '') else f.puts realdest end } end end def diff?(new_content, path) return true unless File.exist?(path) new_content != File.binread(path) end def command(*args) $stderr.puts args.join(' ') if verbose? system(*args) or raise RuntimeError, "system(#{args.map{|a| a.inspect }.join(' ')}) failed" end def ruby(*args) command config('rubyprog'), *args end def make(task = nil) command(*[config('makeprog'), task].compact) end def extdir?(dir) File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") end def files_of(dir) Dir.open(dir) {|d| return d.select {|ent| File.file?("#{dir}/#{ent}") } } end DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) def directories_of(dir) Dir.open(dir) {|d| return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT } end end # This module requires: #srcdir_root, #objdir_root, #relpath module HookScriptAPI def get_config(key) @config[key] end alias config get_config # obsolete: use metaconfig to change configuration def set_config(key, val) @config[key] = val end # # srcdir/objdir (works only in the package directory) # def curr_srcdir "#{srcdir_root()}/#{relpath()}" end def curr_objdir "#{objdir_root()}/#{relpath()}" end def srcfile(path) "#{curr_srcdir()}/#{path}" end def srcexist?(path) File.exist?(srcfile(path)) end def srcdirectory?(path) File.dir?(srcfile(path)) end def srcfile?(path) File.file?(srcfile(path)) end def srcentries(path = '.') Dir.open("#{curr_srcdir()}/#{path}") {|d| return d.to_a - %w(. ..) } end def srcfiles(path = '.') srcentries(path).select {|fname| File.file?(File.join(curr_srcdir(), path, fname)) } end def srcdirectories(path = '.') srcentries(path).select {|fname| File.dir?(File.join(curr_srcdir(), path, fname)) } end end class ToplevelInstaller Version = '3.4.1' Copyright = 'Copyright (c) 2000-2005 Minero Aoki' TASKS = [ [ 'all', 'do config, setup, then install' ], [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles ruby extentions and others' ], [ 'install', 'installs files' ], [ 'test', 'run all tests in test/' ], [ 'clean', "does `make clean' for each extention" ], [ 'distclean',"does `make distclean' for each extention" ] ] def ToplevelInstaller.invoke config = ConfigTable.new(load_rbconfig()) config.load_standard_entries config.load_multipackage_entries if multipackage? config.fixup klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) klass.new(File.dirname($0), config).invoke end def ToplevelInstaller.multipackage? File.dir?(File.dirname($0) + '/packages') end def ToplevelInstaller.load_rbconfig if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } ARGV.delete(arg) load File.expand_path(arg.split(/=/, 2)[1]) $".push 'rbconfig.rb' else require 'rbconfig' end ::Config::CONFIG end def initialize(ardir_root, config) @ardir = File.expand_path(ardir_root) @config = config # cache @valid_task_re = nil end def config(key) @config[key] end def inspect "#<#{self.class} #{__id__()}>" end def invoke run_metaconfigs case task = parsearg_global() when nil, 'all' parsearg_config init_installers exec_config exec_setup exec_install else case task when 'config', 'test' ; when 'clean', 'distclean' @config.load_savefile if File.exist?(@config.savefile) else @config.load_savefile end __send__ "parsearg_#{task}" init_installers __send__ "exec_#{task}" end end def run_metaconfigs @config.load_script "#{@ardir}/metaconfig" end def init_installers @installer = Installer.new(@config, @ardir, File.expand_path('.')) end # # Hook Script API bases # def srcdir_root @ardir end def objdir_root '.' end def relpath '.' end # # Option Parsing # def parsearg_global while arg = ARGV.shift case arg when /\A\w+\z/ setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) return arg when '-q', '--quiet' @config.verbose = false when '--verbose' @config.verbose = true when '--help' print_usage $stdout exit 0 when '--version' puts "#{File.basename($0)} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else setup_rb_error "unknown global option '#{arg}'" end end nil end def valid_task?(t) valid_task_re() =~ t end def valid_task_re @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ end def parsearg_no_options unless ARGV.empty? task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" end end alias parsearg_show parsearg_no_options alias parsearg_setup parsearg_no_options alias parsearg_test parsearg_no_options alias parsearg_clean parsearg_no_options alias parsearg_distclean parsearg_no_options def parsearg_config evalopt = [] set = [] @config.config_opt = [] while i = ARGV.shift if /\A--?\z/ =~ i @config.config_opt = ARGV.dup break end name, value = *@config.parse_opt(i) if @config.value_config?(name) @config[name] = value else evalopt.push [name, value] end set.push name end evalopt.each do |name, value| @config.lookup(name).evaluate value, @config end # Check if configuration is valid set.each do |n| @config[n] if @config.value_config?(n) end end def parsearg_install @config.no_harm = false @config.install_prefix = '' while a = ARGV.shift case a when '--no-harm' @config.no_harm = true when /\A--prefix=/ path = a.split(/=/, 2)[1] path = File.expand_path(path) unless path[0,1] == '/' @config.install_prefix = path else setup_rb_error "install: unknown option #{a}" end end end def print_usage(out) out.puts 'Typical Installation Procedure:' out.puts " $ ruby #{File.basename $0} config" out.puts " $ ruby #{File.basename $0} setup" out.puts " # ruby #{File.basename $0} install (may require root privilege)" out.puts out.puts 'Detailed Usage:' out.puts " ruby #{File.basename $0} " out.puts " ruby #{File.basename $0} [] []" fmt = " %-24s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, ' --help', 'print this message' out.printf fmt, ' --version', 'print version and quit' out.printf fmt, ' --copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf fmt, name, desc end fmt = " %-24s %s [%s]\n" out.puts out.puts 'Options for CONFIG or ALL:' @config.each do |item| out.printf fmt, item.help_opt, item.description, item.help_default end out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" out.puts out.puts 'Options for INSTALL:' out.printf fmt, '--no-harm', 'only display what to do if given', 'off' out.printf fmt, '--prefix=path', 'install path prefix', '' out.puts end # # Task Handlers # def exec_config @installer.exec_config @config.save # must be final end def exec_setup @installer.exec_setup end def exec_install @installer.exec_install end def exec_test @installer.exec_test end def exec_show @config.each do |i| printf "%-20s %s\n", i.name, i.value if i.value? end end def exec_clean @installer.exec_clean end def exec_distclean @installer.exec_distclean end end # class ToplevelInstaller class ToplevelInstallerMulti < ToplevelInstaller include FileOperations def initialize(ardir_root, config) super @packages = directories_of("#{@ardir}/packages") raise 'no package exists' if @packages.empty? @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) end def run_metaconfigs @config.load_script "#{@ardir}/metaconfig", self @packages.each do |name| @config.load_script "#{@ardir}/packages/#{name}/metaconfig" end end attr_reader :packages def packages=(list) raise 'package list is empty' if list.empty? list.each do |name| raise "directory packages/#{name} does not exist"\ unless File.dir?("#{@ardir}/packages/#{name}") end @packages = list end def init_installers @installers = {} @packages.each do |pack| @installers[pack] = Installer.new(@config, "#{@ardir}/packages/#{pack}", "packages/#{pack}") end with = extract_selection(config('with')) without = extract_selection(config('without')) @selected = @installers.keys.select {|name| (with.empty? or with.include?(name)) \ and not without.include?(name) } end def extract_selection(list) a = list.split(/,/) a.each do |name| setup_rb_error "no such package: #{name}" unless @installers.key?(name) end a end def print_usage(f) super f.puts 'Inluded packages:' f.puts ' ' + @packages.sort.join(' ') f.puts end # # Task Handlers # def exec_config run_hook 'pre-config' each_selected_installers {|inst| inst.exec_config } run_hook 'post-config' @config.save # must be final end def exec_setup run_hook 'pre-setup' each_selected_installers {|inst| inst.exec_setup } run_hook 'post-setup' end def exec_install run_hook 'pre-install' each_selected_installers {|inst| inst.exec_install } run_hook 'post-install' end def exec_test run_hook 'pre-test' each_selected_installers {|inst| inst.exec_test } run_hook 'post-test' end def exec_clean rm_f @config.savefile run_hook 'pre-clean' each_selected_installers {|inst| inst.exec_clean } run_hook 'post-clean' end def exec_distclean rm_f @config.savefile run_hook 'pre-distclean' each_selected_installers {|inst| inst.exec_distclean } run_hook 'post-distclean' end # # lib # def each_selected_installers Dir.mkdir 'packages' unless File.dir?('packages') @selected.each do |pack| $stderr.puts "Processing the package `#{pack}' ..." if verbose? Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") Dir.chdir "packages/#{pack}" yield @installers[pack] Dir.chdir '../..' end end def run_hook(id) @root_installer.run_hook id end # module FileOperations requires this def verbose? @config.verbose? end # module FileOperations requires this def no_harm? @config.no_harm? end end # class ToplevelInstallerMulti class Installer FILETYPES = %w( bin lib ext data conf man ) include FileOperations include HookScriptAPI def initialize(config, srcroot, objroot) @config = config @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{self.class} #{File.basename(@srcdir)}>" end def noop(rel) end # # Hook Script API base methods # def srcdir_root @srcdir end def objdir_root @objdir end def relpath @currdir end # # Config Access # # module FileOperations requires this def verbose? @config.verbose? end # module FileOperations requires this def no_harm? @config.no_harm? end def verbose_off begin save, @config.verbose = @config.verbose?, false yield ensure @config.verbose = save end end # # TASK config # def exec_config exec_task_traverse 'config' end alias config_dir_bin noop alias config_dir_lib noop def config_dir_ext(rel) extconf if extdir?(curr_srcdir()) end alias config_dir_data noop alias config_dir_conf noop alias config_dir_man noop def extconf ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt end # # TASK setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin(rel) files_of(curr_srcdir()).each do |fname| update_shebang_line "#{curr_srcdir()}/#{fname}" end end alias setup_dir_lib noop def setup_dir_ext(rel) make if extdir?(curr_srcdir()) end alias setup_dir_data noop alias setup_dir_conf noop alias setup_dir_man noop def update_shebang_line(path) return if no_harm? return if config('shebang') == 'never' old = Shebang.load(path) if old $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 new = new_shebang(old) return if new.to_s == old.to_s else return unless config('shebang') == 'all' new = Shebang.new(config('rubypath')) end $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? open_atomic_writer(path) {|output| File.open(path, 'rb') {|f| f.gets if old # discard output.puts new.to_s output.print f.read } } end def new_shebang(old) if /\Aruby/ =~ File.basename(old.cmd) Shebang.new(config('rubypath'), old.args) elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' Shebang.new(config('rubypath'), old.args[1..-1]) else return old unless config('shebang') == 'all' Shebang.new(config('rubypath')) end end def open_atomic_writer(path, &block) tmpfile = File.basename(path) + '.tmp' begin File.open(tmpfile, 'wb', &block) File.rename tmpfile, File.basename(path) ensure File.unlink tmpfile if File.exist?(tmpfile) end end class Shebang def Shebang.load(path) line = nil File.open(path) {|f| line = f.gets } return nil unless /\A#!/ =~ line parse(line) end def Shebang.parse(line) cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') new(cmd, args) end def initialize(cmd, args = []) @cmd = cmd @args = args end attr_reader :cmd attr_reader :args def to_s "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") end end # # TASK install # def exec_install rm_f 'InstalledFiles' exec_task_traverse 'install' end def install_dir_bin(rel) install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 end def install_dir_lib(rel) install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 end def install_dir_ext(rel) return unless extdir?(curr_srcdir()) install_files rubyextentions('.'), "#{config('sodir')}/#{File.dirname(rel)}", 0555 end def install_dir_data(rel) install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 end def install_dir_conf(rel) # FIXME: should not remove current config files # (rename previous file to .old/.org) install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 end def install_dir_man(rel) install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 end def install_files(list, dest, mode) mkdir_p dest, @config.install_prefix list.each do |fname| install fname, dest, mode, @config.install_prefix end end def libfiles glob_reject(%w(*.y *.output), targetfiles()) end def rubyextentions(dir) ents = glob_select("*.#{@config.dllext}", targetfiles()) if ents.empty? setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" end ents end def targetfiles mapdir(existfiles() - hookfiles()) end def mapdir(ents) ents.map {|ent| if File.exist?(ent) then ent # objdir else "#{curr_srcdir()}/#{ent}" # srcdir end } end # picked up many entries from cvs-1.11.1/src/ignore.c JUNK_FILES = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ *.org *.in .* ) def existfiles glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) end def hookfiles %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| %w( config setup install clean ).map {|t| sprintf(fmt, t) } }.flatten end def glob_select(pat, ents) re = globs2re([pat]) ents.select {|ent| re =~ ent } end def glob_reject(pats, ents) re = globs2re(pats) ents.reject {|ent| re =~ ent } end GLOB2REGEX = { '.' => '\.', '$' => '\$', '#' => '\#', '*' => '.*' } def globs2re(pats) /\A(?:#{ pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') })\z/ end # # TASK test # TESTDIR = 'test' def exec_test unless File.directory?('test') $stderr.puts 'no test in this package' if verbose? return end $stderr.puts 'Running tests...' if verbose? begin require 'test/unit' rescue LoadError setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' end runner = Test::Unit::AutoRunner.new(true) runner.to_run << TESTDIR runner.run end # # TASK clean # def exec_clean exec_task_traverse 'clean' rm_f @config.savefile rm_f 'InstalledFiles' end alias clean_dir_bin noop alias clean_dir_lib noop alias clean_dir_data noop alias clean_dir_conf noop alias clean_dir_man noop def clean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'clean' if File.file?('Makefile') end # # TASK distclean # def exec_distclean exec_task_traverse 'distclean' rm_f @config.savefile rm_f 'InstalledFiles' end alias distclean_dir_bin noop alias distclean_dir_lib noop def distclean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'distclean' if File.file?('Makefile') end alias distclean_dir_data noop alias distclean_dir_conf noop alias distclean_dir_man noop # # Traversing # def exec_task_traverse(task) run_hook "pre-#{task}" FILETYPES.each do |type| if type == 'ext' and config('without-ext') == 'yes' $stderr.puts 'skipping ext/* by user option' if verbose? next end traverse task, type, "#{task}_dir_#{type}" end run_hook "post-#{task}" end def traverse(task, rel, mid) dive_into(rel) { run_hook "pre-#{task}" __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') directories_of(curr_srcdir()).each do |d| traverse task, "#{rel}/#{d}", mid end run_hook "post-#{task}" } end def dive_into(rel) return unless File.dir?("#{@srcdir}/#{rel}") dir = File.basename(rel) Dir.mkdir dir unless File.dir?(dir) prevdir = Dir.pwd Dir.chdir dir $stderr.puts '---> ' + rel if verbose? @currdir = rel yield Dir.chdir prevdir $stderr.puts '<--- ' + rel if verbose? @currdir = File.dirname(rel) end def run_hook(id) path = [ "#{curr_srcdir()}/#{id}", "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } return unless path begin instance_eval File.read(path), path, 1 rescue raise if $DEBUG setup_rb_error "hook #{path} failed:\n" + $!.message end end end # class Installer class SetupError < StandardError; end def setup_rb_error(msg) raise SetupError, msg end if $0 == __FILE__ begin ToplevelInstaller.invoke rescue SetupError raise if $DEBUG $stderr.puts $!.message $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." exit 1 end end feed2imap-1.2/Rakefile0000644000175000017500000000304512207251102015061 0ustar terceiroterceirorequire 'rake/testtask' require 'rdoc/task' require 'rake/packagetask' require 'rake' require 'find' task :default => [:test] PKG_NAME = 'feed2imap' PKG_VERSION = '1.2' PKG_FILES = [ 'ChangeLog', 'README', 'COPYING', 'setup.rb', 'Rakefile'] Find.find('bin/', 'lib/', 'test/', 'data/') do |f| if FileTest.directory?(f) and f =~ /\.svn/ Find.prune else PKG_FILES << f end end Rake::TestTask.new do |t| t.libs << "libs/feed2imap" t.libs << "test" t.test_files = FileList['test/tc_*.rb'] - ['test/tc_httpfetcher.rb'] end RDoc::Task.new do |rd| rd.main = 'README' rd.rdoc_files.include('lib/*.rb', 'lib/feed2imap/*.rb') rd.options << '--all' rd.options << '--diagram' rd.options << '--fileboxes' rd.options << '--inline-source' rd.options << '--line-numbers' rd.rdoc_dir = 'rdoc' end Rake::PackageTask.new(PKG_NAME, PKG_VERSION) do |p| p.need_tar = true p.need_zip = true p.package_files = PKG_FILES end # "Gem" part of the Rakefile begin require 'rubygems/package_task' spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = "RSS/Atom feed aggregator" s.name = PKG_NAME s.version = PKG_VERSION s.add_runtime_dependency 'ruby-feedparser', '0.9' s.require_path = 'lib' s.executables = PKG_FILES.grep(%r{\Abin\/.}).map { |bin| bin.gsub(%r{\Abin/}, '') } s.files = PKG_FILES s.description = "RSS/Atom feed aggregator" s.authors = ['Lucas Nussbaum'] end Gem::PackageTask.new(spec) do |pkg| pkg.need_zip = true pkg.need_tar = true end rescue LoadError puts "Will not generate gem." end feed2imap-1.2/lib/0000755000175000017500000000000012207251241014164 5ustar terceiroterceirofeed2imap-1.2/lib/feed2imap.rb0000644000175000017500000000003611442712411016345 0ustar terceiroterceirorequire 'feed2imap/feed2imap' feed2imap-1.2/lib/feed2imap/0000755000175000017500000000000012207251241016020 5ustar terceiroterceirofeed2imap-1.2/lib/feed2imap/feed2imap.rb0000644000175000017500000002427712207243010020210 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server Copyright (c) 2005 Lucas Nussbaum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA =end # Feed2Imap version F2I_VERSION = '1.0' F2I_WARNFETCHTIME = 10 require 'feed2imap/config' require 'feed2imap/cache' require 'feed2imap/httpfetcher' require 'logger' require 'thread' require 'feedparser' require 'feed2imap/itemtomail' require 'open3' class Feed2Imap def Feed2Imap.version return F2I_VERSION end def initialize(verbose, cacherebuild, configfile) @logger = Logger::new(STDOUT) if verbose == :debug @logger.level = Logger::DEBUG require 'pp' elsif verbose == true @logger.level = Logger::INFO else @logger.level = Logger::WARN end @logger.info("Feed2Imap V.#{F2I_VERSION} started") # reading config @logger.info('Reading configuration file ...') if not File::exist?(configfile) @logger.fatal("Configuration file #{configfile} not found.") exit(1) end if (File::stat(configfile).mode & 044) != 0 @logger.warn("Configuration file is readable by other users. It " + "probably contains your password.") end begin File::open(configfile) { |f| @config = F2IConfig::new(f) } rescue @logger.fatal("Error while reading configuration file, exiting: #{$!}") exit(1) end if @logger.level == Logger::DEBUG @logger.debug("Configuration read:") pp(@config) end # init cache @logger.info('Initializing cache ...') @cache = ItemCache::new(@config.updateddebug) if not File::exist?(@config.cache + '.lock') f = File::new(@config.cache + '.lock', 'w') f.close end if File::new(@config.cache + '.lock', 'w').flock(File::LOCK_EX | File::LOCK_NB) == false @logger.fatal("Another instance of feed2imap is already locking the cache file") exit(1) end if not File::exist?(@config.cache) @logger.warn("Cache file #{@config.cache} not found, using a new one") else File::open(@config.cache) do |f| @cache.load(f) end end # connecting all IMAP accounts @logger.info('Connecting to IMAP accounts ...') @config.imap_accounts.each_value do |ac| begin ac.connect rescue @logger.fatal("Error while connecting to #{ac}, exiting: #{$!}") exit(1) end end # for each feed, fetch, upload to IMAP and cache @logger.info("Fetching and filtering feeds ...") ths = [] mutex = Mutex::new sparefetchers = 16 # max number of fetchers running at the same time. sparefetchers_mutex = Mutex::new sparefetchers_cond = ConditionVariable::new @config.feeds.each do |f| ths << Thread::new(f) do |feed| begin mutex.lock lastcheck = @cache.get_last_check(feed.name) if feed.needfetch(lastcheck) mutex.unlock sparefetchers_mutex.synchronize do while sparefetchers <= 0 sparefetchers_cond.wait(sparefetchers_mutex) end sparefetchers -= 1 end fetch_start = Time::now if feed.url fetcher = HTTPFetcher::new fetcher::timeout = @config.timeout s = fetcher::fetch(feed.url, @cache.get_last_check(feed.name)) elsif feed.execurl # avoid running more than one command at the same time. # We need it because the called command might not be # thread-safe, and we need to get the right exitcode mutex.lock s = %x{#{feed.execurl}} if $?.exitstatus != 0 @logger.warn("Command for #{feed.name} exited with status #{$?.exitstatus} !") end mutex.unlock else @logger.warn("No way to fetch feed #{feed.name} !") end if feed.filter and s != nil # avoid running more than one command at the same time. # We need it because the called command might not be # thread-safe, and we need to get the right exitcode. mutex.lock # hack hack hack, avoid buffering problems stdin, stdout, stderr = Open3::popen3(feed.filter) inth = Thread::new do stdin.puts s stdin.close end output = nil outh = Thread::new do output = stdout.read end inth.join outh.join s = output if $?.exitstatus != 0 @logger.warn("Filter command for #{feed.name} exited with status #{$?.exitstatus}. Output might be corrupted !") end mutex.unlock end if Time::now - fetch_start > F2I_WARNFETCHTIME @logger.info("Fetching feed #{feed.name} took #{(Time::now - fetch_start).to_i}s") end sparefetchers_mutex.synchronize do sparefetchers += 1 sparefetchers_cond.signal end mutex.lock feed.body = s @cache.set_last_check(feed.name, Time::now) else @logger.debug("Feed #{feed.name} doesn't need to be checked again for now.") end mutex.unlock # dump if requested if @config.dumpdir mutex.synchronize do if feed.body fname = @config.dumpdir + '/' + feed.name + '-' + Time::now.xmlschema File::open(fname, 'w') { |file| file.puts feed.body } end end end # dump this feed if requested if feed.dumpdir mutex.synchronize do if feed.body fname = feed.dumpdir + '/' + feed.name + '-' + Time::now.xmlschema File::open(fname, 'w') { |file| file.puts feed.body } end end end rescue Timeout::Error mutex.synchronize do n = @cache.fetch_failed(feed.name) m = "Timeout::Error while fetching #{feed.url}: #{$!} (failed #{n} times)" if n > @config.max_failures @logger.fatal(m) else @logger.info(m) end end rescue mutex.synchronize do n = @cache.fetch_failed(feed.name) m = "Error while fetching #{feed.url}: #{$!} (failed #{n} times)" if n > @config.max_failures @logger.fatal(m) else @logger.info(m) end end end end end ths.each { |t| t.join } @logger.info("Parsing and uploading ...") @config.feeds.each do |f| if f.body.nil? # means 304 @logger.debug("Feed #{f.name} did not change.") next end begin feed = FeedParser::Feed::new(f.body.force_encoding('UTF-8'), f.url) rescue Exception n = @cache.parse_failed(f.name) m = "Error while parsing #{f.name}: #{$!} (failed #{n} times)" if n > @config.max_failures @logger.fatal(m) else @logger.info(m) end next end begin newitems, updateditems = @cache.get_new_items(f.name, feed.items, f.always_new, f.ignore_hash) rescue @logger.fatal("Exception caught when selecting new items for #{f.name}: #{$!}") puts $!.backtrace next end @logger.info("#{f.name}: #{newitems.length} new items, #{updateditems.length} updated items.") if newitems.length > 0 or updateditems.length > 0 or @logger.level == Logger::DEBUG begin if !cacherebuild fn = f.name.gsub(/[^0-9A-Za-z]/,'') updateditems.each do |i| id = "<#{fn}-#{i.cacheditem.index}@#{@config.hostname}>" email = item_to_mail(@config, i, id, true, f.name, f.include_images, f.wrapto) f.imapaccount.updatemail(f.folder, email, id, i.date || Time::new, f.reupload_if_updated) end # reverse is needed to upload older items first (fixes gna#8986) newitems.reverse.each do |i| id = "<#{fn}-#{i.cacheditem.index}@#{@config.hostname}>" email = item_to_mail(@config, i, id, false, f.name, f.include_images, f.wrapto) f.imapaccount.putmail(f.folder, email, i.date || Time::new) end end rescue @logger.fatal("Exception caught while uploading mail to #{f.folder}: #{$!}") puts $!.backtrace @logger.fatal("We can't recover from IMAP errors, so we are exiting.") exit(1) end begin @cache.commit_cache(f.name) rescue @logger.fatal("Exception caught while updating cache for #{f.name}: #{$!}") next end end @logger.info("Finished. Saving cache ...") begin File::open("#{@config.cache}.new", 'w') { |f| @cache.save(f) } rescue @logger.fatal("Exception caught while writing new cache to #{@config.cache}.new: #{$!}") end begin File::rename("#{@config.cache}.new", @config.cache) rescue @logger.fatal("Exception caught while renaming #{@config.cache}.new to #{@config.cache}: #{$!}") end @logger.info("Closing IMAP connections ...") @config.imap_accounts.each_value do |ac| begin ac.disconnect rescue # servers tend to cause an exception to be raised here, hence the INFO level. @logger.info("Exception caught while closing connection to #{ac.to_s}: #{$!}") end end end end feed2imap-1.2/lib/feed2imap/html2text-parser.rb0000644000175000017500000000432111442712411021573 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server Copyright (c) 2005 Lucas Nussbaum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA =end require 'feed2imap/sgml-parser' # this class provides a simple SGML parser that removes HTML tags class HTML2TextParser < SGMLParser attr_reader :savedata def initialize(verbose = false) @savedata = '' @pre = false @href = nil @links = [] super(verbose) end def handle_data(data) # let's remove all CR data.gsub!(/\n/, '') if not @pre @savedata << data end def unknown_starttag(tag, attrs) case tag when 'p' @savedata << "\n\n" when 'br' @savedata << "\n" when 'b' @savedata << '*' when 'u' @savedata << '_' when 'i' @savedata << '/' when 'pre' @savedata << "\n\n" @pre = true when 'a' # find href in args @href = nil attrs.each do |a| if a[0] == 'href' @href = a[1] end end if @href @links << @href.gsub(/^("|'|)(.*)("|')$/,'\2') end end end def close super if @links.length > 0 @savedata << "\n\n" @links.each_index do |i| @savedata << "[#{i+1}] #{@links[i]}\n" end end end def unknown_endtag(tag) case tag when 'b' @savedata << '*' when 'u' @savedata << '_' when 'i' @savedata << '/' when 'pre' @savedata << "\n\n" @pre = false when 'a' if @href @savedata << "[#{@links.length}]" @href = nil end end end end feed2imap-1.2/lib/feed2imap/cache.rb0000644000175000017500000002051412202270621017410 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server Copyright (c) 2005 Lucas Nussbaum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA =end # debug mode $updateddebug = false # This class manages a cache of items # (items which have already been seen) require 'digest/md5' class ItemCache def initialize(debug = false) @channels = {} @@cacheidx = 0 $updateddebug = debug self end # Returns the really new items amongst items def get_new_items(id, items, always_new = false, ignore_hash = false) if $updateddebug puts "=======================================================" puts "GET_NEW_ITEMS FOR #{id}... (#{Time::now})" end @channels[id] ||= CachedChannel::new @channels[id].parsefailures = 0 return @channels[id].get_new_items(items, always_new, ignore_hash) end # Commit changes to the cache def commit_cache(id) @channels[id] ||= CachedChannel::new @channels[id].commit end # Get the last time the cache was updated def get_last_check(id) @channels[id] ||= CachedChannel::new @channels[id].lastcheck end # Get the last time the cache was updated def set_last_check(id, time) @channels[id] ||= CachedChannel::new @channels[id].lastcheck = time @channels[id].failures = 0 self end # Fetching failure. # returns number of failures def fetch_failed(id) @channels[id].fetch_failed end # Parsing failure. # returns number of failures def parse_failed(id) @channels[id].parse_failed end # Load the cache from an IO stream def load(io) begin @@cacheidx, @channels = Marshal.load(io) rescue @channels = Marshal.load(io) @@cacheidx = 0 end end # Save the cache to an IO stream def save(io) Marshal.dump([@@cacheidx, @channels], io) end # Return the number of channels in the cache def nbchannels @channels.length end # Return the number of items in the cache def nbitems nb = 0 @channels.each_value { |c| nb += c.nbitems } nb end def ItemCache.getindex i = @@cacheidx @@cacheidx += 1 i end end class CachedChannel # Size of the cache for each feed # 100 items should be enough for everybody, even quite busy feeds CACHESIZE = 100 attr_accessor :lastcheck, :items, :failures, :parsefailures def initialize @lastcheck = Time::at(0) @items = [] @itemstemp = [] # see below @nbnewitems = 0 @failures = 0 @parsefailures = 0 end # Let's explain @items and @itemstemp. # @items contains the CachedItems serialized to the disk cache. # The - quite complicated - get_new_items method fills in @itemstemp # but leaves @items unchanged. # Later, the commit() method replaces @items with @itemstemp and # empties @itemstemp. This way, if something wrong happens during the # upload to the IMAP server, items aren't lost. # @nbnewitems is set by get_new_items, and is used to limit the number # of (old) items serialized. # Returns the really new items amongst items def get_new_items(items, always_new = false, ignore_hash = false) # save number of new items @nbnewitems = items.length # set items' cached version if not set yet newitems = [] updateditems = [] @itemstemp = @items items.each { |i| i.cacheditem ||= CachedItem::new(i) } if $updateddebug puts "-------Items downloaded before dups removal (#{items.length}) :----------" items.each { |i| puts "#{i.cacheditem.to_s}" } end # remove dups dups = true while dups dups = false for i in 0...items.length do for j in i+1...items.length do if items[i].cacheditem == items[j].cacheditem if $updateddebug puts "## Removed duplicate #{items[j].cacheditem.to_s}" end items.delete_at(j) dups = true break end end break if dups end end # debug : dump interesting info to stdout. if $updateddebug puts "-------Items downloaded after dups removal (#{items.length}) :----------" items.each { |i| puts "#{i.cacheditem.to_s}" } puts "-------Items already there (#{@items.length}) :----------" @items.each { |i| puts "#{i.to_s}" } puts "Items always considered as new: #{always_new.to_s}" puts "Items compared ignoring the hash: #{ignore_hash.to_s}" end items.each do |i| found = false # Try to find a perfect match @items.each do |j| # note that simple_compare only CachedItem, not RSSItem, so we have to use # j.simple_compare(i) and not i.simple_compare(j) if (i.cacheditem == j and not ignore_hash) or (j.simple_compare(i) and ignore_hash) i.cacheditem.index = j.index found = true # let's put j in front of itemstemp @itemstemp.delete(j) @itemstemp.unshift(j) break end # If we didn't find exact match, try to check if we have an update if j.is_ancestor_of(i) i.cacheditem.index = j.index i.cacheditem.updated = true updateditems.push(i) found = true # let's put j in front of itemstemp @itemstemp.delete(j) @itemstemp.unshift(i.cacheditem) break end end next if found # add as new i.cacheditem.create_index newitems.push(i) # add i.cacheditem to @itemstemp @itemstemp.unshift(i.cacheditem) end if $updateddebug puts "-------New items :----------" newitems.each { |i| puts "#{i.cacheditem.to_s}" } puts "-------Updated items :----------" updateditems.each { |i| puts "#{i.cacheditem.to_s}" } end return [newitems, updateditems] end def commit # too old items must be dropped n = @nbnewitems > CACHESIZE ? @nbnewitems : CACHESIZE @items = @itemstemp[0..n] if $updateddebug puts "Committing: new items: #{@nbnewitems} / items kept: #{@items.length}" end @itemstemp = [] self end # returns the number of items def nbitems @items.length end def parse_failed @parsefailures = 0 if @parsefailures.nil? @parsefailures += 1 return @parsefailures end def fetch_failed @failures = 0 if @failures.nil? @failures += 1 return @failures end end # This class is the only thing kept in the cache class CachedItem attr_reader :title, :link, :creator, :date, :hash attr_accessor :index attr_accessor :updated def initialize(item) @title = item.title @link = item.link @date = item.date @creator = item.creator if item.content.nil? @hash = nil else @hash = Digest::MD5.hexdigest(item.content.to_s) end end def ==(other) if $updateddebug puts "Comparing #{self.to_s} and #{other.to_s}:" puts "Title: #{@title == other.title}" puts "Link: #{@link == other.link}" puts "Creator: #{@creator == other.creator}" puts "Date: #{@date == other.date}" puts "Hash: #{@hash == other.hash}" end @title == other.title and @link == other.link and (@creator.nil? or other.creator.nil? or @creator == other.creator) and (@date.nil? or other.date.nil? or @date == other.date) and @hash == other.hash end def simple_compare(other) @title == other.title and @link == other.link and (@creator.nil? or other.creator.nil? or @creator == other.creator) end def create_index @index = ItemCache.getindex end def is_ancestor_of(other) (@link and other.link and @link == other.link) and ((@creator and other.creator and @creator == other.creator) or (@creator.nil?)) end def to_s "\"#{@title}\" #{@creator}/#{@date} #{@link} #{@hash}" end end feed2imap-1.2/lib/feed2imap/httpfetcher.rb0000644000175000017500000000706212202270621020670 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server Copyright (c) 2005 Lucas Nussbaum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA =end require 'zlib' require 'net/http' # get openssl if available begin require 'net/https' rescue LoadError end require 'uri' # max number of redirections MAXREDIR = 5 HTTPDEBUG = false # Class used to retrieve the feed over HTTP class HTTPFetcher @timeout = 30 # should be enough for everybody... def timeout=(value) @timeout = value end def fetcher(baseuri, uri, lastcheck, recursion) proxy_host = nil proxy_port = nil proxy_user = nil proxy_pass = nil if ENV['http_proxy'] proxy_uri = URI.parse(ENV['http_proxy']) proxy_host = proxy_uri.host proxy_port = proxy_uri.port proxy_user, proxy_pass = proxy_uri.userinfo.split(/:/) if proxy_uri.userinfo end http = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass ).new(uri.host, uri.port) http.read_timeout = @timeout http.open_timeout = @timeout if uri.scheme == 'https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end if defined?(Feed2Imap) useragent = "Feed2Imap v#{Feed2Imap.version} http://home.gna.org/feed2imap/" else useragent = 'Feed2Imap http://home.gna.org/feed2imap/' end headers = { 'User-Agent' => useragent, 'Accept-Encoding' => 'gzip', } if lastcheck != Time::at(0) headers.merge!('If-Modified-Since' => lastcheck.httpdate) end req = Net::HTTP::Get::new(uri.request_uri, headers) if uri.userinfo login, pw = uri.userinfo.split(':') req.basic_auth(login, pw) # workaround. eg. wikini redirects and loses auth info. elsif uri.host == baseuri.host and baseuri.userinfo login, pw = baseuri.userinfo.split(':') req.basic_auth(login, pw) end begin response = http.request(req) rescue Timeout::Error raise "Timeout while fetching #{baseuri.to_s}" end case response when Net::HTTPSuccess case response['Content-Encoding'] when 'gzip' return Zlib::GzipReader.new(StringIO.new(response.body)).read else return response.body end when Net::HTTPRedirection # if not modified if Net::HTTPNotModified === response puts "HTTPNotModified on #{uri}" if HTTPDEBUG return nil end if recursion > 0 redir = URI::join(uri.to_s, response['location']) return fetcher(baseuri, redir, lastcheck, recursion - 1) else raise "Too many redirections while fetching #{baseuri.to_s}" end else raise "#{response.code}: #{response.message} while fetching #{baseuri.to_s}" end end def fetch(url, lastcheck) uri = URI::parse(url) return fetcher(uri, uri, lastcheck, MAXREDIR) end end feed2imap-1.2/lib/feed2imap/rexml_patch.rb0000644000175000017500000000252512202271166020662 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server Copyright (c) 2005 Lucas Nussbaum This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA =end require 'feedparser' # Patch for REXML # Very ugly patch to make REXML error-proof. # The problem is REXML uses IConv, which isn't error-proof at all. # With those changes, it uses unpack/pack with some error handling module REXML module Encoding def decode(str) return str.encode(@encoding) end def encode(str) return str end def encoding=(enc) return if defined? @encoding and enc == @encoding @encoding = enc || 'utf-8' end end class Element def children @children end end end feed2imap-1.2/lib/feed2imap/sgml-parser.rb0000644000175000017500000001636511442712411020615 0ustar terceiroterceiro# A parser for SGML, using the derived class as static DTD. # from http://raa.ruby-lang.org/project/html-parser class SGMLParser # Regular expressions used for parsing: Interesting = /[&<]/ Incomplete = Regexp.compile('&([a-zA-Z][a-zA-Z0-9]*|#[0-9]*)?|' + '<([a-zA-Z][^<>]*|/([a-zA-Z][^<>]*)?|' + '![^<>]*)?') Entityref = /&([a-zA-Z][-.a-zA-Z0-9]*)[^-.a-zA-Z0-9]/ Charref = /&#([0-9]+)[^0-9]/ Starttagopen = /<[>a-zA-Z]/ Endtagopen = /<\/[<>a-zA-Z]/ Endbracket = /[<>]/ Special = /]*>/ Commentopen = /