InfoExtractors.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import HTMLParser
  5. import httplib
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import time
  11. import urllib
  12. import urllib2
  13. import email.utils
  14. import xml.etree.ElementTree
  15. import random
  16. import math
  17. from urlparse import parse_qs
  18. try:
  19. import cStringIO as StringIO
  20. except ImportError:
  21. import StringIO
  22. from utils import *
  23. class InfoExtractor(object):
  24. """Information Extractor class.
  25. Information extractors are the classes that, given a URL, extract
  26. information from the video (or videos) the URL refers to. This
  27. information includes the real video URL, the video title and simplified
  28. title, author and others. The information is stored in a dictionary
  29. which is then passed to the FileDownloader. The FileDownloader
  30. processes this information possibly downloading the video to the file
  31. system, among other possible outcomes. The dictionaries must include
  32. the following fields:
  33. id: Video identifier.
  34. url: Final video URL.
  35. uploader: Nickname of the video uploader.
  36. title: Literal title.
  37. ext: Video filename extension.
  38. format: Video format.
  39. player_url: SWF Player URL (may be None).
  40. The following fields are optional. Their primary purpose is to allow
  41. youtube-dl to serve as the backend for a video search function, such
  42. as the one in youtube2mp3. They are only used when their respective
  43. forced printing functions are called:
  44. thumbnail: Full URL to a video thumbnail image.
  45. description: One-line video description.
  46. Subclasses of this one should re-define the _real_initialize() and
  47. _real_extract() methods and define a _VALID_URL regexp.
  48. Probably, they should also be added to the list of extractors.
  49. """
  50. _ready = False
  51. _downloader = None
  52. def __init__(self, downloader=None):
  53. """Constructor. Receives an optional downloader."""
  54. self._ready = False
  55. self.set_downloader(downloader)
  56. def suitable(self, url):
  57. """Receives a URL and returns True if suitable for this IE."""
  58. return re.match(self._VALID_URL, url) is not None
  59. def initialize(self):
  60. """Initializes an instance (authentication, etc)."""
  61. if not self._ready:
  62. self._real_initialize()
  63. self._ready = True
  64. def extract(self, url):
  65. """Extracts URL information and returns it in list of dicts."""
  66. self.initialize()
  67. return self._real_extract(url)
  68. def set_downloader(self, downloader):
  69. """Sets the downloader for this IE."""
  70. self._downloader = downloader
  71. def _real_initialize(self):
  72. """Real initialization process. Redefine in subclasses."""
  73. pass
  74. def _real_extract(self, url):
  75. """Real extraction process. Redefine in subclasses."""
  76. pass
  77. class YoutubeIE(InfoExtractor):
  78. """Information extractor for youtube.com."""
  79. _VALID_URL = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|tube\.majestyc\.net/)(?!view_play_list|my_playlists|artist|playlist)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=))?)?([0-9A-Za-z_-]+)(?(1).+)?$'
  80. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  81. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  82. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  83. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  84. _NETRC_MACHINE = 'youtube'
  85. # Listed in order of quality
  86. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  87. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  88. _video_extensions = {
  89. '13': '3gp',
  90. '17': 'mp4',
  91. '18': 'mp4',
  92. '22': 'mp4',
  93. '37': 'mp4',
  94. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  95. '43': 'webm',
  96. '44': 'webm',
  97. '45': 'webm',
  98. '46': 'webm',
  99. }
  100. _video_dimensions = {
  101. '5': '240x400',
  102. '6': '???',
  103. '13': '???',
  104. '17': '144x176',
  105. '18': '360x640',
  106. '22': '720x1280',
  107. '34': '360x640',
  108. '35': '480x854',
  109. '37': '1080x1920',
  110. '38': '3072x4096',
  111. '43': '360x640',
  112. '44': '480x854',
  113. '45': '720x1280',
  114. '46': '1080x1920',
  115. }
  116. IE_NAME = u'youtube'
  117. def report_lang(self):
  118. """Report attempt to set language."""
  119. self._downloader.to_screen(u'[youtube] Setting language')
  120. def report_login(self):
  121. """Report attempt to log in."""
  122. self._downloader.to_screen(u'[youtube] Logging in')
  123. def report_age_confirmation(self):
  124. """Report attempt to confirm age."""
  125. self._downloader.to_screen(u'[youtube] Confirming age')
  126. def report_video_webpage_download(self, video_id):
  127. """Report attempt to download video webpage."""
  128. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  129. def report_video_info_webpage_download(self, video_id):
  130. """Report attempt to download video info webpage."""
  131. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  132. def report_video_subtitles_download(self, video_id):
  133. """Report attempt to download video info webpage."""
  134. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  135. def report_information_extraction(self, video_id):
  136. """Report attempt to extract video information."""
  137. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  138. def report_unavailable_format(self, video_id, format):
  139. """Report extracted video URL."""
  140. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  141. def report_rtmp_download(self):
  142. """Indicate the download will use the RTMP protocol."""
  143. self._downloader.to_screen(u'[youtube] RTMP download detected')
  144. def _closed_captions_xml_to_srt(self, xml_string):
  145. srt = ''
  146. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  147. # TODO parse xml instead of regex
  148. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  149. if not dur: dur = '4'
  150. start = float(start)
  151. end = start + float(dur)
  152. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  153. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  154. caption = unescapeHTML(caption)
  155. caption = unescapeHTML(caption) # double cycle, intentional
  156. srt += str(n+1) + '\n'
  157. srt += start + ' --> ' + end + '\n'
  158. srt += caption + '\n\n'
  159. return srt
  160. def _print_formats(self, formats):
  161. print 'Available formats:'
  162. for x in formats:
  163. print '%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???'))
  164. def _real_initialize(self):
  165. if self._downloader is None:
  166. return
  167. username = None
  168. password = None
  169. downloader_params = self._downloader.params
  170. # Attempt to use provided username and password or .netrc data
  171. if downloader_params.get('username', None) is not None:
  172. username = downloader_params['username']
  173. password = downloader_params['password']
  174. elif downloader_params.get('usenetrc', False):
  175. try:
  176. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  177. if info is not None:
  178. username = info[0]
  179. password = info[2]
  180. else:
  181. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  182. except (IOError, netrc.NetrcParseError), err:
  183. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  184. return
  185. # Set language
  186. request = urllib2.Request(self._LANG_URL)
  187. try:
  188. self.report_lang()
  189. urllib2.urlopen(request).read()
  190. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  191. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  192. return
  193. # No authentication to be performed
  194. if username is None:
  195. return
  196. # Log in
  197. login_form = {
  198. 'current_form': 'loginForm',
  199. 'next': '/',
  200. 'action_login': 'Log In',
  201. 'username': username,
  202. 'password': password,
  203. }
  204. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  205. try:
  206. self.report_login()
  207. login_results = urllib2.urlopen(request).read()
  208. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  209. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  210. return
  211. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  212. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  213. return
  214. # Confirm age
  215. age_form = {
  216. 'next_url': '/',
  217. 'action_confirm': 'Confirm',
  218. }
  219. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  220. try:
  221. self.report_age_confirmation()
  222. age_results = urllib2.urlopen(request).read()
  223. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  224. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  225. return
  226. def _real_extract(self, url):
  227. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  228. mobj = re.search(self._NEXT_URL_RE, url)
  229. if mobj:
  230. url = 'http://www.youtube.com/' + urllib.unquote(mobj.group(1)).lstrip('/')
  231. # Extract video id from URL
  232. mobj = re.match(self._VALID_URL, url)
  233. if mobj is None:
  234. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  235. return
  236. video_id = mobj.group(2)
  237. # Get video webpage
  238. self.report_video_webpage_download(video_id)
  239. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id)
  240. try:
  241. video_webpage = urllib2.urlopen(request).read()
  242. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  243. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  244. return
  245. # Attempt to extract SWF player URL
  246. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  247. if mobj is not None:
  248. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  249. else:
  250. player_url = None
  251. # Get video info
  252. self.report_video_info_webpage_download(video_id)
  253. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  254. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  255. % (video_id, el_type))
  256. request = urllib2.Request(video_info_url)
  257. try:
  258. video_info_webpage = urllib2.urlopen(request).read()
  259. video_info = parse_qs(video_info_webpage)
  260. if 'token' in video_info:
  261. break
  262. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  263. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  264. return
  265. if 'token' not in video_info:
  266. if 'reason' in video_info:
  267. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  268. else:
  269. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  270. return
  271. # Check for "rental" videos
  272. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  273. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  274. return
  275. # Start extracting information
  276. self.report_information_extraction(video_id)
  277. # uploader
  278. if 'author' not in video_info:
  279. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  280. return
  281. video_uploader = urllib.unquote_plus(video_info['author'][0])
  282. # title
  283. if 'title' not in video_info:
  284. self._downloader.trouble(u'ERROR: unable to extract video title')
  285. return
  286. video_title = urllib.unquote_plus(video_info['title'][0])
  287. video_title = video_title.decode('utf-8')
  288. # thumbnail image
  289. if 'thumbnail_url' not in video_info:
  290. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  291. video_thumbnail = ''
  292. else: # don't panic if we can't find it
  293. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  294. # upload date
  295. upload_date = u'NA'
  296. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  297. if mobj is not None:
  298. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  299. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  300. for expression in format_expressions:
  301. try:
  302. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  303. except:
  304. pass
  305. # description
  306. video_description = get_element_by_id("eow-description", video_webpage.decode('utf8'))
  307. if video_description: video_description = clean_html(video_description)
  308. else: video_description = ''
  309. # closed captions
  310. video_subtitles = None
  311. if self._downloader.params.get('writesubtitles', False):
  312. try:
  313. self.report_video_subtitles_download(video_id)
  314. request = urllib2.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  315. try:
  316. srt_list = urllib2.urlopen(request).read()
  317. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  318. raise Trouble(u'WARNING: unable to download video subtitles: %s' % str(err))
  319. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  320. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  321. if not srt_lang_list:
  322. raise Trouble(u'WARNING: video has no closed captions')
  323. if self._downloader.params.get('subtitleslang', False):
  324. srt_lang = self._downloader.params.get('subtitleslang')
  325. elif 'en' in srt_lang_list:
  326. srt_lang = 'en'
  327. else:
  328. srt_lang = srt_lang_list.keys()[0]
  329. if not srt_lang in srt_lang_list:
  330. raise Trouble(u'WARNING: no closed captions found in the specified language')
  331. request = urllib2.Request('http://www.youtube.com/api/timedtext?lang=%s&name=%s&v=%s' % (srt_lang, srt_lang_list[srt_lang], video_id))
  332. try:
  333. srt_xml = urllib2.urlopen(request).read()
  334. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  335. raise Trouble(u'WARNING: unable to download video subtitles: %s' % str(err))
  336. if not srt_xml:
  337. raise Trouble(u'WARNING: unable to download video subtitles')
  338. video_subtitles = self._closed_captions_xml_to_srt(srt_xml.decode('utf-8'))
  339. except Trouble as trouble:
  340. self._downloader.trouble(trouble[0])
  341. # token
  342. video_token = urllib.unquote_plus(video_info['token'][0])
  343. # Decide which formats to download
  344. req_format = self._downloader.params.get('format', None)
  345. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  346. self.report_rtmp_download()
  347. video_url_list = [(None, video_info['conn'][0])]
  348. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  349. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  350. url_data = [parse_qs(uds) for uds in url_data_strs]
  351. url_data = filter(lambda ud: 'itag' in ud and 'url' in ud, url_data)
  352. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  353. format_limit = self._downloader.params.get('format_limit', None)
  354. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  355. if format_limit is not None and format_limit in available_formats:
  356. format_list = available_formats[available_formats.index(format_limit):]
  357. else:
  358. format_list = available_formats
  359. existing_formats = [x for x in format_list if x in url_map]
  360. if len(existing_formats) == 0:
  361. self._downloader.trouble(u'ERROR: no known formats available for video')
  362. return
  363. if self._downloader.params.get('listformats', None):
  364. self._print_formats(existing_formats)
  365. return
  366. if req_format is None or req_format == 'best':
  367. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  368. elif req_format == 'worst':
  369. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  370. elif req_format in ('-1', 'all'):
  371. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  372. else:
  373. # Specific formats. We pick the first in a slash-delimeted sequence.
  374. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  375. req_formats = req_format.split('/')
  376. video_url_list = None
  377. for rf in req_formats:
  378. if rf in url_map:
  379. video_url_list = [(rf, url_map[rf])]
  380. break
  381. if video_url_list is None:
  382. self._downloader.trouble(u'ERROR: requested format not available')
  383. return
  384. else:
  385. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  386. return
  387. results = []
  388. for format_param, video_real_url in video_url_list:
  389. # Extension
  390. video_extension = self._video_extensions.get(format_param, 'flv')
  391. results.append({
  392. 'id': video_id.decode('utf-8'),
  393. 'url': video_real_url.decode('utf-8'),
  394. 'uploader': video_uploader.decode('utf-8'),
  395. 'upload_date': upload_date,
  396. 'title': video_title,
  397. 'ext': video_extension.decode('utf-8'),
  398. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  399. 'thumbnail': video_thumbnail.decode('utf-8'),
  400. 'description': video_description,
  401. 'player_url': player_url,
  402. 'subtitles': video_subtitles
  403. })
  404. return results
  405. class MetacafeIE(InfoExtractor):
  406. """Information Extractor for metacafe.com."""
  407. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  408. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  409. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  410. IE_NAME = u'metacafe'
  411. def __init__(self, downloader=None):
  412. InfoExtractor.__init__(self, downloader)
  413. def report_disclaimer(self):
  414. """Report disclaimer retrieval."""
  415. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  416. def report_age_confirmation(self):
  417. """Report attempt to confirm age."""
  418. self._downloader.to_screen(u'[metacafe] Confirming age')
  419. def report_download_webpage(self, video_id):
  420. """Report webpage download."""
  421. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  422. def report_extraction(self, video_id):
  423. """Report information extraction."""
  424. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  425. def _real_initialize(self):
  426. # Retrieve disclaimer
  427. request = urllib2.Request(self._DISCLAIMER)
  428. try:
  429. self.report_disclaimer()
  430. disclaimer = urllib2.urlopen(request).read()
  431. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  432. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  433. return
  434. # Confirm age
  435. disclaimer_form = {
  436. 'filters': '0',
  437. 'submit': "Continue - I'm over 18",
  438. }
  439. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  440. try:
  441. self.report_age_confirmation()
  442. disclaimer = urllib2.urlopen(request).read()
  443. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  444. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  445. return
  446. def _real_extract(self, url):
  447. # Extract id and simplified title from URL
  448. mobj = re.match(self._VALID_URL, url)
  449. if mobj is None:
  450. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  451. return
  452. video_id = mobj.group(1)
  453. # Check if video comes from YouTube
  454. mobj2 = re.match(r'^yt-(.*)$', video_id)
  455. if mobj2 is not None:
  456. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  457. return
  458. # Retrieve video webpage to extract further information
  459. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  460. try:
  461. self.report_download_webpage(video_id)
  462. webpage = urllib2.urlopen(request).read()
  463. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  464. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  465. return
  466. # Extract URL, uploader and title from webpage
  467. self.report_extraction(video_id)
  468. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  469. if mobj is not None:
  470. mediaURL = urllib.unquote(mobj.group(1))
  471. video_extension = mediaURL[-3:]
  472. # Extract gdaKey if available
  473. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  474. if mobj is None:
  475. video_url = mediaURL
  476. else:
  477. gdaKey = mobj.group(1)
  478. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  479. else:
  480. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  481. if mobj is None:
  482. self._downloader.trouble(u'ERROR: unable to extract media URL')
  483. return
  484. vardict = parse_qs(mobj.group(1))
  485. if 'mediaData' not in vardict:
  486. self._downloader.trouble(u'ERROR: unable to extract media URL')
  487. return
  488. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  489. if mobj is None:
  490. self._downloader.trouble(u'ERROR: unable to extract media URL')
  491. return
  492. mediaURL = mobj.group(1).replace('\\/', '/')
  493. video_extension = mediaURL[-3:]
  494. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  495. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  496. if mobj is None:
  497. self._downloader.trouble(u'ERROR: unable to extract title')
  498. return
  499. video_title = mobj.group(1).decode('utf-8')
  500. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  501. if mobj is None:
  502. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  503. return
  504. video_uploader = mobj.group(1)
  505. return [{
  506. 'id': video_id.decode('utf-8'),
  507. 'url': video_url.decode('utf-8'),
  508. 'uploader': video_uploader.decode('utf-8'),
  509. 'upload_date': u'NA',
  510. 'title': video_title,
  511. 'ext': video_extension.decode('utf-8'),
  512. 'format': u'NA',
  513. 'player_url': None,
  514. }]
  515. class DailymotionIE(InfoExtractor):
  516. """Information Extractor for Dailymotion"""
  517. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
  518. IE_NAME = u'dailymotion'
  519. def __init__(self, downloader=None):
  520. InfoExtractor.__init__(self, downloader)
  521. def report_download_webpage(self, video_id):
  522. """Report webpage download."""
  523. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  524. def report_extraction(self, video_id):
  525. """Report information extraction."""
  526. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  527. def _real_extract(self, url):
  528. # Extract id and simplified title from URL
  529. mobj = re.match(self._VALID_URL, url)
  530. if mobj is None:
  531. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  532. return
  533. video_id = mobj.group(1)
  534. video_extension = 'mp4'
  535. # Retrieve video webpage to extract further information
  536. request = urllib2.Request(url)
  537. request.add_header('Cookie', 'family_filter=off')
  538. try:
  539. self.report_download_webpage(video_id)
  540. webpage = urllib2.urlopen(request).read()
  541. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  542. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  543. return
  544. # Extract URL, uploader and title from webpage
  545. self.report_extraction(video_id)
  546. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  547. if mobj is None:
  548. self._downloader.trouble(u'ERROR: unable to extract media URL')
  549. return
  550. flashvars = urllib.unquote(mobj.group(1))
  551. if 'hqURL' in flashvars: max_quality = 'hqURL'
  552. elif 'sdURL' in flashvars: max_quality = 'sdURL'
  553. else: max_quality = 'ldURL'
  554. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  555. if mobj is None:
  556. self._downloader.trouble(u'ERROR: unable to extract media URL')
  557. return
  558. video_url = mobj.group(1).replace('\\/', '/')
  559. # TODO: support choosing qualities
  560. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  561. if mobj is None:
  562. self._downloader.trouble(u'ERROR: unable to extract title')
  563. return
  564. video_title = unescapeHTML(mobj.group('title').decode('utf-8'))
  565. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a></span>', webpage)
  566. if mobj is None:
  567. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  568. return
  569. video_uploader = mobj.group(1)
  570. return [{
  571. 'id': video_id.decode('utf-8'),
  572. 'url': video_url.decode('utf-8'),
  573. 'uploader': video_uploader.decode('utf-8'),
  574. 'upload_date': u'NA',
  575. 'title': video_title,
  576. 'ext': video_extension.decode('utf-8'),
  577. 'format': u'NA',
  578. 'player_url': None,
  579. }]
  580. class GoogleIE(InfoExtractor):
  581. """Information extractor for video.google.com."""
  582. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  583. IE_NAME = u'video.google'
  584. def __init__(self, downloader=None):
  585. InfoExtractor.__init__(self, downloader)
  586. def report_download_webpage(self, video_id):
  587. """Report webpage download."""
  588. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  589. def report_extraction(self, video_id):
  590. """Report information extraction."""
  591. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  592. def _real_extract(self, url):
  593. # Extract id from URL
  594. mobj = re.match(self._VALID_URL, url)
  595. if mobj is None:
  596. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  597. return
  598. video_id = mobj.group(1)
  599. video_extension = 'mp4'
  600. # Retrieve video webpage to extract further information
  601. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  602. try:
  603. self.report_download_webpage(video_id)
  604. webpage = urllib2.urlopen(request).read()
  605. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  606. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  607. return
  608. # Extract URL, uploader, and title from webpage
  609. self.report_extraction(video_id)
  610. mobj = re.search(r"download_url:'([^']+)'", webpage)
  611. if mobj is None:
  612. video_extension = 'flv'
  613. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  614. if mobj is None:
  615. self._downloader.trouble(u'ERROR: unable to extract media URL')
  616. return
  617. mediaURL = urllib.unquote(mobj.group(1))
  618. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  619. mediaURL = mediaURL.replace('\\x26', '\x26')
  620. video_url = mediaURL
  621. mobj = re.search(r'<title>(.*)</title>', webpage)
  622. if mobj is None:
  623. self._downloader.trouble(u'ERROR: unable to extract title')
  624. return
  625. video_title = mobj.group(1).decode('utf-8')
  626. # Extract video description
  627. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  628. if mobj is None:
  629. self._downloader.trouble(u'ERROR: unable to extract video description')
  630. return
  631. video_description = mobj.group(1).decode('utf-8')
  632. if not video_description:
  633. video_description = 'No description available.'
  634. # Extract video thumbnail
  635. if self._downloader.params.get('forcethumbnail', False):
  636. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  637. try:
  638. webpage = urllib2.urlopen(request).read()
  639. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  640. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  641. return
  642. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  643. if mobj is None:
  644. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  645. return
  646. video_thumbnail = mobj.group(1)
  647. else: # we need something to pass to process_info
  648. video_thumbnail = ''
  649. return [{
  650. 'id': video_id.decode('utf-8'),
  651. 'url': video_url.decode('utf-8'),
  652. 'uploader': u'NA',
  653. 'upload_date': u'NA',
  654. 'title': video_title,
  655. 'ext': video_extension.decode('utf-8'),
  656. 'format': u'NA',
  657. 'player_url': None,
  658. }]
  659. class PhotobucketIE(InfoExtractor):
  660. """Information extractor for photobucket.com."""
  661. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  662. IE_NAME = u'photobucket'
  663. def __init__(self, downloader=None):
  664. InfoExtractor.__init__(self, downloader)
  665. def report_download_webpage(self, video_id):
  666. """Report webpage download."""
  667. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  668. def report_extraction(self, video_id):
  669. """Report information extraction."""
  670. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  671. def _real_extract(self, url):
  672. # Extract id from URL
  673. mobj = re.match(self._VALID_URL, url)
  674. if mobj is None:
  675. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  676. return
  677. video_id = mobj.group(1)
  678. video_extension = 'flv'
  679. # Retrieve video webpage to extract further information
  680. request = urllib2.Request(url)
  681. try:
  682. self.report_download_webpage(video_id)
  683. webpage = urllib2.urlopen(request).read()
  684. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  685. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  686. return
  687. # Extract URL, uploader, and title from webpage
  688. self.report_extraction(video_id)
  689. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  690. if mobj is None:
  691. self._downloader.trouble(u'ERROR: unable to extract media URL')
  692. return
  693. mediaURL = urllib.unquote(mobj.group(1))
  694. video_url = mediaURL
  695. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  696. if mobj is None:
  697. self._downloader.trouble(u'ERROR: unable to extract title')
  698. return
  699. video_title = mobj.group(1).decode('utf-8')
  700. video_uploader = mobj.group(2).decode('utf-8')
  701. return [{
  702. 'id': video_id.decode('utf-8'),
  703. 'url': video_url.decode('utf-8'),
  704. 'uploader': video_uploader,
  705. 'upload_date': u'NA',
  706. 'title': video_title,
  707. 'ext': video_extension.decode('utf-8'),
  708. 'format': u'NA',
  709. 'player_url': None,
  710. }]
  711. class YahooIE(InfoExtractor):
  712. """Information extractor for video.yahoo.com."""
  713. # _VALID_URL matches all Yahoo! Video URLs
  714. # _VPAGE_URL matches only the extractable '/watch/' URLs
  715. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  716. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  717. IE_NAME = u'video.yahoo'
  718. def __init__(self, downloader=None):
  719. InfoExtractor.__init__(self, downloader)
  720. def report_download_webpage(self, video_id):
  721. """Report webpage download."""
  722. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  723. def report_extraction(self, video_id):
  724. """Report information extraction."""
  725. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  726. def _real_extract(self, url, new_video=True):
  727. # Extract ID from URL
  728. mobj = re.match(self._VALID_URL, url)
  729. if mobj is None:
  730. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  731. return
  732. video_id = mobj.group(2)
  733. video_extension = 'flv'
  734. # Rewrite valid but non-extractable URLs as
  735. # extractable English language /watch/ URLs
  736. if re.match(self._VPAGE_URL, url) is None:
  737. request = urllib2.Request(url)
  738. try:
  739. webpage = urllib2.urlopen(request).read()
  740. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  741. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  742. return
  743. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  744. if mobj is None:
  745. self._downloader.trouble(u'ERROR: Unable to extract id field')
  746. return
  747. yahoo_id = mobj.group(1)
  748. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  749. if mobj is None:
  750. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  751. return
  752. yahoo_vid = mobj.group(1)
  753. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  754. return self._real_extract(url, new_video=False)
  755. # Retrieve video webpage to extract further information
  756. request = urllib2.Request(url)
  757. try:
  758. self.report_download_webpage(video_id)
  759. webpage = urllib2.urlopen(request).read()
  760. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  761. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  762. return
  763. # Extract uploader and title from webpage
  764. self.report_extraction(video_id)
  765. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  766. if mobj is None:
  767. self._downloader.trouble(u'ERROR: unable to extract video title')
  768. return
  769. video_title = mobj.group(1).decode('utf-8')
  770. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  771. if mobj is None:
  772. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  773. return
  774. video_uploader = mobj.group(1).decode('utf-8')
  775. # Extract video thumbnail
  776. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  777. if mobj is None:
  778. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  779. return
  780. video_thumbnail = mobj.group(1).decode('utf-8')
  781. # Extract video description
  782. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  783. if mobj is None:
  784. self._downloader.trouble(u'ERROR: unable to extract video description')
  785. return
  786. video_description = mobj.group(1).decode('utf-8')
  787. if not video_description:
  788. video_description = 'No description available.'
  789. # Extract video height and width
  790. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  791. if mobj is None:
  792. self._downloader.trouble(u'ERROR: unable to extract video height')
  793. return
  794. yv_video_height = mobj.group(1)
  795. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  796. if mobj is None:
  797. self._downloader.trouble(u'ERROR: unable to extract video width')
  798. return
  799. yv_video_width = mobj.group(1)
  800. # Retrieve video playlist to extract media URL
  801. # I'm not completely sure what all these options are, but we
  802. # seem to need most of them, otherwise the server sends a 401.
  803. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  804. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  805. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  806. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  807. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  808. try:
  809. self.report_download_webpage(video_id)
  810. webpage = urllib2.urlopen(request).read()
  811. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  812. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  813. return
  814. # Extract media URL from playlist XML
  815. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  816. if mobj is None:
  817. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  818. return
  819. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  820. video_url = unescapeHTML(video_url)
  821. return [{
  822. 'id': video_id.decode('utf-8'),
  823. 'url': video_url,
  824. 'uploader': video_uploader,
  825. 'upload_date': u'NA',
  826. 'title': video_title,
  827. 'ext': video_extension.decode('utf-8'),
  828. 'thumbnail': video_thumbnail.decode('utf-8'),
  829. 'description': video_description,
  830. 'thumbnail': video_thumbnail,
  831. 'player_url': None,
  832. }]
  833. class VimeoIE(InfoExtractor):
  834. """Information extractor for vimeo.com."""
  835. # _VALID_URL matches Vimeo URLs
  836. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:groups/[^/]+/)?(?:videos?/)?([0-9]+)'
  837. IE_NAME = u'vimeo'
  838. def __init__(self, downloader=None):
  839. InfoExtractor.__init__(self, downloader)
  840. def report_download_webpage(self, video_id):
  841. """Report webpage download."""
  842. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  843. def report_extraction(self, video_id):
  844. """Report information extraction."""
  845. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  846. def _real_extract(self, url, new_video=True):
  847. # Extract ID from URL
  848. mobj = re.match(self._VALID_URL, url)
  849. if mobj is None:
  850. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  851. return
  852. video_id = mobj.group(1)
  853. # Retrieve video webpage to extract further information
  854. request = urllib2.Request(url, None, std_headers)
  855. try:
  856. self.report_download_webpage(video_id)
  857. webpage = urllib2.urlopen(request).read()
  858. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  859. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  860. return
  861. # Now we begin extracting as much information as we can from what we
  862. # retrieved. First we extract the information common to all extractors,
  863. # and latter we extract those that are Vimeo specific.
  864. self.report_extraction(video_id)
  865. # Extract the config JSON
  866. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  867. try:
  868. config = json.loads(config)
  869. except:
  870. self._downloader.trouble(u'ERROR: unable to extract info section')
  871. return
  872. # Extract title
  873. video_title = config["video"]["title"]
  874. # Extract uploader
  875. video_uploader = config["video"]["owner"]["name"]
  876. # Extract video thumbnail
  877. video_thumbnail = config["video"]["thumbnail"]
  878. # Extract video description
  879. video_description = get_element_by_id("description", webpage.decode('utf8'))
  880. if video_description: video_description = clean_html(video_description)
  881. else: video_description = ''
  882. # Extract upload date
  883. video_upload_date = u'NA'
  884. mobj = re.search(r'<span id="clip-date" style="display:none">[^:]*: (.*?)( \([^\(]*\))?</span>', webpage)
  885. if mobj is not None:
  886. video_upload_date = mobj.group(1)
  887. # Vimeo specific: extract request signature and timestamp
  888. sig = config['request']['signature']
  889. timestamp = config['request']['timestamp']
  890. # Vimeo specific: extract video codec and quality information
  891. # TODO bind to format param
  892. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  893. for codec in codecs:
  894. if codec[0] in config["video"]["files"]:
  895. video_codec = codec[0]
  896. video_extension = codec[1]
  897. if 'hd' in config["video"]["files"][codec[0]]: quality = 'hd'
  898. else: quality = 'sd'
  899. break
  900. else:
  901. self._downloader.trouble(u'ERROR: no known codec found')
  902. return
  903. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  904. %(video_id, sig, timestamp, quality, video_codec.upper())
  905. return [{
  906. 'id': video_id,
  907. 'url': video_url,
  908. 'uploader': video_uploader,
  909. 'upload_date': video_upload_date,
  910. 'title': video_title,
  911. 'ext': video_extension,
  912. 'thumbnail': video_thumbnail,
  913. 'description': video_description,
  914. 'player_url': None,
  915. }]
  916. class GenericIE(InfoExtractor):
  917. """Generic last-resort information extractor."""
  918. _VALID_URL = r'.*'
  919. IE_NAME = u'generic'
  920. def __init__(self, downloader=None):
  921. InfoExtractor.__init__(self, downloader)
  922. def report_download_webpage(self, video_id):
  923. """Report webpage download."""
  924. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  925. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  926. def report_extraction(self, video_id):
  927. """Report information extraction."""
  928. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  929. def report_following_redirect(self, new_url):
  930. """Report information extraction."""
  931. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  932. def _test_redirect(self, url):
  933. """Check if it is a redirect, like url shorteners, in case restart chain."""
  934. class HeadRequest(urllib2.Request):
  935. def get_method(self):
  936. return "HEAD"
  937. class HEADRedirectHandler(urllib2.HTTPRedirectHandler):
  938. """
  939. Subclass the HTTPRedirectHandler to make it use our
  940. HeadRequest also on the redirected URL
  941. """
  942. def redirect_request(self, req, fp, code, msg, headers, newurl):
  943. if code in (301, 302, 303, 307):
  944. newurl = newurl.replace(' ', '%20')
  945. newheaders = dict((k,v) for k,v in req.headers.items()
  946. if k.lower() not in ("content-length", "content-type"))
  947. return HeadRequest(newurl,
  948. headers=newheaders,
  949. origin_req_host=req.get_origin_req_host(),
  950. unverifiable=True)
  951. else:
  952. raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
  953. class HTTPMethodFallback(urllib2.BaseHandler):
  954. """
  955. Fallback to GET if HEAD is not allowed (405 HTTP error)
  956. """
  957. def http_error_405(self, req, fp, code, msg, headers):
  958. fp.read()
  959. fp.close()
  960. newheaders = dict((k,v) for k,v in req.headers.items()
  961. if k.lower() not in ("content-length", "content-type"))
  962. return self.parent.open(urllib2.Request(req.get_full_url(),
  963. headers=newheaders,
  964. origin_req_host=req.get_origin_req_host(),
  965. unverifiable=True))
  966. # Build our opener
  967. opener = urllib2.OpenerDirector()
  968. for handler in [urllib2.HTTPHandler, urllib2.HTTPDefaultErrorHandler,
  969. HTTPMethodFallback, HEADRedirectHandler,
  970. urllib2.HTTPErrorProcessor, urllib2.HTTPSHandler]:
  971. opener.add_handler(handler())
  972. response = opener.open(HeadRequest(url))
  973. new_url = response.geturl()
  974. if url == new_url: return False
  975. self.report_following_redirect(new_url)
  976. self._downloader.download([new_url])
  977. return True
  978. def _real_extract(self, url):
  979. if self._test_redirect(url): return
  980. video_id = url.split('/')[-1]
  981. request = urllib2.Request(url)
  982. try:
  983. self.report_download_webpage(video_id)
  984. webpage = urllib2.urlopen(request).read()
  985. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  986. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  987. return
  988. except ValueError, err:
  989. # since this is the last-resort InfoExtractor, if
  990. # this error is thrown, it'll be thrown here
  991. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  992. return
  993. self.report_extraction(video_id)
  994. # Start with something easy: JW Player in SWFObject
  995. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  996. if mobj is None:
  997. # Broaden the search a little bit
  998. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  999. if mobj is None:
  1000. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1001. return
  1002. # It's possible that one of the regexes
  1003. # matched, but returned an empty group:
  1004. if mobj.group(1) is None:
  1005. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1006. return
  1007. video_url = urllib.unquote(mobj.group(1))
  1008. video_id = os.path.basename(video_url)
  1009. # here's a fun little line of code for you:
  1010. video_extension = os.path.splitext(video_id)[1][1:]
  1011. video_id = os.path.splitext(video_id)[0]
  1012. # it's tempting to parse this further, but you would
  1013. # have to take into account all the variations like
  1014. # Video Title - Site Name
  1015. # Site Name | Video Title
  1016. # Video Title - Tagline | Site Name
  1017. # and so on and so forth; it's just not practical
  1018. mobj = re.search(r'<title>(.*)</title>', webpage)
  1019. if mobj is None:
  1020. self._downloader.trouble(u'ERROR: unable to extract title')
  1021. return
  1022. video_title = mobj.group(1).decode('utf-8')
  1023. # video uploader is domain name
  1024. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1025. if mobj is None:
  1026. self._downloader.trouble(u'ERROR: unable to extract title')
  1027. return
  1028. video_uploader = mobj.group(1).decode('utf-8')
  1029. return [{
  1030. 'id': video_id.decode('utf-8'),
  1031. 'url': video_url.decode('utf-8'),
  1032. 'uploader': video_uploader,
  1033. 'upload_date': u'NA',
  1034. 'title': video_title,
  1035. 'ext': video_extension.decode('utf-8'),
  1036. 'format': u'NA',
  1037. 'player_url': None,
  1038. }]
  1039. class YoutubeSearchIE(InfoExtractor):
  1040. """Information Extractor for YouTube search queries."""
  1041. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1042. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1043. _max_youtube_results = 1000
  1044. IE_NAME = u'youtube:search'
  1045. def __init__(self, downloader=None):
  1046. InfoExtractor.__init__(self, downloader)
  1047. def report_download_page(self, query, pagenum):
  1048. """Report attempt to download search page with given number."""
  1049. query = query.decode(preferredencoding())
  1050. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1051. def _real_extract(self, query):
  1052. mobj = re.match(self._VALID_URL, query)
  1053. if mobj is None:
  1054. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1055. return
  1056. prefix, query = query.split(':')
  1057. prefix = prefix[8:]
  1058. query = query.encode('utf-8')
  1059. if prefix == '':
  1060. self._download_n_results(query, 1)
  1061. return
  1062. elif prefix == 'all':
  1063. self._download_n_results(query, self._max_youtube_results)
  1064. return
  1065. else:
  1066. try:
  1067. n = long(prefix)
  1068. if n <= 0:
  1069. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1070. return
  1071. elif n > self._max_youtube_results:
  1072. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1073. n = self._max_youtube_results
  1074. self._download_n_results(query, n)
  1075. return
  1076. except ValueError: # parsing prefix as integer fails
  1077. self._download_n_results(query, 1)
  1078. return
  1079. def _download_n_results(self, query, n):
  1080. """Downloads a specified number of results for a query"""
  1081. video_ids = []
  1082. pagenum = 0
  1083. limit = n
  1084. while (50 * pagenum) < limit:
  1085. self.report_download_page(query, pagenum+1)
  1086. result_url = self._API_URL % (urllib.quote_plus(query), (50*pagenum)+1)
  1087. request = urllib2.Request(result_url)
  1088. try:
  1089. data = urllib2.urlopen(request).read()
  1090. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1091. self._downloader.trouble(u'ERROR: unable to download API page: %s' % str(err))
  1092. return
  1093. api_response = json.loads(data)['data']
  1094. new_ids = list(video['id'] for video in api_response['items'])
  1095. video_ids += new_ids
  1096. limit = min(n, api_response['totalItems'])
  1097. pagenum += 1
  1098. if len(video_ids) > n:
  1099. video_ids = video_ids[:n]
  1100. for id in video_ids:
  1101. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1102. return
  1103. class GoogleSearchIE(InfoExtractor):
  1104. """Information Extractor for Google Video search queries."""
  1105. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1106. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1107. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1108. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1109. _max_google_results = 1000
  1110. IE_NAME = u'video.google:search'
  1111. def __init__(self, downloader=None):
  1112. InfoExtractor.__init__(self, downloader)
  1113. def report_download_page(self, query, pagenum):
  1114. """Report attempt to download playlist page with given number."""
  1115. query = query.decode(preferredencoding())
  1116. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1117. def _real_extract(self, query):
  1118. mobj = re.match(self._VALID_URL, query)
  1119. if mobj is None:
  1120. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1121. return
  1122. prefix, query = query.split(':')
  1123. prefix = prefix[8:]
  1124. query = query.encode('utf-8')
  1125. if prefix == '':
  1126. self._download_n_results(query, 1)
  1127. return
  1128. elif prefix == 'all':
  1129. self._download_n_results(query, self._max_google_results)
  1130. return
  1131. else:
  1132. try:
  1133. n = long(prefix)
  1134. if n <= 0:
  1135. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1136. return
  1137. elif n > self._max_google_results:
  1138. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1139. n = self._max_google_results
  1140. self._download_n_results(query, n)
  1141. return
  1142. except ValueError: # parsing prefix as integer fails
  1143. self._download_n_results(query, 1)
  1144. return
  1145. def _download_n_results(self, query, n):
  1146. """Downloads a specified number of results for a query"""
  1147. video_ids = []
  1148. pagenum = 0
  1149. while True:
  1150. self.report_download_page(query, pagenum)
  1151. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum*10)
  1152. request = urllib2.Request(result_url)
  1153. try:
  1154. page = urllib2.urlopen(request).read()
  1155. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1156. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1157. return
  1158. # Extract video identifiers
  1159. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1160. video_id = mobj.group(1)
  1161. if video_id not in video_ids:
  1162. video_ids.append(video_id)
  1163. if len(video_ids) == n:
  1164. # Specified n videos reached
  1165. for id in video_ids:
  1166. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1167. return
  1168. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1169. for id in video_ids:
  1170. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1171. return
  1172. pagenum = pagenum + 1
  1173. class YahooSearchIE(InfoExtractor):
  1174. """Information Extractor for Yahoo! Video search queries."""
  1175. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1176. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1177. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1178. _MORE_PAGES_INDICATOR = r'\s*Next'
  1179. _max_yahoo_results = 1000
  1180. IE_NAME = u'video.yahoo:search'
  1181. def __init__(self, downloader=None):
  1182. InfoExtractor.__init__(self, downloader)
  1183. def report_download_page(self, query, pagenum):
  1184. """Report attempt to download playlist page with given number."""
  1185. query = query.decode(preferredencoding())
  1186. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1187. def _real_extract(self, query):
  1188. mobj = re.match(self._VALID_URL, query)
  1189. if mobj is None:
  1190. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1191. return
  1192. prefix, query = query.split(':')
  1193. prefix = prefix[8:]
  1194. query = query.encode('utf-8')
  1195. if prefix == '':
  1196. self._download_n_results(query, 1)
  1197. return
  1198. elif prefix == 'all':
  1199. self._download_n_results(query, self._max_yahoo_results)
  1200. return
  1201. else:
  1202. try:
  1203. n = long(prefix)
  1204. if n <= 0:
  1205. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1206. return
  1207. elif n > self._max_yahoo_results:
  1208. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1209. n = self._max_yahoo_results
  1210. self._download_n_results(query, n)
  1211. return
  1212. except ValueError: # parsing prefix as integer fails
  1213. self._download_n_results(query, 1)
  1214. return
  1215. def _download_n_results(self, query, n):
  1216. """Downloads a specified number of results for a query"""
  1217. video_ids = []
  1218. already_seen = set()
  1219. pagenum = 1
  1220. while True:
  1221. self.report_download_page(query, pagenum)
  1222. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1223. request = urllib2.Request(result_url)
  1224. try:
  1225. page = urllib2.urlopen(request).read()
  1226. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1227. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1228. return
  1229. # Extract video identifiers
  1230. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1231. video_id = mobj.group(1)
  1232. if video_id not in already_seen:
  1233. video_ids.append(video_id)
  1234. already_seen.add(video_id)
  1235. if len(video_ids) == n:
  1236. # Specified n videos reached
  1237. for id in video_ids:
  1238. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1239. return
  1240. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1241. for id in video_ids:
  1242. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1243. return
  1244. pagenum = pagenum + 1
  1245. class YoutubePlaylistIE(InfoExtractor):
  1246. """Information Extractor for YouTube playlists."""
  1247. _VALID_URL = r'(?:https?://)?(?:\w+\.)?youtube\.com/(?:(?:course|view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)(?:PL)?([0-9A-Za-z-_]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1248. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1249. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;list=.*?%s'
  1250. _MORE_PAGES_INDICATOR = r'yt-uix-pager-next'
  1251. IE_NAME = u'youtube:playlist'
  1252. def __init__(self, downloader=None):
  1253. InfoExtractor.__init__(self, downloader)
  1254. def report_download_page(self, playlist_id, pagenum):
  1255. """Report attempt to download playlist page with given number."""
  1256. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1257. def _real_extract(self, url):
  1258. # Extract playlist id
  1259. mobj = re.match(self._VALID_URL, url)
  1260. if mobj is None:
  1261. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1262. return
  1263. # Single video case
  1264. if mobj.group(3) is not None:
  1265. self._downloader.download([mobj.group(3)])
  1266. return
  1267. # Download playlist pages
  1268. # prefix is 'p' as default for playlists but there are other types that need extra care
  1269. playlist_prefix = mobj.group(1)
  1270. if playlist_prefix == 'a':
  1271. playlist_access = 'artist'
  1272. else:
  1273. playlist_prefix = 'p'
  1274. playlist_access = 'view_play_list'
  1275. playlist_id = mobj.group(2)
  1276. video_ids = []
  1277. pagenum = 1
  1278. while True:
  1279. self.report_download_page(playlist_id, pagenum)
  1280. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  1281. request = urllib2.Request(url)
  1282. try:
  1283. page = urllib2.urlopen(request).read()
  1284. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1285. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1286. return
  1287. # Extract video identifiers
  1288. ids_in_page = []
  1289. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  1290. if mobj.group(1) not in ids_in_page:
  1291. ids_in_page.append(mobj.group(1))
  1292. video_ids.extend(ids_in_page)
  1293. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1294. break
  1295. pagenum = pagenum + 1
  1296. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1297. playlistend = self._downloader.params.get('playlistend', -1)
  1298. if playlistend == -1:
  1299. video_ids = video_ids[playliststart:]
  1300. else:
  1301. video_ids = video_ids[playliststart:playlistend]
  1302. for id in video_ids:
  1303. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1304. return
  1305. class YoutubeUserIE(InfoExtractor):
  1306. """Information Extractor for YouTube users."""
  1307. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1308. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1309. _GDATA_PAGE_SIZE = 50
  1310. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1311. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1312. IE_NAME = u'youtube:user'
  1313. def __init__(self, downloader=None):
  1314. InfoExtractor.__init__(self, downloader)
  1315. def report_download_page(self, username, start_index):
  1316. """Report attempt to download user page."""
  1317. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1318. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1319. def _real_extract(self, url):
  1320. # Extract username
  1321. mobj = re.match(self._VALID_URL, url)
  1322. if mobj is None:
  1323. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1324. return
  1325. username = mobj.group(1)
  1326. # Download video ids using YouTube Data API. Result size per
  1327. # query is limited (currently to 50 videos) so we need to query
  1328. # page by page until there are no video ids - it means we got
  1329. # all of them.
  1330. video_ids = []
  1331. pagenum = 0
  1332. while True:
  1333. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1334. self.report_download_page(username, start_index)
  1335. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1336. try:
  1337. page = urllib2.urlopen(request).read()
  1338. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1339. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1340. return
  1341. # Extract video identifiers
  1342. ids_in_page = []
  1343. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1344. if mobj.group(1) not in ids_in_page:
  1345. ids_in_page.append(mobj.group(1))
  1346. video_ids.extend(ids_in_page)
  1347. # A little optimization - if current page is not
  1348. # "full", ie. does not contain PAGE_SIZE video ids then
  1349. # we can assume that this page is the last one - there
  1350. # are no more ids on further pages - no need to query
  1351. # again.
  1352. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1353. break
  1354. pagenum += 1
  1355. all_ids_count = len(video_ids)
  1356. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1357. playlistend = self._downloader.params.get('playlistend', -1)
  1358. if playlistend == -1:
  1359. video_ids = video_ids[playliststart:]
  1360. else:
  1361. video_ids = video_ids[playliststart:playlistend]
  1362. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1363. (username, all_ids_count, len(video_ids)))
  1364. for video_id in video_ids:
  1365. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1366. class BlipTVUserIE(InfoExtractor):
  1367. """Information Extractor for blip.tv users."""
  1368. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1369. _PAGE_SIZE = 12
  1370. IE_NAME = u'blip.tv:user'
  1371. def __init__(self, downloader=None):
  1372. InfoExtractor.__init__(self, downloader)
  1373. def report_download_page(self, username, pagenum):
  1374. """Report attempt to download user page."""
  1375. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1376. (self.IE_NAME, username, pagenum))
  1377. def _real_extract(self, url):
  1378. # Extract username
  1379. mobj = re.match(self._VALID_URL, url)
  1380. if mobj is None:
  1381. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1382. return
  1383. username = mobj.group(1)
  1384. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1385. request = urllib2.Request(url)
  1386. try:
  1387. page = urllib2.urlopen(request).read().decode('utf-8')
  1388. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1389. page_base = page_base % mobj.group(1)
  1390. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1391. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1392. return
  1393. # Download video ids using BlipTV Ajax calls. Result size per
  1394. # query is limited (currently to 12 videos) so we need to query
  1395. # page by page until there are no video ids - it means we got
  1396. # all of them.
  1397. video_ids = []
  1398. pagenum = 1
  1399. while True:
  1400. self.report_download_page(username, pagenum)
  1401. request = urllib2.Request( page_base + "&page=" + str(pagenum) )
  1402. try:
  1403. page = urllib2.urlopen(request).read().decode('utf-8')
  1404. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1405. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1406. return
  1407. # Extract video identifiers
  1408. ids_in_page = []
  1409. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1410. if mobj.group(1) not in ids_in_page:
  1411. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1412. video_ids.extend(ids_in_page)
  1413. # A little optimization - if current page is not
  1414. # "full", ie. does not contain PAGE_SIZE video ids then
  1415. # we can assume that this page is the last one - there
  1416. # are no more ids on further pages - no need to query
  1417. # again.
  1418. if len(ids_in_page) < self._PAGE_SIZE:
  1419. break
  1420. pagenum += 1
  1421. all_ids_count = len(video_ids)
  1422. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1423. playlistend = self._downloader.params.get('playlistend', -1)
  1424. if playlistend == -1:
  1425. video_ids = video_ids[playliststart:]
  1426. else:
  1427. video_ids = video_ids[playliststart:playlistend]
  1428. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1429. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1430. for video_id in video_ids:
  1431. self._downloader.download([u'http://blip.tv/'+video_id])
  1432. class DepositFilesIE(InfoExtractor):
  1433. """Information extractor for depositfiles.com"""
  1434. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1435. IE_NAME = u'DepositFiles'
  1436. def __init__(self, downloader=None):
  1437. InfoExtractor.__init__(self, downloader)
  1438. def report_download_webpage(self, file_id):
  1439. """Report webpage download."""
  1440. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1441. def report_extraction(self, file_id):
  1442. """Report information extraction."""
  1443. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1444. def _real_extract(self, url):
  1445. file_id = url.split('/')[-1]
  1446. # Rebuild url in english locale
  1447. url = 'http://depositfiles.com/en/files/' + file_id
  1448. # Retrieve file webpage with 'Free download' button pressed
  1449. free_download_indication = { 'gateway_result' : '1' }
  1450. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  1451. try:
  1452. self.report_download_webpage(file_id)
  1453. webpage = urllib2.urlopen(request).read()
  1454. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1455. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  1456. return
  1457. # Search for the real file URL
  1458. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1459. if (mobj is None) or (mobj.group(1) is None):
  1460. # Try to figure out reason of the error.
  1461. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1462. if (mobj is not None) and (mobj.group(1) is not None):
  1463. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1464. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1465. else:
  1466. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1467. return
  1468. file_url = mobj.group(1)
  1469. file_extension = os.path.splitext(file_url)[1][1:]
  1470. # Search for file title
  1471. mobj = re.search(r'<b title="(.*?)">', webpage)
  1472. if mobj is None:
  1473. self._downloader.trouble(u'ERROR: unable to extract title')
  1474. return
  1475. file_title = mobj.group(1).decode('utf-8')
  1476. return [{
  1477. 'id': file_id.decode('utf-8'),
  1478. 'url': file_url.decode('utf-8'),
  1479. 'uploader': u'NA',
  1480. 'upload_date': u'NA',
  1481. 'title': file_title,
  1482. 'ext': file_extension.decode('utf-8'),
  1483. 'format': u'NA',
  1484. 'player_url': None,
  1485. }]
  1486. class FacebookIE(InfoExtractor):
  1487. """Information Extractor for Facebook"""
  1488. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1489. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1490. _NETRC_MACHINE = 'facebook'
  1491. _available_formats = ['video', 'highqual', 'lowqual']
  1492. _video_extensions = {
  1493. 'video': 'mp4',
  1494. 'highqual': 'mp4',
  1495. 'lowqual': 'mp4',
  1496. }
  1497. IE_NAME = u'facebook'
  1498. def __init__(self, downloader=None):
  1499. InfoExtractor.__init__(self, downloader)
  1500. def _reporter(self, message):
  1501. """Add header and report message."""
  1502. self._downloader.to_screen(u'[facebook] %s' % message)
  1503. def report_login(self):
  1504. """Report attempt to log in."""
  1505. self._reporter(u'Logging in')
  1506. def report_video_webpage_download(self, video_id):
  1507. """Report attempt to download video webpage."""
  1508. self._reporter(u'%s: Downloading video webpage' % video_id)
  1509. def report_information_extraction(self, video_id):
  1510. """Report attempt to extract video information."""
  1511. self._reporter(u'%s: Extracting video information' % video_id)
  1512. def _parse_page(self, video_webpage):
  1513. """Extract video information from page"""
  1514. # General data
  1515. data = {'title': r'\("video_title", "(.*?)"\)',
  1516. 'description': r'<div class="datawrap">(.*?)</div>',
  1517. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1518. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1519. }
  1520. video_info = {}
  1521. for piece in data.keys():
  1522. mobj = re.search(data[piece], video_webpage)
  1523. if mobj is not None:
  1524. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1525. # Video urls
  1526. video_urls = {}
  1527. for fmt in self._available_formats:
  1528. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1529. if mobj is not None:
  1530. # URL is in a Javascript segment inside an escaped Unicode format within
  1531. # the generally utf-8 page
  1532. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1533. video_info['video_urls'] = video_urls
  1534. return video_info
  1535. def _real_initialize(self):
  1536. if self._downloader is None:
  1537. return
  1538. useremail = None
  1539. password = None
  1540. downloader_params = self._downloader.params
  1541. # Attempt to use provided username and password or .netrc data
  1542. if downloader_params.get('username', None) is not None:
  1543. useremail = downloader_params['username']
  1544. password = downloader_params['password']
  1545. elif downloader_params.get('usenetrc', False):
  1546. try:
  1547. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1548. if info is not None:
  1549. useremail = info[0]
  1550. password = info[2]
  1551. else:
  1552. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1553. except (IOError, netrc.NetrcParseError), err:
  1554. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  1555. return
  1556. if useremail is None:
  1557. return
  1558. # Log in
  1559. login_form = {
  1560. 'email': useremail,
  1561. 'pass': password,
  1562. 'login': 'Log+In'
  1563. }
  1564. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  1565. try:
  1566. self.report_login()
  1567. login_results = urllib2.urlopen(request).read()
  1568. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1569. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1570. return
  1571. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1572. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  1573. return
  1574. def _real_extract(self, url):
  1575. mobj = re.match(self._VALID_URL, url)
  1576. if mobj is None:
  1577. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1578. return
  1579. video_id = mobj.group('ID')
  1580. # Get video webpage
  1581. self.report_video_webpage_download(video_id)
  1582. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1583. try:
  1584. page = urllib2.urlopen(request)
  1585. video_webpage = page.read()
  1586. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1587. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  1588. return
  1589. # Start extracting information
  1590. self.report_information_extraction(video_id)
  1591. # Extract information
  1592. video_info = self._parse_page(video_webpage)
  1593. # uploader
  1594. if 'owner' not in video_info:
  1595. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1596. return
  1597. video_uploader = video_info['owner']
  1598. # title
  1599. if 'title' not in video_info:
  1600. self._downloader.trouble(u'ERROR: unable to extract video title')
  1601. return
  1602. video_title = video_info['title']
  1603. video_title = video_title.decode('utf-8')
  1604. # thumbnail image
  1605. if 'thumbnail' not in video_info:
  1606. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1607. video_thumbnail = ''
  1608. else:
  1609. video_thumbnail = video_info['thumbnail']
  1610. # upload date
  1611. upload_date = u'NA'
  1612. if 'upload_date' in video_info:
  1613. upload_time = video_info['upload_date']
  1614. timetuple = email.utils.parsedate_tz(upload_time)
  1615. if timetuple is not None:
  1616. try:
  1617. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1618. except:
  1619. pass
  1620. # description
  1621. video_description = video_info.get('description', 'No description available.')
  1622. url_map = video_info['video_urls']
  1623. if len(url_map.keys()) > 0:
  1624. # Decide which formats to download
  1625. req_format = self._downloader.params.get('format', None)
  1626. format_limit = self._downloader.params.get('format_limit', None)
  1627. if format_limit is not None and format_limit in self._available_formats:
  1628. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1629. else:
  1630. format_list = self._available_formats
  1631. existing_formats = [x for x in format_list if x in url_map]
  1632. if len(existing_formats) == 0:
  1633. self._downloader.trouble(u'ERROR: no known formats available for video')
  1634. return
  1635. if req_format is None:
  1636. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1637. elif req_format == 'worst':
  1638. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1639. elif req_format == '-1':
  1640. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1641. else:
  1642. # Specific format
  1643. if req_format not in url_map:
  1644. self._downloader.trouble(u'ERROR: requested format not available')
  1645. return
  1646. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1647. results = []
  1648. for format_param, video_real_url in video_url_list:
  1649. # Extension
  1650. video_extension = self._video_extensions.get(format_param, 'mp4')
  1651. results.append({
  1652. 'id': video_id.decode('utf-8'),
  1653. 'url': video_real_url.decode('utf-8'),
  1654. 'uploader': video_uploader.decode('utf-8'),
  1655. 'upload_date': upload_date,
  1656. 'title': video_title,
  1657. 'ext': video_extension.decode('utf-8'),
  1658. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1659. 'thumbnail': video_thumbnail.decode('utf-8'),
  1660. 'description': video_description.decode('utf-8'),
  1661. 'player_url': None,
  1662. })
  1663. return results
  1664. class BlipTVIE(InfoExtractor):
  1665. """Information extractor for blip.tv"""
  1666. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1667. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1668. IE_NAME = u'blip.tv'
  1669. def report_extraction(self, file_id):
  1670. """Report information extraction."""
  1671. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1672. def report_direct_download(self, title):
  1673. """Report information extraction."""
  1674. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1675. def _real_extract(self, url):
  1676. mobj = re.match(self._VALID_URL, url)
  1677. if mobj is None:
  1678. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1679. return
  1680. if '?' in url:
  1681. cchar = '&'
  1682. else:
  1683. cchar = '?'
  1684. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1685. request = urllib2.Request(json_url.encode('utf-8'))
  1686. self.report_extraction(mobj.group(1))
  1687. info = None
  1688. try:
  1689. urlh = urllib2.urlopen(request)
  1690. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1691. basename = url.split('/')[-1]
  1692. title,ext = os.path.splitext(basename)
  1693. title = title.decode('UTF-8')
  1694. ext = ext.replace('.', '')
  1695. self.report_direct_download(title)
  1696. info = {
  1697. 'id': title,
  1698. 'url': url,
  1699. 'title': title,
  1700. 'ext': ext,
  1701. 'urlhandle': urlh
  1702. }
  1703. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1704. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  1705. return
  1706. if info is None: # Regular URL
  1707. try:
  1708. json_code = urlh.read()
  1709. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1710. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % str(err))
  1711. return
  1712. try:
  1713. json_data = json.loads(json_code)
  1714. if 'Post' in json_data:
  1715. data = json_data['Post']
  1716. else:
  1717. data = json_data
  1718. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1719. video_url = data['media']['url']
  1720. umobj = re.match(self._URL_EXT, video_url)
  1721. if umobj is None:
  1722. raise ValueError('Can not determine filename extension')
  1723. ext = umobj.group(1)
  1724. info = {
  1725. 'id': data['item_id'],
  1726. 'url': video_url,
  1727. 'uploader': data['display_name'],
  1728. 'upload_date': upload_date,
  1729. 'title': data['title'],
  1730. 'ext': ext,
  1731. 'format': data['media']['mimeType'],
  1732. 'thumbnail': data['thumbnailUrl'],
  1733. 'description': data['description'],
  1734. 'player_url': data['embedUrl']
  1735. }
  1736. except (ValueError,KeyError), err:
  1737. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1738. return
  1739. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1740. return [info]
  1741. class MyVideoIE(InfoExtractor):
  1742. """Information Extractor for myvideo.de."""
  1743. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1744. IE_NAME = u'myvideo'
  1745. def __init__(self, downloader=None):
  1746. InfoExtractor.__init__(self, downloader)
  1747. def report_download_webpage(self, video_id):
  1748. """Report webpage download."""
  1749. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1750. def report_extraction(self, video_id):
  1751. """Report information extraction."""
  1752. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1753. def _real_extract(self,url):
  1754. mobj = re.match(self._VALID_URL, url)
  1755. if mobj is None:
  1756. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1757. return
  1758. video_id = mobj.group(1)
  1759. # Get video webpage
  1760. request = urllib2.Request('http://www.myvideo.de/watch/%s' % video_id)
  1761. try:
  1762. self.report_download_webpage(video_id)
  1763. webpage = urllib2.urlopen(request).read()
  1764. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1765. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1766. return
  1767. self.report_extraction(video_id)
  1768. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1769. webpage)
  1770. if mobj is None:
  1771. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1772. return
  1773. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1774. mobj = re.search('<title>([^<]+)</title>', webpage)
  1775. if mobj is None:
  1776. self._downloader.trouble(u'ERROR: unable to extract title')
  1777. return
  1778. video_title = mobj.group(1)
  1779. return [{
  1780. 'id': video_id,
  1781. 'url': video_url,
  1782. 'uploader': u'NA',
  1783. 'upload_date': u'NA',
  1784. 'title': video_title,
  1785. 'ext': u'flv',
  1786. 'format': u'NA',
  1787. 'player_url': None,
  1788. }]
  1789. class ComedyCentralIE(InfoExtractor):
  1790. """Information extractor for The Daily Show and Colbert Report """
  1791. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  1792. IE_NAME = u'comedycentral'
  1793. def report_extraction(self, episode_id):
  1794. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1795. def report_config_download(self, episode_id):
  1796. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  1797. def report_index_download(self, episode_id):
  1798. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1799. def report_player_url(self, episode_id):
  1800. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  1801. def _real_extract(self, url):
  1802. mobj = re.match(self._VALID_URL, url)
  1803. if mobj is None:
  1804. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1805. return
  1806. if mobj.group('shortname'):
  1807. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1808. url = u'http://www.thedailyshow.com/full-episodes/'
  1809. else:
  1810. url = u'http://www.colbertnation.com/full-episodes/'
  1811. mobj = re.match(self._VALID_URL, url)
  1812. assert mobj is not None
  1813. dlNewest = not mobj.group('episode')
  1814. if dlNewest:
  1815. epTitle = mobj.group('showname')
  1816. else:
  1817. epTitle = mobj.group('episode')
  1818. req = urllib2.Request(url)
  1819. self.report_extraction(epTitle)
  1820. try:
  1821. htmlHandle = urllib2.urlopen(req)
  1822. html = htmlHandle.read()
  1823. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1824. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  1825. return
  1826. if dlNewest:
  1827. url = htmlHandle.geturl()
  1828. mobj = re.match(self._VALID_URL, url)
  1829. if mobj is None:
  1830. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  1831. return
  1832. if mobj.group('episode') == '':
  1833. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  1834. return
  1835. epTitle = mobj.group('episode')
  1836. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"', html)
  1837. if len(mMovieParams) == 0:
  1838. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  1839. return
  1840. playerUrl_raw = mMovieParams[0][0]
  1841. self.report_player_url(epTitle)
  1842. try:
  1843. urlHandle = urllib2.urlopen(playerUrl_raw)
  1844. playerUrl = urlHandle.geturl()
  1845. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1846. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + unicode(err))
  1847. return
  1848. uri = mMovieParams[0][1]
  1849. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + urllib.urlencode({'uri': uri})
  1850. self.report_index_download(epTitle)
  1851. try:
  1852. indexXml = urllib2.urlopen(indexUrl).read()
  1853. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1854. self._downloader.trouble(u'ERROR: unable to download episode index: ' + unicode(err))
  1855. return
  1856. results = []
  1857. idoc = xml.etree.ElementTree.fromstring(indexXml)
  1858. itemEls = idoc.findall('.//item')
  1859. for itemEl in itemEls:
  1860. mediaId = itemEl.findall('./guid')[0].text
  1861. shortMediaId = mediaId.split(':')[-1]
  1862. showId = mediaId.split(':')[-2].replace('.com', '')
  1863. officialTitle = itemEl.findall('./title')[0].text
  1864. officialDate = itemEl.findall('./pubDate')[0].text
  1865. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  1866. urllib.urlencode({'uri': mediaId}))
  1867. configReq = urllib2.Request(configUrl)
  1868. self.report_config_download(epTitle)
  1869. try:
  1870. configXml = urllib2.urlopen(configReq).read()
  1871. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1872. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  1873. return
  1874. cdoc = xml.etree.ElementTree.fromstring(configXml)
  1875. turls = []
  1876. for rendition in cdoc.findall('.//rendition'):
  1877. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  1878. turls.append(finfo)
  1879. if len(turls) == 0:
  1880. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  1881. continue
  1882. # For now, just pick the highest bitrate
  1883. format,video_url = turls[-1]
  1884. effTitle = showId + u'-' + epTitle
  1885. info = {
  1886. 'id': shortMediaId,
  1887. 'url': video_url,
  1888. 'uploader': showId,
  1889. 'upload_date': officialDate,
  1890. 'title': effTitle,
  1891. 'ext': 'mp4',
  1892. 'format': format,
  1893. 'thumbnail': None,
  1894. 'description': officialTitle,
  1895. 'player_url': playerUrl
  1896. }
  1897. results.append(info)
  1898. return results
  1899. class EscapistIE(InfoExtractor):
  1900. """Information extractor for The Escapist """
  1901. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  1902. IE_NAME = u'escapist'
  1903. def report_extraction(self, showName):
  1904. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  1905. def report_config_download(self, showName):
  1906. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  1907. def _real_extract(self, url):
  1908. mobj = re.match(self._VALID_URL, url)
  1909. if mobj is None:
  1910. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1911. return
  1912. showName = mobj.group('showname')
  1913. videoId = mobj.group('episode')
  1914. self.report_extraction(showName)
  1915. try:
  1916. webPage = urllib2.urlopen(url)
  1917. webPageBytes = webPage.read()
  1918. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  1919. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  1920. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1921. self._downloader.trouble(u'ERROR: unable to download webpage: ' + unicode(err))
  1922. return
  1923. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  1924. description = unescapeHTML(descMatch.group(1))
  1925. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  1926. imgUrl = unescapeHTML(imgMatch.group(1))
  1927. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  1928. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  1929. configUrlMatch = re.search('config=(.*)$', playerUrl)
  1930. configUrl = urllib2.unquote(configUrlMatch.group(1))
  1931. self.report_config_download(showName)
  1932. try:
  1933. configJSON = urllib2.urlopen(configUrl).read()
  1934. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1935. self._downloader.trouble(u'ERROR: unable to download configuration: ' + unicode(err))
  1936. return
  1937. # Technically, it's JavaScript, not JSON
  1938. configJSON = configJSON.replace("'", '"')
  1939. try:
  1940. config = json.loads(configJSON)
  1941. except (ValueError,), err:
  1942. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + unicode(err))
  1943. return
  1944. playlist = config['playlist']
  1945. videoUrl = playlist[1]['url']
  1946. info = {
  1947. 'id': videoId,
  1948. 'url': videoUrl,
  1949. 'uploader': showName,
  1950. 'upload_date': None,
  1951. 'title': showName,
  1952. 'ext': 'flv',
  1953. 'format': 'flv',
  1954. 'thumbnail': imgUrl,
  1955. 'description': description,
  1956. 'player_url': playerUrl,
  1957. }
  1958. return [info]
  1959. class CollegeHumorIE(InfoExtractor):
  1960. """Information extractor for collegehumor.com"""
  1961. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  1962. IE_NAME = u'collegehumor'
  1963. def report_webpage(self, video_id):
  1964. """Report information extraction."""
  1965. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  1966. def report_extraction(self, video_id):
  1967. """Report information extraction."""
  1968. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  1969. def _real_extract(self, url):
  1970. mobj = re.match(self._VALID_URL, url)
  1971. if mobj is None:
  1972. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1973. return
  1974. video_id = mobj.group('videoid')
  1975. self.report_webpage(video_id)
  1976. request = urllib2.Request(url)
  1977. try:
  1978. webpage = urllib2.urlopen(request).read()
  1979. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1980. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  1981. return
  1982. m = re.search(r'id="video:(?P<internalvideoid>[0-9]+)"', webpage)
  1983. if m is None:
  1984. self._downloader.trouble(u'ERROR: Cannot extract internal video ID')
  1985. return
  1986. internal_video_id = m.group('internalvideoid')
  1987. info = {
  1988. 'id': video_id,
  1989. 'internal_id': internal_video_id,
  1990. }
  1991. self.report_extraction(video_id)
  1992. xmlUrl = 'http://www.collegehumor.com/moogaloop/video:' + internal_video_id
  1993. try:
  1994. metaXml = urllib2.urlopen(xmlUrl).read()
  1995. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1996. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % str(err))
  1997. return
  1998. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  1999. try:
  2000. videoNode = mdoc.findall('./video')[0]
  2001. info['description'] = videoNode.findall('./description')[0].text
  2002. info['title'] = videoNode.findall('./caption')[0].text
  2003. info['url'] = videoNode.findall('./file')[0].text
  2004. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2005. info['ext'] = info['url'].rpartition('.')[2]
  2006. info['format'] = info['ext']
  2007. except IndexError:
  2008. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2009. return
  2010. return [info]
  2011. class XVideosIE(InfoExtractor):
  2012. """Information extractor for xvideos.com"""
  2013. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2014. IE_NAME = u'xvideos'
  2015. def report_webpage(self, video_id):
  2016. """Report information extraction."""
  2017. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2018. def report_extraction(self, video_id):
  2019. """Report information extraction."""
  2020. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2021. def _real_extract(self, url):
  2022. mobj = re.match(self._VALID_URL, url)
  2023. if mobj is None:
  2024. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2025. return
  2026. video_id = mobj.group(1).decode('utf-8')
  2027. self.report_webpage(video_id)
  2028. request = urllib2.Request(r'http://www.xvideos.com/video' + video_id)
  2029. try:
  2030. webpage = urllib2.urlopen(request).read()
  2031. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2032. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2033. return
  2034. self.report_extraction(video_id)
  2035. # Extract video URL
  2036. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2037. if mobj is None:
  2038. self._downloader.trouble(u'ERROR: unable to extract video url')
  2039. return
  2040. video_url = urllib2.unquote(mobj.group(1).decode('utf-8'))
  2041. # Extract title
  2042. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2043. if mobj is None:
  2044. self._downloader.trouble(u'ERROR: unable to extract video title')
  2045. return
  2046. video_title = mobj.group(1).decode('utf-8')
  2047. # Extract video thumbnail
  2048. mobj = re.search(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/([a-fA-F0-9.]+jpg)', webpage)
  2049. if mobj is None:
  2050. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2051. return
  2052. video_thumbnail = mobj.group(0).decode('utf-8')
  2053. info = {
  2054. 'id': video_id,
  2055. 'url': video_url,
  2056. 'uploader': None,
  2057. 'upload_date': None,
  2058. 'title': video_title,
  2059. 'ext': 'flv',
  2060. 'format': 'flv',
  2061. 'thumbnail': video_thumbnail,
  2062. 'description': None,
  2063. 'player_url': None,
  2064. }
  2065. return [info]
  2066. class SoundcloudIE(InfoExtractor):
  2067. """Information extractor for soundcloud.com
  2068. To access the media, the uid of the song and a stream token
  2069. must be extracted from the page source and the script must make
  2070. a request to media.soundcloud.com/crossdomain.xml. Then
  2071. the media can be grabbed by requesting from an url composed
  2072. of the stream token and uid
  2073. """
  2074. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2075. IE_NAME = u'soundcloud'
  2076. def __init__(self, downloader=None):
  2077. InfoExtractor.__init__(self, downloader)
  2078. def report_webpage(self, video_id):
  2079. """Report information extraction."""
  2080. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2081. def report_extraction(self, video_id):
  2082. """Report information extraction."""
  2083. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2084. def _real_extract(self, url):
  2085. mobj = re.match(self._VALID_URL, url)
  2086. if mobj is None:
  2087. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2088. return
  2089. # extract uploader (which is in the url)
  2090. uploader = mobj.group(1).decode('utf-8')
  2091. # extract simple title (uploader + slug of song title)
  2092. slug_title = mobj.group(2).decode('utf-8')
  2093. simple_title = uploader + u'-' + slug_title
  2094. self.report_webpage('%s/%s' % (uploader, slug_title))
  2095. request = urllib2.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  2096. try:
  2097. webpage = urllib2.urlopen(request).read()
  2098. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2099. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2100. return
  2101. self.report_extraction('%s/%s' % (uploader, slug_title))
  2102. # extract uid and stream token that soundcloud hands out for access
  2103. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  2104. if mobj:
  2105. video_id = mobj.group(1)
  2106. stream_token = mobj.group(2)
  2107. # extract unsimplified title
  2108. mobj = re.search('"title":"(.*?)",', webpage)
  2109. if mobj:
  2110. title = mobj.group(1).decode('utf-8')
  2111. else:
  2112. title = simple_title
  2113. # construct media url (with uid/token)
  2114. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  2115. mediaURL = mediaURL % (video_id, stream_token)
  2116. # description
  2117. description = u'No description available'
  2118. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  2119. if mobj:
  2120. description = mobj.group(1)
  2121. # upload date
  2122. upload_date = None
  2123. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  2124. if mobj:
  2125. try:
  2126. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  2127. except Exception, e:
  2128. self._downloader.to_stderr(str(e))
  2129. # for soundcloud, a request to a cross domain is required for cookies
  2130. request = urllib2.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  2131. return [{
  2132. 'id': video_id.decode('utf-8'),
  2133. 'url': mediaURL,
  2134. 'uploader': uploader.decode('utf-8'),
  2135. 'upload_date': upload_date,
  2136. 'title': title,
  2137. 'ext': u'mp3',
  2138. 'format': u'NA',
  2139. 'player_url': None,
  2140. 'description': description.decode('utf-8')
  2141. }]
  2142. class InfoQIE(InfoExtractor):
  2143. """Information extractor for infoq.com"""
  2144. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2145. IE_NAME = u'infoq'
  2146. def report_webpage(self, video_id):
  2147. """Report information extraction."""
  2148. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2149. def report_extraction(self, video_id):
  2150. """Report information extraction."""
  2151. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2152. def _real_extract(self, url):
  2153. mobj = re.match(self._VALID_URL, url)
  2154. if mobj is None:
  2155. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2156. return
  2157. self.report_webpage(url)
  2158. request = urllib2.Request(url)
  2159. try:
  2160. webpage = urllib2.urlopen(request).read()
  2161. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2162. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2163. return
  2164. self.report_extraction(url)
  2165. # Extract video URL
  2166. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2167. if mobj is None:
  2168. self._downloader.trouble(u'ERROR: unable to extract video url')
  2169. return
  2170. video_url = 'rtmpe://video.infoq.com/cfx/st/' + urllib2.unquote(mobj.group(1).decode('base64'))
  2171. # Extract title
  2172. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2173. if mobj is None:
  2174. self._downloader.trouble(u'ERROR: unable to extract video title')
  2175. return
  2176. video_title = mobj.group(1).decode('utf-8')
  2177. # Extract description
  2178. video_description = u'No description available.'
  2179. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2180. if mobj is not None:
  2181. video_description = mobj.group(1).decode('utf-8')
  2182. video_filename = video_url.split('/')[-1]
  2183. video_id, extension = video_filename.split('.')
  2184. info = {
  2185. 'id': video_id,
  2186. 'url': video_url,
  2187. 'uploader': None,
  2188. 'upload_date': None,
  2189. 'title': video_title,
  2190. 'ext': extension,
  2191. 'format': extension, # Extension is always(?) mp4, but seems to be flv
  2192. 'thumbnail': None,
  2193. 'description': video_description,
  2194. 'player_url': None,
  2195. }
  2196. return [info]
  2197. class MixcloudIE(InfoExtractor):
  2198. """Information extractor for www.mixcloud.com"""
  2199. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2200. IE_NAME = u'mixcloud'
  2201. def __init__(self, downloader=None):
  2202. InfoExtractor.__init__(self, downloader)
  2203. def report_download_json(self, file_id):
  2204. """Report JSON download."""
  2205. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2206. def report_extraction(self, file_id):
  2207. """Report information extraction."""
  2208. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2209. def get_urls(self, jsonData, fmt, bitrate='best'):
  2210. """Get urls from 'audio_formats' section in json"""
  2211. file_url = None
  2212. try:
  2213. bitrate_list = jsonData[fmt]
  2214. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2215. bitrate = max(bitrate_list) # select highest
  2216. url_list = jsonData[fmt][bitrate]
  2217. except TypeError: # we have no bitrate info.
  2218. url_list = jsonData[fmt]
  2219. return url_list
  2220. def check_urls(self, url_list):
  2221. """Returns 1st active url from list"""
  2222. for url in url_list:
  2223. try:
  2224. urllib2.urlopen(url)
  2225. return url
  2226. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2227. url = None
  2228. return None
  2229. def _print_formats(self, formats):
  2230. print 'Available formats:'
  2231. for fmt in formats.keys():
  2232. for b in formats[fmt]:
  2233. try:
  2234. ext = formats[fmt][b][0]
  2235. print '%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1])
  2236. except TypeError: # we have no bitrate info
  2237. ext = formats[fmt][0]
  2238. print '%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1])
  2239. break
  2240. def _real_extract(self, url):
  2241. mobj = re.match(self._VALID_URL, url)
  2242. if mobj is None:
  2243. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2244. return
  2245. # extract uploader & filename from url
  2246. uploader = mobj.group(1).decode('utf-8')
  2247. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2248. # construct API request
  2249. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2250. # retrieve .json file with links to files
  2251. request = urllib2.Request(file_url)
  2252. try:
  2253. self.report_download_json(file_url)
  2254. jsonData = urllib2.urlopen(request).read()
  2255. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2256. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % str(err))
  2257. return
  2258. # parse JSON
  2259. json_data = json.loads(jsonData)
  2260. player_url = json_data['player_swf_url']
  2261. formats = dict(json_data['audio_formats'])
  2262. req_format = self._downloader.params.get('format', None)
  2263. bitrate = None
  2264. if self._downloader.params.get('listformats', None):
  2265. self._print_formats(formats)
  2266. return
  2267. if req_format is None or req_format == 'best':
  2268. for format_param in formats.keys():
  2269. url_list = self.get_urls(formats, format_param)
  2270. # check urls
  2271. file_url = self.check_urls(url_list)
  2272. if file_url is not None:
  2273. break # got it!
  2274. else:
  2275. if req_format not in formats.keys():
  2276. self._downloader.trouble(u'ERROR: format is not available')
  2277. return
  2278. url_list = self.get_urls(formats, req_format)
  2279. file_url = self.check_urls(url_list)
  2280. format_param = req_format
  2281. return [{
  2282. 'id': file_id.decode('utf-8'),
  2283. 'url': file_url.decode('utf-8'),
  2284. 'uploader': uploader.decode('utf-8'),
  2285. 'upload_date': u'NA',
  2286. 'title': json_data['name'],
  2287. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2288. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2289. 'thumbnail': json_data['thumbnail_url'],
  2290. 'description': json_data['description'],
  2291. 'player_url': player_url.decode('utf-8'),
  2292. }]
  2293. class StanfordOpenClassroomIE(InfoExtractor):
  2294. """Information extractor for Stanford's Open ClassRoom"""
  2295. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2296. IE_NAME = u'stanfordoc'
  2297. def report_download_webpage(self, objid):
  2298. """Report information extraction."""
  2299. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2300. def report_extraction(self, video_id):
  2301. """Report information extraction."""
  2302. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2303. def _real_extract(self, url):
  2304. mobj = re.match(self._VALID_URL, url)
  2305. if mobj is None:
  2306. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2307. return
  2308. if mobj.group('course') and mobj.group('video'): # A specific video
  2309. course = mobj.group('course')
  2310. video = mobj.group('video')
  2311. info = {
  2312. 'id': course + '_' + video,
  2313. }
  2314. self.report_extraction(info['id'])
  2315. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2316. xmlUrl = baseUrl + video + '.xml'
  2317. try:
  2318. metaXml = urllib2.urlopen(xmlUrl).read()
  2319. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2320. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % unicode(err))
  2321. return
  2322. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2323. try:
  2324. info['title'] = mdoc.findall('./title')[0].text
  2325. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2326. except IndexError:
  2327. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2328. return
  2329. info['ext'] = info['url'].rpartition('.')[2]
  2330. info['format'] = info['ext']
  2331. return [info]
  2332. elif mobj.group('course'): # A course page
  2333. course = mobj.group('course')
  2334. info = {
  2335. 'id': course,
  2336. 'type': 'playlist',
  2337. }
  2338. self.report_download_webpage(info['id'])
  2339. try:
  2340. coursepage = urllib2.urlopen(url).read()
  2341. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2342. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  2343. return
  2344. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2345. if m:
  2346. info['title'] = unescapeHTML(m.group(1))
  2347. else:
  2348. info['title'] = info['id']
  2349. m = re.search('<description>([^<]+)</description>', coursepage)
  2350. if m:
  2351. info['description'] = unescapeHTML(m.group(1))
  2352. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2353. info['list'] = [
  2354. {
  2355. 'type': 'reference',
  2356. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2357. }
  2358. for vpage in links]
  2359. results = []
  2360. for entry in info['list']:
  2361. assert entry['type'] == 'reference'
  2362. results += self.extract(entry['url'])
  2363. return results
  2364. else: # Root page
  2365. info = {
  2366. 'id': 'Stanford OpenClassroom',
  2367. 'type': 'playlist',
  2368. }
  2369. self.report_download_webpage(info['id'])
  2370. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2371. try:
  2372. rootpage = urllib2.urlopen(rootURL).read()
  2373. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2374. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  2375. return
  2376. info['title'] = info['id']
  2377. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2378. info['list'] = [
  2379. {
  2380. 'type': 'reference',
  2381. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2382. }
  2383. for cpage in links]
  2384. results = []
  2385. for entry in info['list']:
  2386. assert entry['type'] == 'reference'
  2387. results += self.extract(entry['url'])
  2388. return results
  2389. class MTVIE(InfoExtractor):
  2390. """Information extractor for MTV.com"""
  2391. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2392. IE_NAME = u'mtv'
  2393. def report_webpage(self, video_id):
  2394. """Report information extraction."""
  2395. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2396. def report_extraction(self, video_id):
  2397. """Report information extraction."""
  2398. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2399. def _real_extract(self, url):
  2400. mobj = re.match(self._VALID_URL, url)
  2401. if mobj is None:
  2402. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2403. return
  2404. if not mobj.group('proto'):
  2405. url = 'http://' + url
  2406. video_id = mobj.group('videoid')
  2407. self.report_webpage(video_id)
  2408. request = urllib2.Request(url)
  2409. try:
  2410. webpage = urllib2.urlopen(request).read()
  2411. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2412. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2413. return
  2414. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2415. if mobj is None:
  2416. self._downloader.trouble(u'ERROR: unable to extract song name')
  2417. return
  2418. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2419. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2420. if mobj is None:
  2421. self._downloader.trouble(u'ERROR: unable to extract performer')
  2422. return
  2423. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2424. video_title = performer + ' - ' + song_name
  2425. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2426. if mobj is None:
  2427. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2428. return
  2429. mtvn_uri = mobj.group(1)
  2430. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2431. if mobj is None:
  2432. self._downloader.trouble(u'ERROR: unable to extract content id')
  2433. return
  2434. content_id = mobj.group(1)
  2435. videogen_url = 'http://www.mtv.com/player/includes/mediaGen.jhtml?uri=' + mtvn_uri + '&id=' + content_id + '&vid=' + video_id + '&ref=www.mtvn.com&viewUri=' + mtvn_uri
  2436. self.report_extraction(video_id)
  2437. request = urllib2.Request(videogen_url)
  2438. try:
  2439. metadataXml = urllib2.urlopen(request).read()
  2440. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2441. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % str(err))
  2442. return
  2443. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2444. renditions = mdoc.findall('.//rendition')
  2445. # For now, always pick the highest quality.
  2446. rendition = renditions[-1]
  2447. try:
  2448. _,_,ext = rendition.attrib['type'].partition('/')
  2449. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2450. video_url = rendition.find('./src').text
  2451. except KeyError:
  2452. self._downloader.trouble('Invalid rendition field.')
  2453. return
  2454. info = {
  2455. 'id': video_id,
  2456. 'url': video_url,
  2457. 'uploader': performer,
  2458. 'title': video_title,
  2459. 'ext': ext,
  2460. 'format': format,
  2461. }
  2462. return [info]
  2463. class YoukuIE(InfoExtractor):
  2464. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2465. IE_NAME = u'Youku'
  2466. def __init__(self, downloader=None):
  2467. InfoExtractor.__init__(self, downloader)
  2468. def report_download_webpage(self, file_id):
  2469. """Report webpage download."""
  2470. self._downloader.to_screen(u'[Youku] %s: Downloading webpage' % file_id)
  2471. def report_extraction(self, file_id):
  2472. """Report information extraction."""
  2473. self._downloader.to_screen(u'[Youku] %s: Extracting information' % file_id)
  2474. def _gen_sid(self):
  2475. nowTime = int(time.time() * 1000)
  2476. random1 = random.randint(1000,1998)
  2477. random2 = random.randint(1000,9999)
  2478. return "%d%d%d" %(nowTime,random1,random2)
  2479. def _get_file_ID_mix_string(self, seed):
  2480. mixed = []
  2481. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2482. seed = float(seed)
  2483. for i in range(len(source)):
  2484. seed = (seed * 211 + 30031 ) % 65536
  2485. index = math.floor(seed / 65536 * len(source) )
  2486. mixed.append(source[int(index)])
  2487. source.remove(source[int(index)])
  2488. #return ''.join(mixed)
  2489. return mixed
  2490. def _get_file_id(self, fileId, seed):
  2491. mixed = self._get_file_ID_mix_string(seed)
  2492. ids = fileId.split('*')
  2493. realId = []
  2494. for ch in ids:
  2495. if ch:
  2496. realId.append(mixed[int(ch)])
  2497. return ''.join(realId)
  2498. def _real_extract(self, url):
  2499. mobj = re.match(self._VALID_URL, url)
  2500. if mobj is None:
  2501. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2502. return
  2503. video_id = mobj.group('ID')
  2504. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2505. request = urllib2.Request(info_url, None, std_headers)
  2506. try:
  2507. self.report_download_webpage(video_id)
  2508. jsondata = urllib2.urlopen(request).read()
  2509. except (urllib2.URLError, httplib.HTTPException, socket.error) as err:
  2510. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  2511. return
  2512. self.report_extraction(video_id)
  2513. try:
  2514. config = json.loads(jsondata)
  2515. video_title = config['data'][0]['title']
  2516. seed = config['data'][0]['seed']
  2517. format = self._downloader.params.get('format', None)
  2518. supported_format = config['data'][0]['streamfileids'].keys()
  2519. if format is None or format == 'best':
  2520. if 'hd2' in supported_format:
  2521. format = 'hd2'
  2522. else:
  2523. format = 'flv'
  2524. ext = u'flv'
  2525. elif format == 'worst':
  2526. format = 'mp4'
  2527. ext = u'mp4'
  2528. else:
  2529. format = 'flv'
  2530. ext = u'flv'
  2531. fileid = config['data'][0]['streamfileids'][format]
  2532. seg_number = len(config['data'][0]['segs'][format])
  2533. keys=[]
  2534. for i in xrange(seg_number):
  2535. keys.append(config['data'][0]['segs'][format][i]['k'])
  2536. #TODO check error
  2537. #youku only could be viewed from mainland china
  2538. except:
  2539. self._downloader.trouble(u'ERROR: unable to extract info section')
  2540. return
  2541. files_info=[]
  2542. sid = self._gen_sid()
  2543. fileid = self._get_file_id(fileid, seed)
  2544. #column 8,9 of fileid represent the segment number
  2545. #fileid[7:9] should be changed
  2546. for index, key in enumerate(keys):
  2547. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2548. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2549. info = {
  2550. 'id': '%s_part%02d' % (video_id, index),
  2551. 'url': download_url,
  2552. 'uploader': None,
  2553. 'title': video_title,
  2554. 'ext': ext,
  2555. 'format': u'NA'
  2556. }
  2557. files_info.append(info)
  2558. return files_info
  2559. class XNXXIE(InfoExtractor):
  2560. """Information extractor for xnxx.com"""
  2561. _VALID_URL = r'^http://video\.xnxx\.com/video([0-9]+)/(.*)'
  2562. IE_NAME = u'xnxx'
  2563. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2564. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2565. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2566. def report_webpage(self, video_id):
  2567. """Report information extraction"""
  2568. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2569. def report_extraction(self, video_id):
  2570. """Report information extraction"""
  2571. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2572. def _real_extract(self, url):
  2573. mobj = re.match(self._VALID_URL, url)
  2574. if mobj is None:
  2575. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2576. return
  2577. video_id = mobj.group(1).decode('utf-8')
  2578. self.report_webpage(video_id)
  2579. # Get webpage content
  2580. try:
  2581. webpage = urllib2.urlopen(url).read()
  2582. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2583. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2584. return
  2585. result = re.search(self.VIDEO_URL_RE, webpage)
  2586. if result is None:
  2587. self._downloader.trouble(u'ERROR: unable to extract video url')
  2588. return
  2589. video_url = urllib.unquote(result.group(1).decode('utf-8'))
  2590. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2591. if result is None:
  2592. self._downloader.trouble(u'ERROR: unable to extract video title')
  2593. return
  2594. video_title = result.group(1).decode('utf-8')
  2595. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2596. if result is None:
  2597. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2598. return
  2599. video_thumbnail = result.group(1).decode('utf-8')
  2600. info = {'id': video_id,
  2601. 'url': video_url,
  2602. 'uploader': None,
  2603. 'upload_date': None,
  2604. 'title': video_title,
  2605. 'ext': 'flv',
  2606. 'format': 'flv',
  2607. 'thumbnail': video_thumbnail,
  2608. 'description': None,
  2609. 'player_url': None}
  2610. return [info]