summaryrefslogtreecommitdiff
path: root/feed-transmission.py
blob: 167dd6b4bc0f175d3f62487d2aef4d32d4133643 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env python

import feedparser
import re
import time
import subprocess
import urllib2
import tempfile
import json

class ConfigParticipant(object):
    def _import_attribute(self, config, key, cast, default):
        if key in config:
            try:
                v = cast(config[key])
            except StandardError as e:
                print "Failed to cast value of %s '%s' to %s: %s" % (key, config[key], cast, e)
                return default
            return v
        else:
            return default

    def _import_list(self, config, key, cast):
        va = self._import_attribute(config, key, list, [])
        va_objs = []
        for v in va:
            try:
                v = cast(v)
            except StandardError as e:
                print "Failed to cast value of %s '%s' to %s: %s" % (key, config[key], cast, e)
                continue
            va_objs.append(v)
        return va_objs

    def _import_data_for_list(self, data, key, obj_list):
        if key not in data:
            return
        try:
            l = list(data[key])
        except TypeError:
            print "Failed to load list for key %s" % key
            return
        for i, v in enumerate(l):
            if i < len(obj_list):
                obj_list[i].import_data(v)
            else:
                print "Too many elements in data - data may be out-of-date"

class App(ConfigParticipant):
    def __init__(self):
        self.feeds = []
        self.config_filename = None
        self.data_filename = None

    def load_config(self, json_filename):
        self.config_filename = json_filename
        try:
            fd = file(self.config_filename)
        except IOError:
            print "No config file"
            return
        self.import_config(json.load(fd))
        fd.close()

    def save_config(self):
        fd = file(self.config_filename, "w")
        json.dump(self.export_data(), fd)
        fd.close()

    def load_data(self, json_filename):
        self.data_filename = json_filename
        try:
            fd = file(json_filename)
        except IOError:
            print "No data file"
            return
        self.import_data(json.load(fd))
        fd.close()

    def save_data(self):
        fd = file(self.data_filename, "w")
        json.dump(self.export_data(), fd)
        fd.close()

    def import_config(self, config):
        self.feeds = self._import_list(config, "feeds", Feed.import_config)

    def export_config(self):
        return {
            "feeds": [f.export_config() for f in self.feeds],
        }

    def import_data(self, data):
        self._import_data_for_list(data, "feeds", self.feeds)

    def export_data(self):
        return {
            "feeds": [f.export_data() for f in self.feeds],
        }

    def setup_env(self):
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        urllib2.install_opener(opener)

    def get_next_feed(self):
        """Returns a (delay, feed) tuple of time to delay before next feed, and
           next feed to run
        """
        next_expiration = None
        next_feed = None
        for feed in self.feeds:
            expir = feed.poll_delay + feed.last_load
            if next_expiration < expir:
                next_expiration = expir
                next_feed = feed
        delay = next_expiration - int(time.time())
        if delay < 0:
            delay = 0
        return (delay, next_feed)

    def _run_relavent(self, feed):
        found = feed.find_relavant()
        for i in found:
            # download file here instead of relying on transmission since we may
            # have cookies that transmission does not
            f = urllib2.urlopen(i)
            temp = tempfile.NamedTemporaryFile()
            temp.write(f.read())
            f.close()
            temp.flush()
            ret = subprocess.call(["transmission-remote", "localhost", "-a", temp.name])
            temp.close()
            if ret:
                print "Error adding torrent"
        self.save_data()

    def main(self):
        try:
            for feed in self.feeds:
                self._run_relavent(feed)
            while True:
                (delay, feed) = self.get_next_feed()
                time.sleep(delay)
                try:
                    self._run_relavent(feed)
                except urllib2.URLError, e:
                    print e
        except KeyboardInterrupt:
            pass

class Feed(ConfigParticipant):
    def __init__(self):
        self.url = None
        # in seconds
        self.poll_delay = 60 * 60
        # list of Matcher objects
        self.matches = None
        # initialize to Epoch. Should always be integer number of seconds since
        # Epoch
        self.last_load = 0
        # true when the default action (when no matcher matches) should be to
        # count the item as relavant
        self.default_white = False
        self.seen = []

    def _load_feed(self):
        self.last_load = int(time.time())
        f = urllib2.urlopen(self.url)
        d = feedparser.parse(f.read())
        f.close()
        return d

    def find_relavant(self):
        d = self._load_feed()
        found = []
        print "New RSS Items:"
        for i in d['items']:
            if i.link in self.seen:
                continue
            self.seen.append(i.link)
            print " ", i.title
            white = self.default_white
            for m in self.matches:
                if not m.matches(i):
                    continue
                print "    Matched.  White:", m.white
                m.matched_count += 1
                white = m.white
            if white:
                found.append(i.link)
        self.seen = self.seen[-len(d['items']):]
        return found

    @staticmethod
    def import_config(config):
        f = Feed()
        f.url = f._import_attribute(config, "url", str, f.url)
        f.poll_delay = f._import_attribute(config, "poll_delay", int, f.poll_delay)
        f.matches = f._import_list(config, "matches", Matcher.import_config)
        f.default_white = f._import_attribute(config, "default_white", bool, f.default_white)
        return f

    def export_config(self):
        return {
            "url": self.url,
            "poll_delay": self.poll_delay,
            "matches": [m.export_config() for m in self.matches],
            "default_white": self.white,
        }

    def import_data(self, data):
        self.seen = self._import_list(data, "seen", str)
        self._import_data_for_list(data, "matches", self.matches)

    def export_data(self):
        return {
            "seen": self.seen,
            "matches": [m.export_data() for m in self.matches],
        }

class Matcher(ConfigParticipant):
    def __init__(self):
        self.str = None
        self.re = None
        # white marks item to be downloaded, black means don't download
        # similar to white and black lists
        self.white = True
        self.matched_count = 0

    @staticmethod
    def import_config(config):
        m = Matcher()
        m.white = m._import_attribute(config, "white", bool, m.white)
        m.str = m._import_attribute(config, "value", str, m.str)
        m.matched_count = m._import_attribute(config, "matched_count", int, m.matched_count)
        m.re = re.compile(m.str)
        return m

    def export_config(self):
        return {
            "white": self.white,
            "str": self.str,
            "matched_count": self.matched_count,
        }

    def import_data(self, data):
        self.matched_count = self._import_attribute(data, "matched_count", int, self.matched_count)

    def export_data(self):
        return {
            "matched_count": self.matched_count,
        }

    def matches(self, item):
        return self.re.match(item.title)

if __name__ == "__main__":
    app = App()
    app.load_config('.feed-transmission.json')
    app.load_data(".feed-transmission.data")
    app.setup_env()
    app.main()