-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharteVIDEOS.py
executable file
·786 lines (703 loc) · 28.6 KB
/
arteVIDEOS.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
#!/usr/bin/python2
# -*- coding: utf8 -*-
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version 2, December 2004
#
# Copyright (C) 2010 solsTiCe d'Hiver <[email protected]>
#
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
########################################################################
# PLAYERS #
########################################################################
# You can add your favorite player at the beginning of the PLAYERS tuple
# The command must read data from stdin
# The order is significant: the first player available is used
PLAYERS = (
'mplayer -really-quiet -',
'vlc -',
'xine stdin:/',
'/usr/bin/totem --enqueue fd://0', # you could use absolute path for the command too
)
########################################################################
# DO NOT MODIFY below this line unless you know what you are doing #
########################################################################
from sys import exit, argv, stderr
try:
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
except ImportError:
print >> stderr, 'Error: you need the BeautifulSoup python module'
exit(1)
import urllib2
from urllib import unquote
import urlparse
import os
from subprocess import Popen, PIPE
from optparse import OptionParser
from cmd import Cmd
VERSION = '0.3.1'
DEFAULT_LANG = 'fr'
QUALITY = ('sd', 'hd')
DEFAULT_QUALITY = 'hd'
DEFAULT_DLDIR = os.getcwd()
CLSID = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'
VIDEO_PER_PAGE = 25
DOMAIN = 'http://videos.arte.tv'
GENERIC_URL = DOMAIN + '/%s/videos/%s'
HOME_URL = DOMAIN + '/%%s/videos#/tv/thumb///1/%d/' % VIDEO_PER_PAGE
SEARCH_URL = DOMAIN + '/%%s/do_search/videos/%%s/index-3188352,view,searchResult.html?itemsPerPage=%d&pageNr=%%s&q=' % VIDEO_PER_PAGE
FILTER_URL = DOMAIN + '/%s/do_delegate/videos/index-3188698,view,asThumbnail.html'
QUERY_STRING = '?hash=tv/thumb///%%s/%d/' % VIDEO_PER_PAGE
EVENTS_PAGE = 'events/index-3188672.html'
SEARCH = {'fr': 'recherche', 'de':'suche', 'en': 'search'}
LANG = SEARCH.keys()
ALL_VIDEOS = {'fr':'toutesLesVideos', 'de':'alleVideos', 'en':'allVideos'}
PROGRAMS = {'fr':'programmes', 'de':'sendungen', 'en':'programs'}
HIST_CMD = ('plus7', 'programs', 'events', 'allvideos', 'search')
BOLD = '[1m'
NC = '[0m' # no color
class Navigator(object):
def __init__(self, options):
self.options = options
self.events = None
self.allvideos = None
self.programs = None
self.more = False
self.last_cmd = ''
self.page = 0
# holds last search result from any command (list, program, search)
self.results = []
def __getitem__(self, key):
indx = int(key)-1
return self.results[indx/VIDEO_PER_PAGE][indx % VIDEO_PER_PAGE]
def extra_help(self):
if len(self.results) == 0:
print >> stderr, 'You need to run either a list, search or program command first'
def get_events(self):
'''get events'''
if self.events is not None:
return
try:
print ':: Retrieving events list'
url = GENERIC_URL % (self.options.lang, EVENTS_PAGE)
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
# get the events
lis = soup.find('div', {'id': 'listChannel'}).findAll('li')
events, urls = [], []
for l in lis:
a = l.find('a')
events.append(a.contents[0])
urls.append(a['href'])
if events != []:
self.events = zip(events, urls)
else:
self.events = None
except urllib2.URLError:
die("Can't get the home page of arte+7")
return None
def event(self, arg):
'''get a list of videos for given event'''
ev = int(arg) - 1
if not self.more:
self.page = 0
self.results = []
try:
url = DOMAIN + self.events[ev][1]
soup = unicode(BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES))
try:
start = soup.index('thumbnailViewUrl: "')+19
except ValueError:
print >> stderr, 'Error: when parsing the page'
self.results[self.page] = []
return
url = DOMAIN + soup[start:soup.index('"', start)] + QUERY_STRING % (self.page+1,)
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
self.results.append(extract_videos(soup))
except urllib2.URLError:
die("Can't complete the requested search")
def get_allvideos(self):
'''get allvideos'''
if self.allvideos is not None:
return
try:
print ':: Retrieving all videos list'
url = GENERIC_URL % (self.options.lang, ALL_VIDEOS[self.options.lang])
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
# get the channels
lis = soup.find('div', {'id': 'listChannel'}).findAll('li')
allvideos, urls = [], []
for l in lis:
a = l.find('a')
allvideos.append(a.contents[0])
urls.append(a['href'])
if allvideos != []:
self.allvideos = zip(allvideos, urls)
else:
self.allvideos = None
except urllib2.URLError:
die("Can't get the home page of arte+7")
return None
def allvideo(self, arg):
'''get a list of videos for given event'''
v = int(arg) - 1
if not self.more:
self.page = 0
self.results = []
try:
url = DOMAIN + self.allvideos[v][1]
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
#soup = unicode(BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES))
#try:
# start = soup.index('thumbnailViewUrl: "')+19
#except ValueError:
# print >> stderr, 'Error: when parsing the page'
# self.results[self.page-1] = []
# return
#url = DOMAIN + soup[start:soup.index('"', start)] + QUERY_STRING % (self.page+1,)
#soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
self.results.append(extract_videos(soup))
except urllib2.URLError:
die("Can't complete the requested search")
def get_programs(self):
'''get programs'''
if self.programs is not None:
return
try:
print ':: Retrieving programs list'
url = GENERIC_URL % (self.options.lang, PROGRAMS[self.options.lang])
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
# get the programs
lis = soup.find('div', {'id': 'listChannel'}).findAll('li')
programs, urls = [], []
for l in lis:
a = l.find('a')
programs.append(a.contents[0])
urls.append(a['href'])
if programs != []:
self.programs = zip(programs, urls)
else:
self.programs = None
except urllib2.URLError:
die("Can't get the home page of arte+7")
return None
def program(self, arg):
'''get a list of videos for given program'''
pr = int(arg) - 1
if not self.more:
self.page = 0
self.results = []
try:
url = DOMAIN + self.programs[pr][1]
soup = unicode(BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES))
start = soup.index('thumbnailViewUrl: "')+19
url = DOMAIN + soup[start:soup.index('"', start)] + QUERY_STRING % (self.page+1,)
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
self.results.append(extract_videos(soup))
except urllib2.URLError:
die("Can't complete the requested search")
def search(self, s):
'''search videos matching string s'''
if not self.more:
self.page = 0
self.results = []
try:
url = SEARCH_URL % (self.options.lang, SEARCH[self.options.lang], self.page+1) + s.replace(' ', '+')
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
self.results.append(extract_videos(soup))
except urllib2.URLError:
die("Can't complete the requested search")
def get_plus7(self):
'''get the list of videos from url'''
if not self.more:
self.page = 0
self.results = []
try:
url = FILTER_URL % self.options.lang + QUERY_STRING % (self.page+1,)
soup = BeautifulSoup(urllib2.urlopen(url).read(), convertEntities=BeautifulSoup.ALL_ENTITIES)
self.results.append(extract_videos(soup))
except urllib2.URLError:
die("Can't get the home page of arte+7")
def clear_info(self):
self.events = None
self.allvideos = None
self.programs = None
self.last_cmd = ''
self.page = 0
self.results = []
class MyCmd(Cmd):
def __init__(self, options, nav=None):
Cmd.__init__(self)
self.prompt = 'arteVIDEOS> '
self.intro = '\nType "help" to see available commands.'
if nav is None:
self.nav = Navigator(options)
else:
self.nav = nav
def postcmd(self, stop, line):
if line.startswith(HIST_CMD):
self.nav.last_cmd = line
return stop
def do_previous(self, arg):
if self.nav.last_cmd.startswith(HIST_CMD) and self.nav.page > 0:
self.nav.page -= 1
print_results(self.nav.results[self.nav.page], page=self.nav.page)
return False
def do_next(self, arg):
if self.nav.last_cmd.startswith(HIST_CMD):
self.nav.page += 1
if self.nav.page > len(self.nav.results)-1:
self.nav.more = True
self.onecmd(self.nav.last_cmd)
self.nav.more = False
else:
print_results(self.nav.results[self.nav.page], page=self.nav.page)
return False
def do_url(self, arg):
'''url NUMBER
show the url of the chosen video'''
try:
video = self.nav[arg]
if 'rtmp_url' not in video:
get_video_player_info(video, self.nav.options)
print video['rtmp_url']
except ValueError:
print >> stderr, 'Error: wrong argument (must be an integer)'
except IndexError:
print >> stderr, 'Error: no video with this number'
self.nav.extra_help()
def do_player_url(self, arg):
'''player_url NUMBER
show the Flash player url of the chosen video'''
try:
video = self.nav[arg]
if 'player_url' not in video:
get_video_player_info(video, self.nav.options)
print video['player_url']
except ValueError:
print >> stderr, 'Error: wrong argument (must be an integer)'
except IndexError:
print >> stderr, 'Error: no video with this number'
self.nav.extra_help()
def do_info(self, arg):
'''info NUMBER
display details about chosen video'''
try:
video = self.nav[arg]
if 'info' not in video:
get_video_player_info(video, self.nav.options)
print '%s== %s ==%s'% (BOLD, video['title'], NC)
print video['info']
except ValueError:
print >> stderr, 'Error: wrong argument (must be an integer)'
except IndexError:
print >> stderr, 'Error: no video with this number'
self.nav.extra_help()
def do_play(self, arg):
'''play NUMBER [NUMBER] ...
play the chosen videos'''
playlist = []
for i in arg.split():
try:
playlist.append(self.nav[i])
except ValueError:
print >> stderr, '"%s": wrong argument, must be an integer' % i
return
except IndexError:
print >> stderr, 'Error: no video with this number: %s' % i
self.nav.extra_help()
return
print ':: Playing video(s): ' + ', '.join('#%s' % i for i in arg.split())
for v in playlist:
play(v, self.nav.options)
def do_record(self, arg):
'''record NUMBER [NUMBER] ...
record the chosen videos to a local file'''
playlist = []
for i in arg.split():
try:
playlist.append(self.nav[i])
except ValueError:
print >> stderr, '"%s": wrong argument, must be an integer' % i
return
except IndexError:
print >> stderr, 'Error: no video with this number: %s' % i
self.nav.extra_help()
return
print ':: Recording video(s): ' + ', '.join('#%s' % i for i in arg.split())
# TODO: do that in parallel ?
for v in playlist:
record(v, self.nav.options)
def do_search(self, arg):
'''search STRING
search for a given STRING on arte+7 web site'''
self.nav.search(arg)
print_results(self.nav.results[self.nav.page], page=self.nav.page)
def complete_lang(self, text, line, begidx, endidx):
if text == '':
return LANG
elif text.startswith('d'):
return ('de',)
elif text.startswith('f'):
return('fr',)
elif text.startswith('e'):
return('en',)
def do_lang(self, arg):
'''lang [fr|de|en]
display or switch to a different language'''
if arg == '':
print self.nav.options.lang
elif arg in LANG:
self.nav.options.lang = arg
self.nav.clear_info()
else:
print >> stderr, 'Error: lang could be %s' % ','.join(LANG)
def complete_quality(self, text, line, begidx, endidx):
if text == '':
return QUALITY
elif text.startswith('s'):
return ('sd',)
elif text.startswith('h'):
return('hd',)
def do_quality(self, arg):
'''quality [sd|hd]
display or switch to a different quality'''
if arg == '':
print self.nav.options.quality
elif arg in QUALITY:
self.nav.options.quality = arg
self.nav.clear_info()
else:
print >> stderr, 'Error: quality could be %s' % ','.join(QUALITY)
def do_plus7(self, arg):
'''list [more]
list 25 videos from the home page'''
print ':: Retrieving plus7 videos list'
self.nav.get_plus7()
print_results(self.nav.results[self.nav.page], page=self.nav.page)
def do_allvideos(self, arg):
'''allvideos [NUMBER] ...
display available videos or search for given videos(s)'''
self.nav.get_allvideos()
if arg == '':
print '\n'.join('(%d) %s' % (i+1, self.nav.allvideos[i][0]) for i in range(len(self.nav.allvideos)))
else:
try:
self.nav.allvideo(arg)
print_results(self.nav.results[self.nav.page], page=self.nav.page)
except IndexError:
print >> stderr, 'Error: unknown channel'
except ValueError:
print >> stderr, 'Error: wrong argument; must be an integer'
def do_events(self, arg):
'''events [NUMBER] ...
display available events or search video for given event(s)'''
self.nav.get_events()
if arg == '':
print '\n'.join('(%d) %s' % (i+1, self.nav.events[i][0]) for i in range(len(self.nav.events)))
else:
try:
self.nav.event(arg)
print_results(self.nav.results[self.nav.page], page=self.nav.page)
except IndexError:
print >> stderr, 'Error: unknown events'
except ValueError:
print >> stderr, 'Error: wrong argument; must be an integer'
def do_programs(self, arg):
'''programs [NUMBER] ...
display available programs or search video for given program(s)'''
# try to get them from home page
self.nav.get_programs()
if arg == '':
print '\n'.join('(%d) %s' % (i+1, self.nav.programs[i][0]) for i in range(len(self.nav.programs)))
else:
try:
self.nav.program(arg)
print_results(self.nav.results[self.nav.page], page=self.nav.page)
except IndexError:
print >> stderr, 'Error: unknown program'
except ValueError:
print >> stderr, 'Error: wrong argument; must be an integer'
def do_dldir(self,arg):
'''dldir [PATH] ...
display or change download directory'''
if arg == '':
print self.nav.options.dldir
return
arg = expand_path(arg) # resolve environment variables and '~'s
if not os.path.exists(arg):
print >> stderr, 'Error: wrong argument; must be a valid path'
else:
self.nav.options.dldir = arg
def do_help(self, arg):
'''print the help'''
if arg == '':
print '''COMMANDS:
plus7 list videos from arte+7
allvideos list videos from allvideos tab
events list videos from events tab
programs list videos from programs tab
search STRING search for a video
next list videos of the next page
previous list videos of previous page
url NUMBER show url of video
play NUMBERS play chosen videos
record NUMBERS download and save videos to a local file
info NUMBER display details about given video
dldir [PATH] display or change download directory
lang [fr|de|en] display or switch to a different language
quality [sd|hd] display or switch to a different video quality
help show this help
quit quit the cli
exit exit the cli'''
else:
try:
print getattr(self, 'do_'+arg).__doc__
except AttributeError:
print >> stderr, 'Error: no help for command %s' % arg
def do_quit(self, arg):
'''quit the command line interpreter'''
return True
def do_exit(self, arg):
'''exit the command line interpreter'''
return True
def do_EOF(self, arg):
'''exit the command line interpreter'''
print
return True
def default(self, arg):
print >> stderr, 'Error: don\'t know how to %s' % arg
def emptyline(self):
pass
def die(msg):
print >> stderr, 'Error: %s. See %s --help' % (msg, argv[0])
exit(1)
def get_rtmp_url(url_page, quality='hd', lang='fr'):
'''get the rtmp url of the video and player url and info about video and soup'''
# inspired by the get_rtmp_url from arte7recorder project
# get the web page
try:
first_soup = soup = BeautifulSoup(urllib2.urlopen(url_page).read())
info = extract_info(soup)
object_tag = soup.find('object', classid=CLSID)
# get the player_url straight from it
player_url = unquote(object_tag.find('embed')['src'])
try:
# if they decide to use jwPlayer
flashvars = urlparse.parse_qs(object_tag.find('param', {'name':'flashvars'})['value'])
rtmp_url = flashvars['streamer'][0]+flashvars['file'][0]
except TypeError:
# the OLD way - we need a few jumps to get to the correct url
flashvars = urlparse.parse_qs(object_tag.find('param', {'name':'movie'})['value'])
# first xml file
soup = BeautifulStoneSoup(urllib2.urlopen(flashvars['videorefFileUrl'][0]).read())
videos_list = soup.findAll('video')
videos = {}
for v in videos_list:
videos[v['lang']] = v['ref']
if lang not in videos:
print >> stderr, 'The video in not available in the language %s. Using the default one' % lang
if DEFAULT_LANG in videos:
xml_url = videos[DEFAULT_LANG]
else:
xml_url = videos.popitem()[1]
else:
xml_url = videos[lang]
# second xml file
soup = BeautifulStoneSoup(urllib2.urlopen(xml_url).read())
# at last the video url
url = soup.urls.find('url', {'quality': quality})
if url is None:
url = soup.urls.find('url')[0]
print >> stderr, "Can't find the desired quality. Using the first one found"
rtmp_url = url.string
return (rtmp_url, player_url, info)
except urllib2.URLError:
die('Invalid URL')
def get_video_player_info(video, options):
'''get various info from page of video: *modify* video variable'''
print ':: Retrieving video data'
r, p, i = get_rtmp_url(video['url'], quality=options.quality, lang=options.lang)
video['rtmp_url'] = r
video['player_url'] = p
video['info'] = i
def extract_videos(soup):
'''extract list of videos title, url, and teaser from video_soup'''
videos = []
video_soup = soup.findAll('div', {'class': 'video'})
for v in video_soup:
teaserNode = v.find('p', {'class': 'teaserText'})
teaser = teaserNode.string if teaserNode is not None else ''
try:
a = v.find('h2').a
except AttributeError:
# ignore bottom videos
continue
try:
videos.append({'title':a.contents[0], 'url':DOMAIN+a['href'], 'teaser':teaser})
except IndexError:
# empty title ??
videos.append({'title':'== NO TITLE ==', 'url':DOMAIN+a['href'], 'teaser':teaser})
return videos
def extract_info(soup):
'''extract info about video from soup'''
rtc = soup.find('div', {'class':'recentTracksCont'})
s = ''
for i in rtc.div.findAll('p'):
s += '\n'.join(j.string for j in i if j.string is not None)
s += '\n\n'
more = rtc.find('div', {'id':'more'}).findAll('p')
for i in more:
s += ' '.join(j.string for j in i if j.string is not None).replace('\n ', '\n')
s = s.strip('\n').replace('\n\n\n', '\n\n')
return s
def print_results(results, verbose=True, page=1):
'''print list of video:
title in bold with a number followed by teaser'''
for i in range(len(results)):
print '%s(%d) %s'% (BOLD, i+1+VIDEO_PER_PAGE*page, results[i]['title'] + NC)
if verbose:
print ' '+ results[i]['teaser']
if len(results) == 0:
print ':: the search returned nothing'
def play(video, options):
cmd_args = make_cmd_args(video, options, streaming=True)
if 'nogeo/carton_23h' in video['rtmp_url']:
print >> stderr, 'Error: This video is only available between 23:00 and 05:00'
return
player_cmd = find_player(PLAYERS)
if player_cmd is not None:
p1 = Popen(['rtmpdump'] + cmd_args.split(' '), stdout=PIPE)
p2 = Popen(player_cmd.split(' '), stdin=p1.stdout, stderr=PIPE)
p2.wait()
# kill the zombie rtmpdump
try:
p1.kill()
p1.wait()
except AttributeError:
# if we use python 2.5
from signal import SIGKILL
from os import kill, waitpid
kill(p1.pid, SIGKILL)
waitpid(p1.pid, 0)
else:
print >> stderr, 'Error: no player has been found.'
def record(video, options):
cwd = os.getcwd()
os.chdir(options.dldir)
cmd_args = make_cmd_args(video, options)
if 'nogeo/carton_23h' in video['rtmp_url']:
print >> stderr, 'Error: This video is only available between 23:00 and 05:00'
return
p = Popen(['rtmpdump'] + cmd_args.split(' '))
os.chdir(cwd)
p.wait()
def make_cmd_args(video, options, streaming=False):
if not find_in_path(os.environ['PATH'], 'rtmpdump'):
print >> stderr, 'Error: rtmpdump has not been found'
exit(1)
if 'rtmp_url' not in video:
get_video_player_info(video, options)
output_file = None
if not streaming:
output_file = urlparse.urlparse(video['url']).path.split('/')[-1]
output_file = output_file.replace('.html', '_%s_%s.flv' % (options.quality, options.lang))
cmd_args = '--rtmp %s --flv %s --swfVfy %s' % (video['rtmp_url'], output_file, video['player_url'])
else:
cmd_args = '--rtmp %s --swfVfy %s' % (video['rtmp_url'], video['player_url'])
if not options.verbose:
cmd_args += ' --quiet'
if not streaming:
if os.path.exists(output_file):
# try to resume a download
cmd_args += ' --resume'
print ':: Resuming download of %s' % output_file
else:
print ':: Downloading to %s' % output_file
else:
print ':: Streaming from %s' % video['rtmp_url']
return cmd_args
def expand_path(path):
if '~' in path:
path = os.path.expanduser(path)
if ('$' in path) or ('%' in path):
path = os.path.expandvars(path)
return path
def find_in_path(path, filename):
'''is filename in $PATH ?'''
for i in path.split(':'):
if os.path.exists('/'.join([i, filename])):
return True
return False
def find_player(players):
for p in players:
cmd = p.split(' ')[0]
if cmd.startswith('/') and os.path.isfile(cmd):
return p
else:
if find_in_path(os.environ['PATH'], cmd):
return p
return None
def main():
usage = '''Usage: %prog url|play|record [OPTIONS] URL
%prog search [OPTIONS] STRING...
%prog
Play or record videos from arte VIDEOS website without a mandatory browser.
In the first form, you need the url of the video page
In the second form, just enter your search term
In the last form (without any argument), you enter an interactive interpreter
(type help to get a list of available commands, once in the interpreter)
COMMANDS
url show the url of the video
play play the video directly
record save the video into a local file
search search for a video on arte+7
It will display a numbered list of results and enter
a simple command line interpreter'''
parser = OptionParser(usage=usage)
parser.add_option('-d', '--downloaddir', dest='dldir', type='string',
default=DEFAULT_DLDIR, action='store', help='directory for downloads')
parser.add_option('-l', '--lang', dest='lang', type='string', default=DEFAULT_LANG,
action='store', help='language of the video fr, de, en (default: fr)')
parser.add_option('-q', '--quality', dest='quality', type='string', default=DEFAULT_QUALITY,
action='store', help='quality of the video sd or hd (default: hd)')
parser.add_option('--verbose', dest='verbose', default=False,
action='store_true', help='show output of rtmpdump')
options, args = parser.parse_args()
if not os.path.exists(options.dldir):
die('Invalid Path')
if options.lang not in ('fr', 'de', 'en'):
die('Invalid option')
if options.quality not in ('sd', 'hd'):
die('Invalid option')
if len(args) < 2:
MyCmd(options).cmdloop()
exit(0)
if args[0] not in ('url', 'play', 'record', 'search'):
die('Invalid command')
if args[0] == 'url':
print get_rtmp_url(args[1], quality=options.quality, lang=options.lang)[0]
elif args[0] == 'play':
play({'url':args[1]}, options)
exit(1)
elif args[0] == 'record':
record({'url':args[1]}, options)
elif args[0] == 'search':
term = ' '.join(args[1:])
print ':: Searching for "%s"' % term
nav = Navigator(options)
nav.search(term)
nav.last_cmd = 'search %s' % term
if nav.results is not None:
print_results(nav.results[0])
MyCmd(options, nav=nav).cmdloop()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print '\nAborted'