/
syndication.py
508 lines (433 loc) · 16.9 KB
/
syndication.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#!/usr/bin/python
# Copyright (C) Michael Still (mikal@stillhq.com) 2006, 2007, 2008
# Released under the terms of the GNU GPL v2
# Subscription functionality
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
import datetime
import time
import feedparser
import re
import sys
import database
import gflags
import mythnettvcore
import program
import utility
import series
# for Kickass
from KickassAPI import Search, Latest, User, CATEGORY, ORDER
# Define command line flags
FLAGS = gflags.FLAGS
complained_about_swf = False
re_attributeparser = re.compile(ur'([^=]*)="([^"]*)" *(.*)', re.UNICODE)
def ParseAttributes(inputline):
"""ParseAttributes -- used to unmangle XML entity attributes"""
line = inputline
result = {}
m = re_attributeparser.match(line)
while m:
result[m.group(1)] = m.group(2)
line = m.group(3)
m = re_attributeparser.match(line)
return result
def Download(db, url, guid, mime,
title, subtitle, description, date, date_parsed, out=sys.stdout):
"""Download -- add a program to the list of waiting downloads"""
prog = program.MythNetTvProgram(db)
if prog.FromUrl(url, guid):
out.write(' Creating program for %s: %s from %s\n\n'
%(database.Normalize(title), database.Normalize(subtitle), guid), GREEN)
elif FLAGS.verbose:
out.write(' Already have %s: %s from %s\n'
%(database.Normalize(title), database.Normalize(subtitle), guid), MAGENTA)
# TODO(mikal): Consider using accessor methods here
for info in ['download_started', 'download_finished', 'imported',
'inactive', 'attempts']:
out.write(' %s: %s\n' %(info, prog.persistant.get(info, None)))
out.write(' Bytes transferred: %s\n'
% utility.DisplayFriendlySize(prog.persistant.get('transferred', 0)))
for row in db.GetRows('select guid from mythnettv_programs '
'where date is null;'):
bad_program = program.MythNetTvProgram(db)
bad_program.Load(row['guid'])
bad_program.SetDate(datetime.datetime.now())
bad_program.Store()
out.write('Program with guid = %s has invalid date, using now\n'
% row['guid'], RED)
# Update program details
prog.SetMime(mime)
prog.SetShowInfo(title, subtitle, description, date, date_parsed)
def GuessMimeType(url):
"""GuessMimeType -- guess a mime type based on a URL"""
if url.endswith('m4v'):
return 'video/x-m4v'
return 'video/x-unguessable'
import dateutil.parser as dparser
def Kickass(db, searchterms, title, out=sys.stdout):
"""Kickass -- get entries from Kickass via api"""
searchterms = searchterms.replace('kickass ','')
kickassentries = Search(searchterms).order(ORDER.SEED)
for entry in kickassentries:
done = False
try:
showdate = series.ExtractDate(entry.name) #extract just the date from a show
showsubtitle = showdate[0] + '.' + showdate[1] + '.' + showdate[2] # now format right for subtitle
date = datetime.datetime.now() #date for database
date_parsed = datetime.datetime.now()
time.sleep(1) # make sure every entry has a unique date
#check if this item has been added once before
if db.GetOneRow('select title from mythnettv_programs where guid="%s";' % utility.hashtitlesubtitle(title, showsubtitle)):
if FLAGS.verbose:
out.write(' Dupicate detected in GUID: %s\n' % utility.hashtitlesubtitle(title, showsubtitle))
else:
Download(db,
entry.magnet_link,
utility.hashtitlesubtitle(title, showsubtitle),
'application/x-bittorrent',
title,
showsubtitle,
'',
date,
date_parsed,
out=out)
except:
pass
try:
showdate = series.ExtractSeasonEpisode(entry.name)
if (showdate[0] < 10):
if (showdate[1] < 10):
showsubtitle = 'S0' + str(showdate[0]) + 'E0' + str(showdate[1])
else:
showsubtitle = 'S0' + str(showdate[0]) + 'E' + str(showdate[1])
else:
if (showdate[1] < 10):
showsubtitle = 'S' + str(showdate[0]) + 'E0' + str(showdate[1])
else:
showsubtitle = 'S' + str(showdate[0]) + 'E' + str(showdate[1])
date_parsed = datetime.datetime.now()
date = date_parsed
time.sleep(1) # make sure every entry has a unique date
if db.GetOneRow('select title from mythnettv_programs where guid="%s";' % utility.hashtitlesubtitle(title, showsubtitle)):
if FLAGS.verbose:
out.write(' Dupicate detected in GUID: %s\n' % utility.hashtitlesubtitle(title, showsubtitle))
else:
Download(db,
entry.magnet_link,
utility.hashtitlesubtitle(title, showsubtitle),
'application/x-bittorrent',
title,
showsubtitle,
'',
date,
date_parsed,
out=out)
except:
pass
def json(db, url, title, out=sys.stdout):
"""json -- try to guess some standard json values. Works with comedians in cars. Can be expaned"""
url = url.replace('json ','')
# url = "https://api.import.io/store/connector/e8110139-b10f-4bbe-bd66-903490d6c6f7/_query?input=webpage/url:http%3A%2F%2Fcomediansincarsgettingcoffee.com%2F&&_apikey=51a4bcc0babd453889e8fc0312ef1dfd143f0b13aacc6c5567ed7f5f9d37381329c2c590111e6c4dd8c1358c39955a1e6b4561391c5d14a9c30bc5b07e1610f17af37a9124485dd78ecee7f7d6db4dcd"
import urllib, json
response = urllib.urlopen(url)
data = json.loads(response.read())
for entry in data['results']:
done = False
#try:
showsubtitle = entry['typevideonum_value'].replace(" ", "") + ' ' + entry['typevideotitle_value']
date = datetime.datetime.now() #date for database
date_parsed = datetime.datetime.now()
time.sleep(1) # make sure every entry has a unique date
#check if this item has been added once before
if db.GetOneRow('select title from mythnettv_programs where guid="%s";' % utility.hashtitlesubtitle(title, showsubtitle)):
if FLAGS.verbose:
out.write(' Dupicate detected in GUID: %s\n' % utility.hashtitlesubtitle(title, showsubtitle))
else:
Download(db,
entry['vid_link'],
utility.hashtitlesubtitle(title, showsubtitle),
'application/x-shockwave-flash',
title,
showsubtitle,
'',
date,
date_parsed,
out=out)
done = True
#except:
# pass
#except:
#pass
def Sync(db, xmlfile, title, out=sys.stdout):
"""Sync -- sync up with an RSS feed"""
global complained_about_swf
# Grab the XML
xmllines = xmlfile.readlines()
# Modify the XML to work around namespace handling bugs in FeedParser
lines = []
re_mediacontent = re.compile('(.*)<media:content([^>]*)/ *>(.*)')
for line in xmllines:
m = re_mediacontent.match(line)
count = 1
while m:
line = '%s<media:wannabe%d>%s</media:wannabe%d>%s' %(m.group(1), count,
m.group(2),
count, m.group(3))
m = re_mediacontent.match(line)
count = count + 1
lines.append(line)
# Parse the modified XML
xml = ''.join(lines)
parser = feedparser.parse(xml)
# Find the media:content entries
for entry in parser.entries:
# detect feedparser version
try: # feedparser >= 5.1.1
date = entry.published # publication date of entry
date_parsed = entry.published_parsed # date parsed
except AttributeError: # older feedparser
try:
date = entry.date # feedparser < 5.1.1
date_parsed = entry.date_parsed
except: # needed because some feeds do not provide a viable date
date = datetime.datetime.now()
date_parsed = date
time.sleep(1) # make sure every entry has a unique date
videos = {}
try:
description = utility.massageDescription(entry.description)
except:
description = ''
subtitle = entry.title
# if entry.has_key('media_description'):
# description = utility.massageDescription(entry['media_description'])
# Enclosures
#out.write(entry)
if entry.has_key('enclosures'):
for enclosure in entry.enclosures:
try:
videos[enclosure.type] = enclosure
except:
videos[GuessMimeType(enclosure.href)] = enclosure
# Media:RSS
for key in entry.keys():
if key.startswith('media_wannabe'):
attrs = ParseAttributes(entry[key])
if attrs.has_key('type'):
videos[attrs['type']] = attrs
if attrs.has_key('title'):
subtitle = attrs['title']
done = False
if FLAGS.verbose:
out.write(' Considering: %s: %s\n' %(title, subtitle))
# very crude, basic subtitle detection
if not done and db.GetOneRow('select title from mythnettv_programs '
'where title=%s and subtitle=%s;' %(db.FormatSqlValue('', title), db.FormatSqlValue('', subtitle))):
done = True
if FLAGS.verbose:
out.write(' Dupicate detected %s: %s\n' %(title, subtitle))
if not done and db.GetOneRow('select title from mythnettv_programs '
'where guid="%s";' % utility.hashtitlesubtitle(title, subtitle)):
done = True
if FLAGS.verbose:
out.write(' Dupicate detected in GUID: %s\n' % utility.hashtitlesubtitle(title, subtitle))
# add this if you want actual bittorrent files instead of magnets 'application/x-bittorrent',
for preferred in ['video/x-msvideo', 'video/mp4', 'video/x-xvid',
'video/wmv', 'video/x-ms-wmv', 'video/quicktime',
'video/x-m4v', 'video/x-flv', 'video/m4v',
'video/msvideo',
'video/vnd.objectvideo', 'video/ms-wmv', 'video/mpeg']:
if not done and videos.has_key(preferred):
Download(db,
videos[preferred]['url'],
utility.hashtitlesubtitle(title, subtitle),
preferred,
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and entry.has_key('link'):
if FLAGS.verbose:
out.write('Link found: %s' %(entry['link']))
if entry['link'].startswith('magnet'):
if FLAGS.verbose:
out.write(' Warning: treating the link as if it where a Magnet link\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-bittorrent',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and entry.has_key('magnetURI'):
if FLAGS.verbose:
out.write('%s' %(entry['magnetURI']))
if entry['magnetURI'].startswith('magnet'):
if FLAGS.verbose:
out.write(' Warning: treating the magnetURI as if it where a Magnet link\n')
Download(db,
entry['magnetURI'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-bittorrent',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and entry.has_key('link'):
if FLAGS.verbose:
out.write('Link found: %s' %(entry['link']))
if entry['link'].endswith('m3u8'):
if FLAGS.verbose:
out.write(' Warning: this seems to be a m3u8 stream\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-mpegurl',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
# handle youtube rss feeds
if not done and entry['link'].startswith('http://www.youtube') or entry['link'].startswith('https://www.youtube'):
if FLAGS.verbose:
out.write(' Warning: looks like a YouTube video link\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-shockwave-flash',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
# handle ZDF rss feeds
if not done and entry['link'].startswith('http://www.zdf'):
if FLAGS.verbose:
out.write(' Warning: looks like a ZDF Mediathek link\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-shockwave-flash',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and entry['link'].startswith('http://www.thedaily'):
if FLAGS.verbose:
out.write(' Warning: looks like a The Daily Show video link\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-shockwave-flash',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and entry['link'].startswith('http://teamcoco'):
if FLAGS.verbose:
out.write(' Warning: looks like a TeamCoco video link\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-shockwave-flash',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
# handle xvideos rss feeds
if not done and (entry['link'].startswith('http://www.xvideos') or entry['link'].startswith('http://www.youporn') or entry['link'].startswith('http://video.xnxx')):
if FLAGS.verbose:
out.write(' Warning: looks like a P0rn video link\n')
Download(db,
entry['link'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-shockwave-flash',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and videos.has_key('text/html'):
db.Log('Warning: Treating text/html as an video enclosure type for '
'%s' % utility.hashtitlesubtitle(title, subtitle))
out.write(' Warning: Treating text/html as an video enclosure from %s for'
' %s pointing to %s\n'
%(repr(videos.keys()), subtitle, videos['text/html']['url']))
Download(db,
videos['text/html']['url'],
utility.hashtitlesubtitle(title, subtitle),
'text/html',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and videos.has_key('application/x-shockwave-flash'):
# we now can download vimeo videos
if videos['application/x-shockwave-flash']['url'].startswith('http://vimeo'):
Download(db,
videos['application/x-shockwave-flash']['url'],
utility.hashtitlesubtitle(title, subtitle),
'application/x-shockwave-flash',
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not complained_about_swf:
out.write('%s\n' % repr(videos))
out.write('Error: SWF is currently unsupported due to ffmpeg and mencoder not supporting compressed SWF files as input. Let mythnettv@stillhq.com know if you are aware of an open source way of transcoding these files.\n\n')
complained_about_swf = True
done = True
if not done and len(videos.keys()) == 1:
# If there is only one attachment, make the rather remarkable
# assumption that it is a video
out.write('Assuming that %s is a video format\n'
% videos.keys()[0])
Download(db,
videos[videos.keys()[0]]['url'],
utility.hashtitlesubtitle(title, subtitle),
videos.keys()[0],
title,
subtitle,
description,
date,
date_parsed,
out=out)
done = True
if not done and videos:
out.write('Error: Unsure which to prefer from: %s for %s\n [%s]\n\n'
%(repr(videos.keys()),
subtitle.encode('utf-8'),
repr(videos)))
if not done and FLAGS.verbose:
out.write(' No downloadable content\n')