#! /usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
#       feednotice.py
#       
#       Copyright © 2008, Florian Birée <florian@biree.name>
#       
#       Thanks to Ryan Paul (http://identi.ca/segphault)
#       
#       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 3 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 <http://www.gnu.org/licenses/>.
#       

###############################################################################
"""Read syndication feed, and put them on a laconi.ca site

The script (if run standalone) or the PressRevue class take two arguments:
a feed registration file path, and the time (in minutes) to refresh feeds.

The registration file is a text file where each line follow:
username, password, http://laconica.site/, http://syndication.feed/
or begin by a # for a coment.
"""

__author__ = "Florian Birée"
__version__ = "0.1.0"
__license__ = "GPL"
__copyright__ = "Copyright © 2008, Florian Birée"
__revision__ = "$Revision: $"
__date__ = "$Date: $"

import os
import sys
import feedparser
import time
import urllib
import urllib2

class PressRevue:
    """This class check at a given interval a list of syndication feeds, and
    send the result to corresponding laconi.ca account.
    
    use the run() method to start the loop.
    """
    
    def __init__(self, feed_registration_file, interval):
        """Initialize the class with the path of a feed_registration_file, and
        define the check interval (in minute).
        """
        self.feed_registration_file = feed_registration_file
        self.interval = interval
        self.stop = False
        self.last_check = time.gmtime()
    
    def get_subscription_list(self):
        """Return the list of registred feeds.
        
        Here a registred feed is a dict with "username", "password", "site",
        "url" keys.
        """
        subscription_list = []
        register_file = open(self.feed_registration_file, 'r')
        for line in register_file:
            line = line.strip()
            if not line.startswith('#'):
                fields = [field.strip() for field in line.split(',')]
                subscription_list.append({
                    'username': fields[0],
                    'password': fields[1],
                    'site': fields[2],
                    'url': fields[3],
                })
        register_file.close()
        return subscription_list
    
    def run(self):
        """Start the main loop to parse feeds"""
        try:
            while not self.stop:
                print self.last_check
                subscription_list = self.get_subscription_list()
                for subscription in subscription_list:
                    feed_content = feedparser.parse(subscription['url'])
                    for item in feed_content['items']:
                        if item['updated_parsed'] > self.last_check:
                            self.post(
                                subscription['username'],
                                subscription['password'],
                                subscription['site'],
                                item['title'],
                                item['link'],
                            )
                self.last_check = time.gmtime()
                time.sleep(self.interval * 60)
        except KeyboardInterrupt:
            sys.exit(0)
    
    def post(self, username, password, site, title, link):
        """Send the notice to the site"""
        message = '%(title)s: %(link)s' % {
            'title': title,
            'link': link,
        }
        
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        opener.open(urllib2.Request("%s/main/login" % site,
        urllib.urlencode({"nickname": username, "password": password}))).read()
        
        out = opener.open(urllib2.Request("%s/notice/new" % site,
                urllib.urlencode({"status_textarea": message}))).read()


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print >> sys.stderr, "Usage: %s feed_registration_file interval" % \
                                                                sys.argv[0]
        sys.exit(1)
    PressRevue(sys.argv[1], int(sys.argv[2])).run()
