-
Notifications
You must be signed in to change notification settings - Fork 1
/
rssCatcher.py
286 lines (251 loc) · 10.2 KB
/
rssCatcher.py
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# -*- coding: utf-8 -*-
import sqlite3
import feedparser
import datetime
import sys
from feed import Feed
from episode import Episode
from chapter import Chapter
class RssCatcher:
db = None
table_feed = "feeds"
table_episodes = "episodes"
table_chapters = "chapters"
config = None
feed = None
feed_url = None
def __init__(self, config):
self.config = config
self.init_db()
def load_rss(self, feedUrl):
self.feed_url = feedUrl
print "Loading RSS Feed: " + self.feed_url
feedparser.USER_AGENT = "FeedToYoutube/0.0.3 +http://ldk.net/"
f = feedparser.parse(self.feed_url, request_headers={'content-type': 'text/html; charset=UTF-8'})
if not hasattr(f, "etag"):
if hasattr(f.feed, "updated"):
etag = f.feed.updated
else:
raise LookupError('Can\'t find any update indicator. please contact the author.')
else:
etag = f.etag
if not self._feed_has_changed(etag):
print "Nothing has changed"
return {'status': "304", "message": "Not Modified"}
if not hasattr(f.feed, "updated"):
f.feed.updated = unicode(datetime.datetime.now())
imageUrl = ""
if hasattr(f.feed, 'image') and hasattr(f.feed.image, "href"):
imageUrl = f.feed.image.href
summary = f.feed.title
if hasattr(f.feed, "summary"):
summary = f.feed.summary
feed = Feed(self.config, feedUrl,
image=imageUrl,
etag=etag,
subtitle=summary,
title=f.feed.title,
updated=f.feed.updated
)
self.save_feed(feed)
feed.episodes = []
print "Importing " + feed.title
for episode in f.entries:
sys.stdout.write(" Episode " + episode.title)
sys.stdout.flush()
if self._is_known_episode(episode.id):
print " - old"
feed.episodes.append(self.load_episode_by_rss_id(rss_episode_id=episode.id))
continue
print " - new"
is_new = True
# chapter handling
cs = []
if hasattr(episode, "psc_chapters"):
for chapter in episode.psc_chapters.chapters:
link = ""
image = ""
if hasattr(chapter, 'href'):
link = chapter.href
if hasattr(chapter, 'image'):
image = chapter.image
c = Chapter(
start=chapter.start,
image=image,
href=link,
title=chapter.title)
print "\t" + c.start + ": " + c.title + " Image= " + c.image + " Href= " + c.href
cs.append(c)
image = ""
duration = ""
if hasattr(episode, 'image') and hasattr(episode.image, "href"):
image = episode.image.href
if hasattr(episode, 'itunes_duration'):
duration = episode.itunes_duration
link = None
if hasattr(episode, "links"):
for link in episode.links:
if link.type == 'audio/mpeg':
link = link.href
break
if link is None:
continue
subtitle = ""
if hasattr(episode, "subtitle"):
subtitle = episode.subtitle
e = Episode(feed_id=feed.feed_id,
rss_episode_id=episode.id,
duration=duration,
link=link,
title=episode.title,
subtitle=subtitle,
description=episode.summary,
published=episode.published,
chapters=cs,
image=image,
is_new=is_new
)
self._insert_episode(e)
if hasattr(feed.episodes, 'append'):
feed.episodes.append(e)
self.feed = feed
return self.feed
def init_db(self):
self.db = sqlite3.connect(self.config.db_name)
self._create_tables()
def close_db(self):
self.db.close()
def save_episode(self, episode):
if episode.episode_id == "" or episode.episode_id is None:
return self._insert_episode(episode)
def save_feed(self, feed):
if feed.feed_id == "" or feed.feed_id is None:
return self._insert_feed(feed)
def _insert_feed(self, feed):
sql = "INSERT OR IGNORE INTO " + self.table_feed + \
" (url, etag, title, subtitle, image, updated)" + \
" VALUES (?, ?, ?, ?, ?, ?)"
cur = self.db.cursor()
cur.execute(sql, [feed.url, feed.etag, feed.title, feed.subtitle, str(feed.image), feed.updated])
feed.feed_id = cur.lastrowid
self.db.commit()
def _insert_episode(self, episode):
sql = "INSERT INTO " + self.table_episodes + " (rss_feed_id, " \
"rss_episode_id, " \
"duration, " \
"title, " \
"description, " \
"subtitle, " \
"link, " \
"published, " \
"image " \
") VALUES (?,?,?,?,?,?,?,?,?)"
cur = self.db.cursor()
cur.execute(sql, [episode.feed_id, episode.rss_episode_id, episode.duration, episode.title, episode.description,
episode.subtitle, episode.link, episode.published, episode.image])
episode.episode_id = cur.lastrowid
self.db.commit()
self._insert_chapters(episode)
def _insert_chapters(self, episode):
sql = "INSERT INTO " + self.table_chapters + \
"(episode_id,start, title, image, href) VALUES (?,?,?,?,?)"
cur = self.db.cursor()
for chapter in episode.chapters:
cur.execute(sql, [episode.episode_id, chapter.start, chapter.title, chapter.image, chapter.href])
self.db.commit()
def _update_episode(self, episode):
sql = "UPDATE"
def _update_feed(self, feed):
if feed.id == "" or feed.id is None:
raise RuntimeWarning("Can't update because no id found")
sql = "UPDATE"
def _create_tables(self):
sql = 'CREATE TABLE IF NOT EXISTS ' + self.table_feed + \
' ( id INTEGER PRIMARY KEY AUTOINCREMENT, ' \
'url VARCHAR UNIQUE, ' \
'etag VARCHAR, ' \
'title VARCHAR, ' \
'image BLOB, ' \
'subtitle VARCHAR, ' \
'updated DATE);'
cur = self.db.cursor()
cur.execute(sql)
cur.execute("CREATE UNIQUE INDEX IF NOT EXISTS `etag_idx` ON `" + self.table_feed + "` (`etag` )")
cur.execute("CREATE INDEX IF NOT EXISTS `id_idx` ON `" + self.table_feed + "` (`id` )")
sql = 'CREATE TABLE IF NOT EXISTS ' + self.table_episodes + \
' ( id INTEGER PRIMARY KEY AUTOINCREMENT, ' \
'rss_feed_id VARCHAR, ' \
'rss_episode_id VARCHAR NOT NULL, ' \
'title VARCHAR, ' \
'subtitle VARCHAR, ' \
'description BLOB, ' \
'image BLOB, ' \
'duration VARCHAR, link VARCHAR, chapters TEXT ,' \
'published DATE, ' \
'movie_created DATE, ' \
'youtube_upload_date DATE);'
cur.execute(sql)
sql = """
CREATE TABLE IF NOT EXISTS `chapters` (
`id` INTEGER NOT NULL,
`episode_id` INTEGER NOT NULL,
`title` TEXT,
`start` TEXT,
`image` BLOB,
`href` TEXT,
PRIMARY KEY(`id`)
);
"""
cur.execute(sql)
sql = "CREATE INDEX IF NOT EXISTS `eid_idx` ON `chapters` (`episode_id` );"
cur.execute(sql)
def load_episode_by_rss_id(self, rss_episode_id=None):
sql = "SELECT * FROM " + self.table_episodes + " AS e WHERE rss_episode_id = ? LIMIT 1"
cur = self.db.cursor()
cur.row_factory = sqlite3.Row
cur.execute(sql, [rss_episode_id])
d = cur.fetchone()
e = Episode(episode_id=d['id'],
rss_episode_id=d["rss_episode_id"],
duration=d["duration"],
title=d["title"],
description=d["description"],
subtitle=d["subtitle"],
link=d["link"],
published=d["published"],
image=d["image"],
chapters=[]
)
sql = "SELECT * FROM " + self.table_chapters + " WHERE episode_id = ?"
cur.row_factory = sqlite3.Row
cur.execute(sql, [d["id"]])
d = cur.fetchall()
chapters = []
for c in d:
chapters.append(
Chapter(c["start"], c["title"], chapter_id=c["id"], episode_id=c["episode_id"], image=c["image"],
href=c["href"]))
e.chapters = chapters
return e
def _feed_has_changed(self, etag):
if self.config.force_upload == 'True':
return True
cur = self.db.cursor()
cur.execute("SELECT etag FROM " + self.table_feed + " WHERE etag = ?", [etag])
data = cur.fetchall()
if len(data) > 0:
return False
else:
return True
def _is_known_episode(self, episode_id):
cur = self.db.cursor()
cur.execute("SELECT rss_episode_id FROM " + self.table_episodes + " WHERE rss_episode_id = ?", [episode_id])
data = cur.fetchall()
if len(data) > 0:
return True
else:
return False
def mark_movie_created(self):
pass
def mark_movie_uploaded(self):
pass