feed2imap-1.2.5/0000755000175000017500000000000012523766471013602 5ustar terceiroterceirofeed2imap-1.2.5/lib/0000755000175000017500000000000012523766471014350 5ustar terceiroterceirofeed2imap-1.2.5/lib/feed2imap.rb0000644000175000017500000000003611442712411016510 0ustar terceiroterceirorequire 'feed2imap/feed2imap' feed2imap-1.2.5/lib/feed2imap/0000755000175000017500000000000012523766471016204 5ustar terceiroterceirofeed2imap-1.2.5/lib/feed2imap/imap.rb0000644000175000017500000001145412277125122017450 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 # Imap connection handling require 'net/imap' begin require 'openssl' rescue LoadError end require 'uri' # This class is a container of IMAP accounts. # Thanks to it, accounts are re-used : several feeds # using the same IMAP account will create only one # IMAP connection. class ImapAccounts < Hash def add_account(uri) u = URI::Generic::build({ :scheme => uri.scheme, :userinfo => uri.userinfo, :host => uri.host, :port => uri.port }) if not include?(u) ac = ImapAccount::new(u) self[u] = ac end return self[u] end end # This class is an IMAP account, with the given fd # once the connection has been established class ImapAccount attr_reader :uri @@no_ssl_verify = false def ImapAccount::no_ssl_verify=(v) @@no_ssl_verify = v end def initialize(uri) @uri = uri @existing_folders = [] self end # connects to the IMAP server # raises an exception if it fails def connect port = 143 usessl = false if uri.scheme == 'imap' port = 143 usessl = false elsif uri.scheme == 'imaps' port = 993 usessl = true else raise "Unknown scheme: #{uri.scheme}" end # use given port if port given port = uri.port if uri.port @connection = Net::IMAP::new(uri.host, port, usessl, nil, !@@no_ssl_verify) user, password = URI::unescape(uri.userinfo).split(':',2) @connection.login(user, password) self end # disconnect from the IMAP server def disconnect if @connection @connection.logout @connection.disconnect end end # tests if the folder exists and create it if not def create_folder_if_not_exists(folder) return if @existing_folders.include?(folder) if @connection.list('', folder).nil? @connection.create(folder) @connection.subscribe(folder) end @existing_folders << folder end # Put the mail in the given folder # You should check whether the folder exist first. def putmail(folder, mail, date = Time::now) create_folder_if_not_exists(folder) @connection.append(folder, mail.gsub(/\n/, "\r\n"), nil, date) end # update a mail def updatemail(folder, mail, id, date = Time::now, reupload_if_updated = true) create_folder_if_not_exists(folder) @connection.select(folder) searchres = @connection.search(['HEADER', 'Message-Id', id]) flags = nil if searchres.length > 0 # we get the flags from the first result and delete everything flags = @connection.fetch(searchres[0], 'FLAGS')[0].attr['FLAGS'] searchres.each { |m| @connection.store(m, "+FLAGS", [:Deleted]) } @connection.expunge flags -= [ :Recent ] # avoids errors with dovecot elsif not reupload_if_updated # mail not present, and we don't want to re-upload it return end @connection.append(folder, mail.gsub(/\n/, "\r\n"), flags, date) end # convert to string def to_s u2 = uri.clone u2.password = 'PASSWORD' u2.to_s end # remove mails in a folder according to a criteria def cleanup(folder, dryrun = false) puts "-- Considering #{folder}:" @connection.select(folder) a = ['SEEN', 'NOT', 'FLAGGED', 'BEFORE', (Date::today - 3).strftime('%d-%b-%Y')] todel = @connection.search(a) todel.each do |m| f = @connection.fetch(m, "FULL") d = f[0].attr['INTERNALDATE'] s = f[0].attr['ENVELOPE'].subject if s =~ /^=\?utf-8\?b\?/ s = Base64::decode64(s.gsub(/^=\?utf-8\?b\?(.*)\?=$/, '\1')).force_encoding('utf-8') elsif s =~ /^=\?iso-8859-1\?b\?/ s = Base64::decode64(s.gsub(/^=\?iso-8859-1\?b\?(.*)\?=$/, '\1')).force_encoding('iso-8859-1').encode('utf-8') end if dryrun puts "To remove: #{s} (#{d})" else puts "Removing: #{s} (#{d})" @connection.store(m, "+FLAGS", [:Deleted]) end end puts "-- Deleted #{todel.length} messages." if not dryrun @connection.expunge end return todel.length end end feed2imap-1.2.5/lib/feed2imap/cache.rb0000644000175000017500000002051412336254241017563 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.5/lib/feed2imap/feed2imap.rb0000644000175000017500000002445012523766442020370 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.2.5' 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 begin 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 ensure mutex.unlock end 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.5/lib/feed2imap/httpfetcher.rb0000644000175000017500000000706212202270621021033 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.5/lib/feed2imap/rexml_patch.rb0000644000175000017500000000252512277125122021027 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.5/lib/feed2imap/config.rb0000644000175000017500000001252612455267526020005 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 'yaml' require 'uri' require 'feed2imap/imap' require 'feed2imap/maildir' require 'etc' require 'socket' require 'set' # Default cache file DEFCACHE = ENV['HOME'] + '/.feed2imap.cache' # Hostname and login name of the current user HOSTNAME = Socket.gethostname LOGNAME = Etc.getlogin # Feed2imap configuration class F2IConfig attr_reader :imap_accounts, :cache, :feeds, :dumpdir, :updateddebug, :max_failures, :include_images, :default_email, :hostname, :reupload_if_updated, :parts, :timeout # Load the configuration from the IO stream # TODO should do some sanity check on the data read. def initialize(io) @conf = YAML::load(io) @cache = @conf['cache'] || DEFCACHE @dumpdir = @conf['dumpdir'] || nil @conf['feeds'] ||= [] @feeds = [] @max_failures = (@conf['max-failures'] || 10).to_i @updateddebug = false @updateddebug = @conf['debug-updated'] if @conf.has_key?('debug-updated') @parts = %w(text html) @parts = Array(@conf['parts']) if @conf.has_key?('parts') && !@conf['parts'].empty? @parts = Set.new(@parts) @include_images = true @include_images = @conf['include-images'] if @conf.has_key?('include-images') @parts << 'html' if @include_images && ! @parts.include?('html') @reupload_if_updated = true @reupload_if_updated = @conf['reupload-if-updated'] if @conf.has_key?('reupload-if-updated') @timeout = if @conf['timeout'] == nil then 30 else @conf['timeout'].to_i end @default_email = (@conf['default-email'] || "#{LOGNAME}@#{HOSTNAME}") ImapAccount.no_ssl_verify = (@conf.has_key?('disable-ssl-verification') and @conf['disable-ssl-verification'] == true) @hostname = HOSTNAME # FIXME: should this be configurable as well? @imap_accounts = ImapAccounts::new maildir_account = MaildirAccount::new @conf['feeds'].each do |f| f['name'] = f['name'].to_s if f['disable'].nil? uri = URI::parse(Array(f['target']).join('')) path = URI::unescape(uri.path) if uri.scheme == 'maildir' @feeds.push(ConfigFeed::new(f, maildir_account, path, self)) else # remove leading slash from IMAP mailbox names path = path[1..-1] if path[0,1] == '/' @feeds.push(ConfigFeed::new(f, @imap_accounts.add_account(uri), path, self)) end end end end def to_s s = "Your Feed2Imap config :\n" s += "=======================\n" s += "Cache file: #{@cache}\n\n" s += "Imap accounts I'll have to connect to :\n" s += "---------------------------------------\n" @imap_accounts.each_value { |i| s += i.to_s + "\n" } s += "\nFeeds :\n" s += "-------\n" i = 1 @feeds.each do |f| s += "#{i}. #{f.name}\n" s += " URL: #{f.url}\n" s += " IMAP Account: #{f.imapaccount}\n" s += " Folder: #{f.folder}\n" if not f.wrapto s += " Not wrapped.\n" end s += "\n" i += 1 end s end end # A configured feed. simple data container. class ConfigFeed attr_reader :name, :url, :imapaccount, :folder, :always_new, :execurl, :filter, :ignore_hash, :dumpdir, :wrapto, :include_images, :reupload_if_updated attr_accessor :body def initialize(f, imapaccount, folder, f2iconfig) @name = f['name'] @url = f['url'] @url.sub!(/^feed:/, '') if @url =~ /^feed:/ @imapaccount = imapaccount @folder = encode_utf7 folder @freq = f['min-frequency'] @always_new = false @always_new = f['always-new'] if f.has_key?('always-new') @execurl = f['execurl'] @filter = f['filter'] @ignore_hash = false @ignore_hash = f['ignore-hash'] if f.has_key?('ignore-hash') @freq = @freq.to_i if @freq @dumpdir = f['dumpdir'] || nil @wrapto = if f['wrapto'] == nil then 72 else f['wrapto'].to_i end @include_images = f2iconfig.include_images @include_images = f['include-images'] if f.has_key?('include-images') @reupload_if_updated = f2iconfig.reupload_if_updated @reupload_if_updated = f['reupload-if-updated'] if f.has_key?('reupload-if-updated') end def needfetch(lastcheck) return true if @freq.nil? return (lastcheck + @freq * 3600) < Time::now end def encode_utf7(s) if "foo".respond_to?(:force_encoding) return Net::IMAP::encode_utf7 s else # this is a copy of the Net::IMAP::encode_utf7 w/o the force_encoding return s.gsub(/(&)|([^\x20-\x7e]+)/u) { if $1 "&-" else base64 = [$&.unpack("U*").pack("n*")].pack("m") "&" + base64.delete("=\n").tr("/", ",") + "-" end } end end end feed2imap-1.2.5/lib/feed2imap/itemtomail.rb0000644000175000017500000001160012523765052020665 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server Copyright (c) 2005 Lucas Nussbaum This file contains classes to parse a feed and store it as a Channel object. 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 'rexml/document' require 'time' require 'rmail' require 'feedparser' require 'feedparser/text-output' require 'feedparser/html-output' require 'base64' require 'rmail' require 'digest/md5' class String def needMIME utf8 = false begin self.unpack('U*').each do |c| if c > 127 utf8 = true break end end rescue # safe fallback in case of problems utf8 = true end utf8 end end def item_to_mail(config, item, id, updated, from = 'Feed2Imap', inline_images = false, wrapto = false) message = RMail::Message::new if item.creator and item.creator != '' if item.creator.include?('@') message.header['From'] = item.creator.chomp else message.header['From'] = "=?utf-8?b?#{Base64::encode64(item.creator.chomp).gsub("\n",'')}?= <#{config.default_email}>" end else message.header['From'] = "=?utf-8?b?#{Base64::encode64(from).gsub("\n",'')}?= <#{config.default_email}>" end message.header['To'] = "=?utf-8?b?#{Base64::encode64(from).gsub("\n",'')}?= <#{config.default_email}>" if item.date.nil? message.header['Date'] = Time::new.rfc2822 else message.header['Date'] = item.date.rfc2822 end message.header['X-Feed2Imap-Version'] = F2I_VERSION if defined?(F2I_VERSION) message.header['Message-Id'] = id message.header['X-F2IStatus'] = "Updated" if updated # treat subject. Might need MIME encoding. subj = item.title or (item.date and item.date.to_s) or item.link if subj if subj.needMIME message.header['Subject'] = "=?utf-8?b?#{Base64::encode64(subj).gsub("\n",'')}?=" else message.header['Subject'] = subj end end textpart = htmlpart = nil parts = config.parts if parts.include?('text') textpart = parts.size == 1 ? message : RMail::Message::new textpart.header['Content-Type'] = 'text/plain; charset=utf-8; format=flowed' textpart.header['Content-Transfer-Encoding'] = '8bit' textpart.body = item.to_text(true, wrapto, false) end if parts.include?('html') htmlpart = parts.size == 1 ? message : RMail::Message::new htmlpart.header['Content-Type'] = 'text/html; charset=utf-8' htmlpart.header['Content-Transfer-Encoding'] = '8bit' htmlpart.body = item.to_html end # inline images as attachments imgs = [] if inline_images cids = [] htmlpart.body.gsub!(/(]+)src="(\S+?\/([^\/]+?\.(png|gif|jpe?g)))"([^>]*>)/i) do |match| # $2 contains url, $3 the image name, $4 the image extension begin fetcher = HTTPFetcher.new image = Base64.encode64(fetcher.fetch($2, Time.at(0)).chomp) + "\n" cid = "#{Digest::MD5.hexdigest($2)}@#{config.hostname}" if not cids.include?(cid) cids << cid imgpart = RMail::Message.new imgpart.header.set('Content-ID', "<#{cid}>") type = $4 type = 'jpeg' if type.downcase == 'jpg' # hack hack hack imgpart.header.set('Content-Type', "image/#{type}", 'name' => $3) imgpart.header.set('Content-Disposition', 'attachment', 'filename' => $3) imgpart.header.set('Content-Transfer-Encoding', 'base64') imgpart.body = image imgs << imgpart end # now to specify what to replace with newtag = "#{$1}src=\"cid:#{cid}\"#{$5}" #print "#{cid}: Replacing '#{$&}' with '#{newtag}'...\n" newtag rescue #print "Error while fetching image #{$2}: #{$!}...\n" $& # don't modify on exception end end end if imgs.length > 0 message.header.set('Content-Type', 'multipart/related', 'type'=> 'multipart/alternative') texthtml = RMail::Message::new texthtml.header.set('Content-Type', 'multipart/alternative') texthtml.add_part(textpart) texthtml.add_part(htmlpart) message.add_part(texthtml) imgs.each do |i| message.add_part(i) end elsif parts.size != 1 message.header['Content-Type'] = 'multipart/alternative' message.add_part(textpart) message.add_part(htmlpart) end return message.to_s end feed2imap-1.2.5/lib/feed2imap/html2text-parser.rb0000644000175000017500000000432111442712411021736 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.5/lib/feed2imap/maildir.rb0000644000175000017500000001143712415055632020146 0ustar terceiroterceiro=begin Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server, or local Maildir Copyright (c) 2009 Andreas Rottmann 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, see . =end require 'uri' require 'fileutils' require 'fcntl' require 'rmail' require 'socket' class MaildirAccount MYHOSTNAME = Socket.gethostname @@seq_num = 0 attr_reader :uri def putmail(folder, mail, date = Time::now) store_message(folder_dir(folder), date, nil) do |f| f.puts(mail) end end def updatemail(folder, mail, idx, date = Time::now, reupload_if_updated = true) dir = folder_dir(folder) guarantee_maildir(dir) mail_files = find_mails(dir, idx) flags = nil if mail_files.length > 0 # get the info from the first result and delete everything info = maildir_file_info(mail_files[0]) mail_files.each { |f| File.delete(File.join(dir, f)) } elsif not reupload_if_updated # mail not present, and we don't want to re-upload it return end store_message(dir, date, info) { |f| f.puts(mail) } end def to_s uri.to_s end def cleanup(folder, dryrun = false) dir = folder_dir(folder) puts "-- Considering #{dir}:" guarantee_maildir(dir) del_count = 0 recent_time = Time.now() - (3 * 24 * 60 * 60) # 3 days Dir[File.join(dir, 'cur', '*')].each do |fn| flags = maildir_file_info_flags(fn) # don't consider not-seen, flagged, or recent messages mtime = File.mtime(fn) next if (not flags.index('S') or flags.index('F') or mtime > recent_time) mail = File.open(fn) do |f| RMail::Parser.read(f) end subject = mail.header['Subject'] if dryrun puts "To remove: #{subject} #{mtime}" else puts "Removing: #{subject} #{mtime}" File.delete(fn) end del_count += 1 end puts "-- Deleted #{del_count} messages" return del_count end private def folder_dir(folder) return File.join('/', folder) end def store_message(dir, date, info, &block) guarantee_maildir(dir) stored = false Dir.chdir(dir) do |d| timer = 30 fd = nil while timer >= 0 new_fn = new_maildir_basefn(date) tmp_path = File.join(dir, 'tmp', new_fn) new_path = File.join(dir, 'new', new_fn) begin fd = IO::sysopen(tmp_path, Fcntl::O_WRONLY | Fcntl::O_EXCL | Fcntl::O_CREAT) break rescue Errno::EEXIST sleep 2 timer -= 2 next end end if fd begin f = IO.open(fd) # provide a writable interface for the caller yield f f.fsync File.link tmp_path, new_path stored = true ensure File.unlink tmp_path if File.exists? tmp_path end end if stored and info cur_path = File.join(dir, 'cur', new_fn + ':' + info) File.rename(new_path, cur_path) end end # Dir.chdir return stored end def find_mails(dir, idx) dir_paths = [] ['cur', 'new'].each do |d| subdir = File.join(dir, d) raise "#{subdir} not a directory" unless File.directory? subdir Dir[File.join(subdir, '*')].each do |fn| File.open(fn) do |f| mail = RMail::Parser.read(f) cache_index = mail.header['Message-ID'] if cache_index && (cache_index == idx || cache_index == "<#{idx}>") dir_paths.push(File.join(d, File.basename(fn))) end end end end return dir_paths end def guarantee_maildir(dir) # Ensure maildir-folderness ['new', 'cur', 'tmp'].each do |d| FileUtils.mkdir_p(File.join(dir, d)) end end def maildir_file_info(file) basename = File.basename(file) colon = basename.rindex(':') return (colon and basename[colon + 1 .. -1]) end # Re-written and no longer shamelessly taken from # http://gitorious.org/sup/mainline/blobs/master/lib/sup/maildir.rb def new_maildir_basefn(date) fn = "#{date.to_i.to_s}.#{@@seq_num.to_s}.#{MYHOSTNAME}" @@seq_num += 1 fn end def maildir_file_info_flags(fn) parts = fn.split(',') if parts.size == 1 '' else parts.last end end end feed2imap-1.2.5/lib/feed2imap/sgml-parser.rb0000644000175000017500000001636511442712411020760 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 = / ' + 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.5/ChangeLog0000644000175000017500000001615411442712411015343 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.5/test/0000755000175000017500000000000012523766471014561 5ustar terceiroterceirofeed2imap-1.2.5/test/tc_cache.rb0000755000175000017500000000432612336253331016633 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.5/test/tc_config.rb0000755000175000017500000000523112455267306017042 0ustar terceiroterceiro#!/usr/bin/ruby -w $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'test/unit' require 'feed2imap/config' require 'stringio' CONF1 = < 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.5/test/maildir/cur/1376320022.18396_5.debian:2,FS0000644000175000017500000000051212277125122022570 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.5/test/maildir/cur/1376317520.15789_1.debian:2,S0000644000175000017500000000053612415055326022502 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.5/test/maildir/cur/1376319137.17850_1.debian:2,0000644000175000017500000000051612277125122022350 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.5/test/maildir/new/0000755000175000017500000000000012523766471016773 5ustar terceiroterceirofeed2imap-1.2.5/test/maildir/new/1376320099.18396_7.debian0000644000175000017500000000047512277125122022137 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.5/test/tc_maildir.rb0000644000175000017500000000433312415055515017206 0ustar terceiroterceirorequire 'test/unit' require 'fileutils' require 'tmpdir' require 'mocha/setup' require 'feed2imap/maildir' class TestMaildir < Test::Unit::TestCase def setup @tmpdirs = [] end def teardown @tmpdirs.each do |dir| FileUtils.rm_rf(dir) end end def test_cleanup folder = create_maildir msgs = message_count(folder) four_days_ago = Time.now - (4 * 24 * 60 * 60) old_message = Dir.glob(File.join(folder, '**/*:2,S')).first FileUtils.touch old_message, mtime: four_days_ago 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.5/test/tc_httpfetcher.rb0000755000175000017500000000322012523765321020105 0ustar terceiroterceiro#!/usr/bin/ruby $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'test/unit' require 'feed2imap/httpfetcher' class HttpFetcherTest < Test::Unit::TestCase def test_get_https s = '' assert_nothing_raised do s = fetcher.fetch('https://linuxfr.org/pub/', Time::at(0)) end assert(s.length > 20) end def test_get_http end def test_get_httpnotmodif s = 'aaa' assert_nothing_raised do s = fetcher.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 = fetcher.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 = fetcher.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 = fetcher.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 = fetcher.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 = fetcher.fetch("http://ensilinx1.imag.fr/~lucas/notfound.html", Time::at(0)) end end private def fetcher HTTPFetcher.new end end feed2imap-1.2.5/data/0000755000175000017500000000000012523766471014513 5ustar terceiroterceirofeed2imap-1.2.5/data/doc/0000755000175000017500000000000012523766471015260 5ustar terceiroterceirofeed2imap-1.2.5/data/doc/feed2imap/0000755000175000017500000000000012523766471017114 5ustar terceiroterceirofeed2imap-1.2.5/data/doc/feed2imap/examples/0000755000175000017500000000000012523766471020732 5ustar terceiroterceirofeed2imap-1.2.5/data/doc/feed2imap/examples/feed2imaprc0000644000175000017500000000711512202270621023017 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.5/data/man/0000755000175000017500000000000012523766471015266 5ustar terceiroterceirofeed2imap-1.2.5/data/man/man5/0000755000175000017500000000000012523766471016126 5ustar terceiroterceirofeed2imap-1.2.5/data/man/man5/feed2imaprc.50000644000175000017500000000235211442712411020357 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.5/data/man/man1/0000755000175000017500000000000012523766471016122 5ustar terceiroterceirofeed2imap-1.2.5/data/man/man1/feed2imap-dumpconfig.10000644000175000017500000000174411442712411022157 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.5/data/man/man1/feed2imap-opmlimport.10000644000175000017500000000215011442712411022216 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.5/data/man/man1/feed2imap-cleaner.10000644000175000017500000000301411442712411021425 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.5/data/man/man1/feed2imap.10000644000175000017500000000272611442712411020027 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.5/README0000644000175000017500000000160411442712411014443 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.5/Rakefile0000644000175000017500000000320312523765640015242 0ustar terceiroterceirorequire 'rake/testtask' require 'rdoc/task' require 'rake/packagetask' require 'rake' require 'find' task :default => [:test] PKG_NAME = 'feed2imap' PKG_VERSION = `ruby -Ilib -rfeed2imap/feed2imap -e 'print F2I_VERSION'` 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.verbose = true 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.5/COPYING0000644000175000017500000004311011442712411014614 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.5/bin/0000755000175000017500000000000012523766471014352 5ustar terceiroterceirofeed2imap-1.2.5/bin/feed2imap-opmlimport0000755000175000017500000000303111442712411020311 0ustar terceiroterceiro#!/usr/bin/ruby =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 $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'rexml/document' require 'yaml' DEFAULTIMAPFOLDER = 'imap://login:password@imapserver/folder.folder2' opml = ARGV[0] doc = nil doc = REXML::Document::new(IO.read(opml)) feeds = [] doc.root.each_element('//outline') do |e| if u = e.attribute('xmlUrl') || e.attribute('htmlUrl') # dirty liferea hack next if u.value == 'vfolder' # get title t = e.attribute('text') || e.attribute('Title') || nil if t.nil? title = '*** FEED TITLE (must be unique) ***' else title = t.value end url = u.value feeds.push({'name' => title, 'url' => url, 'target' => DEFAULTIMAPFOLDER}) end end YAML::dump({'feeds' => feeds}, $stdout) feed2imap-1.2.5/bin/feed2imap-cleaner0000755000175000017500000000132511442712411017524 0ustar terceiroterceiro#!/usr/bin/ruby $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'feed2imap/feed2imap' require 'optparse' configf = ENV['HOME'] + '/.feed2imaprc' dryrun = false opts = OptionParser::new do |opts| opts.banner = "Usage: feed2imap-cleaner [options]" opts.separator "" opts.separator "Options:" opts.on("-d", "--dry-run", "Dont really remove messages") do |v| dryrun = true end opts.on("-f", "--config ", "Select alternate config file") do |f| configf = f end end opts.parse!(ARGV) config = nil File::open(configf) { |f| config = F2IConfig::new(f) } config.imap_accounts.each_value do |ac| ac.connect end config.feeds.each do |f| f.imapaccount.cleanup(f.folder, dryrun) end feed2imap-1.2.5/bin/feed2imap-dumpconfig0000755000175000017500000000254411442712411020252 0ustar terceiroterceiro#!/usr/bin/ruby =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 $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'feed2imap/config' require 'optparse' configf = ENV['HOME'] + '/.feed2imaprc' opts = OptionParser::new do |opts| opts.banner = "Usage: ./dumpconfig.rb [options]" opts.separator "" opts.separator "Options:" opts.on("-f", "--config ", "Select alternate config file") do |f| configf = f end end opts.parse!(ARGV) if not File::exist?(configf) puts "Configuration file #{configfile} not found." exit(1) end File::open(configf) { |f| puts F2IConfig::new(f).to_s } feed2imap-1.2.5/bin/feed2imap0000755000175000017500000000232111442712411016112 0ustar terceiroterceiro#!/usr/bin/ruby $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'feed2imap/feed2imap' require 'optparse' verbose = false version = false cacherebuild = false configf = ENV['HOME'] + '/.feed2imaprc' progname = File::basename($PROGRAM_NAME) opts = OptionParser::new do |opts| opts.program_name = progname opts.banner = "Usage: #{progname} [options]" opts.separator "" opts.separator "Options:" opts.on("-v", "--verbose", "Verbose mode") do |v| verbose = true end opts.on("-d", "--debug", "Debug mode") do |v| verbose = :debug end opts.on("-V", "--version", "Display Feed2Imap version") do |v| version = true end opts.on("-c", "--rebuild-cache", "Cache rebuilding run : will fetch everything and add to cache, without uploading to the IMAP server. Useful if your cache file was lost, and you don't want to re-read all the items.") do |c| cacherebuild = true end opts.on("-f", "--config ", "Select alternate config file") do |f| configf = f end end begin opts.parse!(ARGV) rescue OptionParser::ParseError => pe opts.warn pe puts opts exit 1 end if version puts "Feed2Imap v.#{F2I_VERSION}" else Feed2Imap::new(verbose, cacherebuild, configf) end