InfoExtractors.py 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import datetime
  5. import netrc
  6. import os
  7. import re
  8. import socket
  9. import time
  10. import email.utils
  11. import xml.etree.ElementTree
  12. import random
  13. import math
  14. from .utils import *
  15. class InfoExtractor(object):
  16. """Information Extractor class.
  17. Information extractors are the classes that, given a URL, extract
  18. information about the video (or videos) the URL refers to. This
  19. information includes the real video URL, the video title, author and
  20. others. The information is stored in a dictionary which is then
  21. passed to the FileDownloader. The FileDownloader processes this
  22. information possibly downloading the video to the file system, among
  23. other possible outcomes.
  24. The dictionaries must include the following fields:
  25. id: Video identifier.
  26. url: Final video URL.
  27. title: Video title, unescaped.
  28. ext: Video filename extension.
  29. uploader: Full name of the video uploader.
  30. upload_date: Video upload date (YYYYMMDD).
  31. The following fields are optional:
  32. format: The video format, defaults to ext (used for --get-format)
  33. thumbnail: Full URL to a video thumbnail image.
  34. description: One-line video description.
  35. uploader_id: Nickname or id of the video uploader.
  36. player_url: SWF Player URL (used for rtmpdump).
  37. subtitles: The .srt file contents.
  38. urlhandle: [internal] The urlHandle to be used to download the file,
  39. like returned by urllib.request.urlopen
  40. The fields should all be Unicode strings.
  41. Subclasses of this one should re-define the _real_initialize() and
  42. _real_extract() methods and define a _VALID_URL regexp.
  43. Probably, they should also be added to the list of extractors.
  44. _real_extract() must return a *list* of information dictionaries as
  45. described above.
  46. Finally, the _WORKING attribute should be set to False for broken IEs
  47. in order to warn the users and skip the tests.
  48. """
  49. _ready = False
  50. _downloader = None
  51. _WORKING = True
  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 working(self):
  60. """Getter method for _WORKING."""
  61. return self._WORKING
  62. def initialize(self):
  63. """Initializes an instance (authentication, etc)."""
  64. if not self._ready:
  65. self._real_initialize()
  66. self._ready = True
  67. def extract(self, url):
  68. """Extracts URL information and returns it in list of dicts."""
  69. self.initialize()
  70. return self._real_extract(url)
  71. def set_downloader(self, downloader):
  72. """Sets the downloader for this IE."""
  73. self._downloader = downloader
  74. def _real_initialize(self):
  75. """Real initialization process. Redefine in subclasses."""
  76. pass
  77. def _real_extract(self, url):
  78. """Real extraction process. Redefine in subclasses."""
  79. pass
  80. @property
  81. def IE_NAME(self):
  82. return type(self).__name__[:-2]
  83. class YoutubeIE(InfoExtractor):
  84. """Information extractor for youtube.com."""
  85. _VALID_URL = r"""^
  86. (
  87. (?:https?://)? # http(s):// (optional)
  88. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  89. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  90. (?:.*?\#/)? # handle anchor (#/) redirect urls
  91. (?!view_play_list|my_playlists|artist|playlist) # ignore playlist URLs
  92. (?: # the various things that can precede the ID:
  93. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  94. |(?: # or the v= param in all its forms
  95. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  96. (?:\?|\#!?) # the params delimiter ? or # or #!
  97. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  98. v=
  99. )
  100. )? # optional -> youtube.com/xxxx is OK
  101. )? # all until now is optional -> you can pass the naked ID
  102. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  103. (?(1).+)? # if we found the ID, everything can follow
  104. $"""
  105. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  106. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  107. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  108. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  109. _NETRC_MACHINE = 'youtube'
  110. # Listed in order of quality
  111. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  112. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  113. _video_extensions = {
  114. '13': '3gp',
  115. '17': 'mp4',
  116. '18': 'mp4',
  117. '22': 'mp4',
  118. '37': 'mp4',
  119. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  120. '43': 'webm',
  121. '44': 'webm',
  122. '45': 'webm',
  123. '46': 'webm',
  124. }
  125. _video_dimensions = {
  126. '5': '240x400',
  127. '6': '???',
  128. '13': '???',
  129. '17': '144x176',
  130. '18': '360x640',
  131. '22': '720x1280',
  132. '34': '360x640',
  133. '35': '480x854',
  134. '37': '1080x1920',
  135. '38': '3072x4096',
  136. '43': '360x640',
  137. '44': '480x854',
  138. '45': '720x1280',
  139. '46': '1080x1920',
  140. }
  141. IE_NAME = u'youtube'
  142. def suitable(self, url):
  143. """Receives a URL and returns True if suitable for this IE."""
  144. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  145. def report_lang(self):
  146. """Report attempt to set language."""
  147. self._downloader.to_screen(u'[youtube] Setting language')
  148. def report_login(self):
  149. """Report attempt to log in."""
  150. self._downloader.to_screen(u'[youtube] Logging in')
  151. def report_age_confirmation(self):
  152. """Report attempt to confirm age."""
  153. self._downloader.to_screen(u'[youtube] Confirming age')
  154. def report_video_webpage_download(self, video_id):
  155. """Report attempt to download video webpage."""
  156. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  157. def report_video_info_webpage_download(self, video_id):
  158. """Report attempt to download video info webpage."""
  159. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  160. def report_video_subtitles_download(self, video_id):
  161. """Report attempt to download video info webpage."""
  162. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  163. def report_information_extraction(self, video_id):
  164. """Report attempt to extract video information."""
  165. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  166. def report_unavailable_format(self, video_id, format):
  167. """Report extracted video URL."""
  168. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  169. def report_rtmp_download(self):
  170. """Indicate the download will use the RTMP protocol."""
  171. self._downloader.to_screen(u'[youtube] RTMP download detected')
  172. def _closed_captions_xml_to_srt(self, xml_string):
  173. srt = ''
  174. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  175. # TODO parse xml instead of regex
  176. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  177. if not dur: dur = '4'
  178. start = float(start)
  179. end = start + float(dur)
  180. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  181. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  182. caption = unescapeHTML(caption)
  183. caption = unescapeHTML(caption) # double cycle, intentional
  184. srt += str(n+1) + '\n'
  185. srt += start + ' --> ' + end + '\n'
  186. srt += caption + '\n\n'
  187. return srt
  188. def _extract_subtitles(self, video_id):
  189. self.report_video_subtitles_download(video_id)
  190. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  191. try:
  192. srt_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  193. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  194. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  195. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  196. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  197. if not srt_lang_list:
  198. return (u'WARNING: video has no closed captions', None)
  199. if self._downloader.params.get('subtitleslang', False):
  200. srt_lang = self._downloader.params.get('subtitleslang')
  201. elif 'en' in srt_lang_list:
  202. srt_lang = 'en'
  203. else:
  204. srt_lang = list(srt_lang_list.keys())[0]
  205. if not srt_lang in srt_lang_list:
  206. return (u'WARNING: no closed captions found in the specified language', None)
  207. request = compat_urllib_request.Request('http://www.youtube.com/api/timedtext?lang=%s&name=%s&v=%s' % (srt_lang, srt_lang_list[srt_lang], video_id))
  208. try:
  209. srt_xml = compat_urllib_request.urlopen(request).read().decode('utf-8')
  210. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  211. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  212. if not srt_xml:
  213. return (u'WARNING: unable to download video subtitles', None)
  214. return (None, self._closed_captions_xml_to_srt(srt_xml))
  215. def _print_formats(self, formats):
  216. print('Available formats:')
  217. for x in formats:
  218. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  219. def _real_initialize(self):
  220. if self._downloader is None:
  221. return
  222. username = None
  223. password = None
  224. downloader_params = self._downloader.params
  225. # Attempt to use provided username and password or .netrc data
  226. if downloader_params.get('username', None) is not None:
  227. username = downloader_params['username']
  228. password = downloader_params['password']
  229. elif downloader_params.get('usenetrc', False):
  230. try:
  231. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  232. if info is not None:
  233. username = info[0]
  234. password = info[2]
  235. else:
  236. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  237. except (IOError, netrc.NetrcParseError) as err:
  238. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  239. return
  240. # Set language
  241. request = compat_urllib_request.Request(self._LANG_URL)
  242. try:
  243. self.report_lang()
  244. compat_urllib_request.urlopen(request).read()
  245. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  246. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % compat_str(err))
  247. return
  248. # No authentication to be performed
  249. if username is None:
  250. return
  251. # Log in
  252. login_form = {
  253. 'current_form': 'loginForm',
  254. 'next': '/',
  255. 'action_login': 'Log In',
  256. 'username': username,
  257. 'password': password,
  258. }
  259. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  260. try:
  261. self.report_login()
  262. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  263. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  264. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  265. return
  266. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  267. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  268. return
  269. # Confirm age
  270. age_form = {
  271. 'next_url': '/',
  272. 'action_confirm': 'Confirm',
  273. }
  274. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  275. try:
  276. self.report_age_confirmation()
  277. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  278. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  279. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  280. return
  281. def _extract_id(self, url):
  282. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  283. if mobj is None:
  284. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  285. return
  286. video_id = mobj.group(2)
  287. return video_id
  288. def _real_extract(self, url):
  289. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  290. mobj = re.search(self._NEXT_URL_RE, url)
  291. if mobj:
  292. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  293. video_id = self._extract_id(url)
  294. # Get video webpage
  295. self.report_video_webpage_download(video_id)
  296. url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  297. request = compat_urllib_request.Request(url)
  298. try:
  299. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  300. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  301. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  302. return
  303. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  304. # Attempt to extract SWF player URL
  305. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  306. if mobj is not None:
  307. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  308. else:
  309. player_url = None
  310. # Get video info
  311. self.report_video_info_webpage_download(video_id)
  312. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  313. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  314. % (video_id, el_type))
  315. request = compat_urllib_request.Request(video_info_url)
  316. try:
  317. video_info_webpage_bytes = compat_urllib_request.urlopen(request).read()
  318. video_info_webpage = video_info_webpage_bytes.decode('utf-8', 'ignore')
  319. video_info = compat_parse_qs(video_info_webpage)
  320. if 'token' in video_info:
  321. break
  322. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  323. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  324. return
  325. if 'token' not in video_info:
  326. if 'reason' in video_info:
  327. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0])
  328. else:
  329. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  330. return
  331. # Check for "rental" videos
  332. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  333. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  334. return
  335. # Start extracting information
  336. self.report_information_extraction(video_id)
  337. # uploader
  338. if 'author' not in video_info:
  339. self._downloader.trouble(u'ERROR: unable to extract uploader name')
  340. return
  341. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  342. # uploader_id
  343. video_uploader_id = None
  344. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/user/([^"]+)">', video_webpage)
  345. if mobj is not None:
  346. video_uploader_id = mobj.group(1)
  347. else:
  348. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  349. # title
  350. if 'title' not in video_info:
  351. self._downloader.trouble(u'ERROR: unable to extract video title')
  352. return
  353. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  354. # thumbnail image
  355. if 'thumbnail_url' not in video_info:
  356. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  357. video_thumbnail = ''
  358. else: # don't panic if we can't find it
  359. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  360. # upload date
  361. upload_date = None
  362. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  363. if mobj is not None:
  364. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  365. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  366. for expression in format_expressions:
  367. try:
  368. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  369. except:
  370. pass
  371. # description
  372. video_description = get_element_by_id("eow-description", video_webpage)
  373. if video_description:
  374. video_description = clean_html(video_description)
  375. else:
  376. video_description = ''
  377. # closed captions
  378. video_subtitles = None
  379. if self._downloader.params.get('writesubtitles', False):
  380. (srt_error, video_subtitles) = self._extract_subtitles(video_id)
  381. if srt_error:
  382. self._downloader.trouble(srt_error)
  383. if 'length_seconds' not in video_info:
  384. self._downloader.trouble(u'WARNING: unable to extract video duration')
  385. video_duration = ''
  386. else:
  387. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  388. # token
  389. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  390. # Decide which formats to download
  391. req_format = self._downloader.params.get('format', None)
  392. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  393. self.report_rtmp_download()
  394. video_url_list = [(None, video_info['conn'][0])]
  395. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  396. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  397. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  398. url_data = [ud for ud in url_data if 'itag' in ud and 'url' in ud]
  399. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  400. format_limit = self._downloader.params.get('format_limit', None)
  401. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  402. if format_limit is not None and format_limit in available_formats:
  403. format_list = available_formats[available_formats.index(format_limit):]
  404. else:
  405. format_list = available_formats
  406. existing_formats = [x for x in format_list if x in url_map]
  407. if len(existing_formats) == 0:
  408. self._downloader.trouble(u'ERROR: no known formats available for video')
  409. return
  410. if self._downloader.params.get('listformats', None):
  411. self._print_formats(existing_formats)
  412. return
  413. if req_format is None or req_format == 'best':
  414. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  415. elif req_format == 'worst':
  416. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  417. elif req_format in ('-1', 'all'):
  418. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  419. else:
  420. # Specific formats. We pick the first in a slash-delimeted sequence.
  421. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  422. req_formats = req_format.split('/')
  423. video_url_list = None
  424. for rf in req_formats:
  425. if rf in url_map:
  426. video_url_list = [(rf, url_map[rf])]
  427. break
  428. if video_url_list is None:
  429. self._downloader.trouble(u'ERROR: requested format not available')
  430. return
  431. else:
  432. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  433. return
  434. results = []
  435. for format_param, video_real_url in video_url_list:
  436. # Extension
  437. video_extension = self._video_extensions.get(format_param, 'flv')
  438. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  439. self._video_dimensions.get(format_param, '???'))
  440. results.append({
  441. 'id': video_id,
  442. 'url': video_real_url,
  443. 'uploader': video_uploader,
  444. 'uploader_id': video_uploader_id,
  445. 'upload_date': upload_date,
  446. 'title': video_title,
  447. 'ext': video_extension,
  448. 'format': video_format,
  449. 'thumbnail': video_thumbnail,
  450. 'description': video_description,
  451. 'player_url': player_url,
  452. 'subtitles': video_subtitles,
  453. 'duration': video_duration
  454. })
  455. return results
  456. class MetacafeIE(InfoExtractor):
  457. """Information Extractor for metacafe.com."""
  458. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  459. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  460. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  461. IE_NAME = u'metacafe'
  462. def __init__(self, downloader=None):
  463. InfoExtractor.__init__(self, downloader)
  464. def report_disclaimer(self):
  465. """Report disclaimer retrieval."""
  466. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  467. def report_age_confirmation(self):
  468. """Report attempt to confirm age."""
  469. self._downloader.to_screen(u'[metacafe] Confirming age')
  470. def report_download_webpage(self, video_id):
  471. """Report webpage download."""
  472. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  473. def report_extraction(self, video_id):
  474. """Report information extraction."""
  475. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  476. def _real_initialize(self):
  477. # Retrieve disclaimer
  478. request = compat_urllib_request.Request(self._DISCLAIMER)
  479. try:
  480. self.report_disclaimer()
  481. disclaimer = compat_urllib_request.urlopen(request).read()
  482. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  483. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % compat_str(err))
  484. return
  485. # Confirm age
  486. disclaimer_form = {
  487. 'filters': '0',
  488. 'submit': "Continue - I'm over 18",
  489. }
  490. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  491. try:
  492. self.report_age_confirmation()
  493. disclaimer = compat_urllib_request.urlopen(request).read()
  494. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  495. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  496. return
  497. def _real_extract(self, url):
  498. # Extract id and simplified title from URL
  499. mobj = re.match(self._VALID_URL, url)
  500. if mobj is None:
  501. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  502. return
  503. video_id = mobj.group(1)
  504. # Check if video comes from YouTube
  505. mobj2 = re.match(r'^yt-(.*)$', video_id)
  506. if mobj2 is not None:
  507. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  508. return
  509. # Retrieve video webpage to extract further information
  510. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  511. try:
  512. self.report_download_webpage(video_id)
  513. webpage = compat_urllib_request.urlopen(request).read()
  514. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  515. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  516. return
  517. # Extract URL, uploader and title from webpage
  518. self.report_extraction(video_id)
  519. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  520. if mobj is not None:
  521. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  522. video_extension = mediaURL[-3:]
  523. # Extract gdaKey if available
  524. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  525. if mobj is None:
  526. video_url = mediaURL
  527. else:
  528. gdaKey = mobj.group(1)
  529. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  530. else:
  531. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  532. if mobj is None:
  533. self._downloader.trouble(u'ERROR: unable to extract media URL')
  534. return
  535. vardict = compat_parse_qs(mobj.group(1))
  536. if 'mediaData' not in vardict:
  537. self._downloader.trouble(u'ERROR: unable to extract media URL')
  538. return
  539. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  540. if mobj is None:
  541. self._downloader.trouble(u'ERROR: unable to extract media URL')
  542. return
  543. mediaURL = mobj.group(1).replace('\\/', '/')
  544. video_extension = mediaURL[-3:]
  545. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  546. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  547. if mobj is None:
  548. self._downloader.trouble(u'ERROR: unable to extract title')
  549. return
  550. video_title = mobj.group(1).decode('utf-8')
  551. mobj = re.search(r'submitter=(.*?);', webpage)
  552. if mobj is None:
  553. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  554. return
  555. video_uploader = mobj.group(1)
  556. return [{
  557. 'id': video_id.decode('utf-8'),
  558. 'url': video_url.decode('utf-8'),
  559. 'uploader': video_uploader.decode('utf-8'),
  560. 'upload_date': None,
  561. 'title': video_title,
  562. 'ext': video_extension.decode('utf-8'),
  563. }]
  564. class DailymotionIE(InfoExtractor):
  565. """Information Extractor for Dailymotion"""
  566. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  567. IE_NAME = u'dailymotion'
  568. def __init__(self, downloader=None):
  569. InfoExtractor.__init__(self, downloader)
  570. def report_download_webpage(self, video_id):
  571. """Report webpage download."""
  572. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  573. def report_extraction(self, video_id):
  574. """Report information extraction."""
  575. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  576. def _real_extract(self, url):
  577. # Extract id and simplified title from URL
  578. mobj = re.match(self._VALID_URL, url)
  579. if mobj is None:
  580. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  581. return
  582. video_id = mobj.group(1).split('_')[0].split('?')[0]
  583. video_extension = 'mp4'
  584. # Retrieve video webpage to extract further information
  585. request = compat_urllib_request.Request(url)
  586. request.add_header('Cookie', 'family_filter=off')
  587. try:
  588. self.report_download_webpage(video_id)
  589. webpage_bytes = compat_urllib_request.urlopen(request).read()
  590. webpage = webpage_bytes.decode('utf-8')
  591. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  592. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  593. return
  594. # Extract URL, uploader and title from webpage
  595. self.report_extraction(video_id)
  596. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  597. if mobj is None:
  598. self._downloader.trouble(u'ERROR: unable to extract media URL')
  599. return
  600. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  601. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  602. if key in flashvars:
  603. max_quality = key
  604. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  605. break
  606. else:
  607. self._downloader.trouble(u'ERROR: unable to extract video URL')
  608. return
  609. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  610. if mobj is None:
  611. self._downloader.trouble(u'ERROR: unable to extract video URL')
  612. return
  613. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  614. # TODO: support choosing qualities
  615. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  616. if mobj is None:
  617. self._downloader.trouble(u'ERROR: unable to extract title')
  618. return
  619. video_title = unescapeHTML(mobj.group('title'))
  620. video_uploader = None
  621. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  622. if mobj is None:
  623. # lookin for official user
  624. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  625. if mobj_official is None:
  626. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  627. else:
  628. video_uploader = mobj_official.group(1)
  629. else:
  630. video_uploader = mobj.group(1)
  631. video_upload_date = None
  632. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  633. if mobj is not None:
  634. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  635. return [{
  636. 'id': video_id,
  637. 'url': video_url,
  638. 'uploader': video_uploader,
  639. 'upload_date': video_upload_date,
  640. 'title': video_title,
  641. 'ext': video_extension,
  642. }]
  643. class PhotobucketIE(InfoExtractor):
  644. """Information extractor for photobucket.com."""
  645. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  646. IE_NAME = u'photobucket'
  647. def __init__(self, downloader=None):
  648. InfoExtractor.__init__(self, downloader)
  649. def report_download_webpage(self, video_id):
  650. """Report webpage download."""
  651. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  652. def report_extraction(self, video_id):
  653. """Report information extraction."""
  654. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  655. def _real_extract(self, url):
  656. # Extract id from URL
  657. mobj = re.match(self._VALID_URL, url)
  658. if mobj is None:
  659. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  660. return
  661. video_id = mobj.group(1)
  662. video_extension = 'flv'
  663. # Retrieve video webpage to extract further information
  664. request = compat_urllib_request.Request(url)
  665. try:
  666. self.report_download_webpage(video_id)
  667. webpage = compat_urllib_request.urlopen(request).read()
  668. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  669. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  670. return
  671. # Extract URL, uploader, and title from webpage
  672. self.report_extraction(video_id)
  673. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  674. if mobj is None:
  675. self._downloader.trouble(u'ERROR: unable to extract media URL')
  676. return
  677. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  678. video_url = mediaURL
  679. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  680. if mobj is None:
  681. self._downloader.trouble(u'ERROR: unable to extract title')
  682. return
  683. video_title = mobj.group(1).decode('utf-8')
  684. video_uploader = mobj.group(2).decode('utf-8')
  685. return [{
  686. 'id': video_id.decode('utf-8'),
  687. 'url': video_url.decode('utf-8'),
  688. 'uploader': video_uploader,
  689. 'upload_date': None,
  690. 'title': video_title,
  691. 'ext': video_extension.decode('utf-8'),
  692. }]
  693. class YahooIE(InfoExtractor):
  694. """Information extractor for video.yahoo.com."""
  695. _WORKING = False
  696. # _VALID_URL matches all Yahoo! Video URLs
  697. # _VPAGE_URL matches only the extractable '/watch/' URLs
  698. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  699. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  700. IE_NAME = u'video.yahoo'
  701. def __init__(self, downloader=None):
  702. InfoExtractor.__init__(self, downloader)
  703. def report_download_webpage(self, video_id):
  704. """Report webpage download."""
  705. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  706. def report_extraction(self, video_id):
  707. """Report information extraction."""
  708. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  709. def _real_extract(self, url, new_video=True):
  710. # Extract ID from URL
  711. mobj = re.match(self._VALID_URL, url)
  712. if mobj is None:
  713. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  714. return
  715. video_id = mobj.group(2)
  716. video_extension = 'flv'
  717. # Rewrite valid but non-extractable URLs as
  718. # extractable English language /watch/ URLs
  719. if re.match(self._VPAGE_URL, url) is None:
  720. request = compat_urllib_request.Request(url)
  721. try:
  722. webpage = compat_urllib_request.urlopen(request).read()
  723. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  724. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  725. return
  726. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  727. if mobj is None:
  728. self._downloader.trouble(u'ERROR: Unable to extract id field')
  729. return
  730. yahoo_id = mobj.group(1)
  731. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  732. if mobj is None:
  733. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  734. return
  735. yahoo_vid = mobj.group(1)
  736. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  737. return self._real_extract(url, new_video=False)
  738. # Retrieve video webpage to extract further information
  739. request = compat_urllib_request.Request(url)
  740. try:
  741. self.report_download_webpage(video_id)
  742. webpage = compat_urllib_request.urlopen(request).read()
  743. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  744. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  745. return
  746. # Extract uploader and title from webpage
  747. self.report_extraction(video_id)
  748. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  749. if mobj is None:
  750. self._downloader.trouble(u'ERROR: unable to extract video title')
  751. return
  752. video_title = mobj.group(1).decode('utf-8')
  753. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  754. if mobj is None:
  755. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  756. return
  757. video_uploader = mobj.group(1).decode('utf-8')
  758. # Extract video thumbnail
  759. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  760. if mobj is None:
  761. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  762. return
  763. video_thumbnail = mobj.group(1).decode('utf-8')
  764. # Extract video description
  765. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  766. if mobj is None:
  767. self._downloader.trouble(u'ERROR: unable to extract video description')
  768. return
  769. video_description = mobj.group(1).decode('utf-8')
  770. if not video_description:
  771. video_description = 'No description available.'
  772. # Extract video height and width
  773. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  774. if mobj is None:
  775. self._downloader.trouble(u'ERROR: unable to extract video height')
  776. return
  777. yv_video_height = mobj.group(1)
  778. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  779. if mobj is None:
  780. self._downloader.trouble(u'ERROR: unable to extract video width')
  781. return
  782. yv_video_width = mobj.group(1)
  783. # Retrieve video playlist to extract media URL
  784. # I'm not completely sure what all these options are, but we
  785. # seem to need most of them, otherwise the server sends a 401.
  786. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  787. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  788. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  789. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  790. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  791. try:
  792. self.report_download_webpage(video_id)
  793. webpage = compat_urllib_request.urlopen(request).read()
  794. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  795. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  796. return
  797. # Extract media URL from playlist XML
  798. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  799. if mobj is None:
  800. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  801. return
  802. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  803. video_url = unescapeHTML(video_url)
  804. return [{
  805. 'id': video_id.decode('utf-8'),
  806. 'url': video_url,
  807. 'uploader': video_uploader,
  808. 'upload_date': None,
  809. 'title': video_title,
  810. 'ext': video_extension.decode('utf-8'),
  811. 'thumbnail': video_thumbnail.decode('utf-8'),
  812. 'description': video_description,
  813. }]
  814. class VimeoIE(InfoExtractor):
  815. """Information extractor for vimeo.com."""
  816. # _VALID_URL matches Vimeo URLs
  817. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?:videos?/)?([0-9]+)'
  818. IE_NAME = u'vimeo'
  819. def __init__(self, downloader=None):
  820. InfoExtractor.__init__(self, downloader)
  821. def report_download_webpage(self, video_id):
  822. """Report webpage download."""
  823. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  824. def report_extraction(self, video_id):
  825. """Report information extraction."""
  826. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  827. def _real_extract(self, url, new_video=True):
  828. # Extract ID from URL
  829. mobj = re.match(self._VALID_URL, url)
  830. if mobj is None:
  831. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  832. return
  833. video_id = mobj.group(1)
  834. # Retrieve video webpage to extract further information
  835. request = compat_urllib_request.Request(url, None, std_headers)
  836. try:
  837. self.report_download_webpage(video_id)
  838. webpage_bytes = compat_urllib_request.urlopen(request).read()
  839. webpage = webpage_bytes.decode('utf-8')
  840. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  841. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  842. return
  843. # Now we begin extracting as much information as we can from what we
  844. # retrieved. First we extract the information common to all extractors,
  845. # and latter we extract those that are Vimeo specific.
  846. self.report_extraction(video_id)
  847. # Extract the config JSON
  848. try:
  849. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  850. config = json.loads(config)
  851. except:
  852. self._downloader.trouble(u'ERROR: unable to extract info section')
  853. return
  854. # Extract title
  855. video_title = config["video"]["title"]
  856. # Extract uploader and uploader_id
  857. video_uploader = config["video"]["owner"]["name"]
  858. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  859. # Extract video thumbnail
  860. video_thumbnail = config["video"]["thumbnail"]
  861. # Extract video description
  862. video_description = get_element_by_attribute("itemprop", "description", webpage)
  863. if video_description: video_description = clean_html(video_description)
  864. else: video_description = ''
  865. # Extract upload date
  866. video_upload_date = None
  867. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  868. if mobj is not None:
  869. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  870. # Vimeo specific: extract request signature and timestamp
  871. sig = config['request']['signature']
  872. timestamp = config['request']['timestamp']
  873. # Vimeo specific: extract video codec and quality information
  874. # First consider quality, then codecs, then take everything
  875. # TODO bind to format param
  876. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  877. files = { 'hd': [], 'sd': [], 'other': []}
  878. for codec_name, codec_extension in codecs:
  879. if codec_name in config["video"]["files"]:
  880. if 'hd' in config["video"]["files"][codec_name]:
  881. files['hd'].append((codec_name, codec_extension, 'hd'))
  882. elif 'sd' in config["video"]["files"][codec_name]:
  883. files['sd'].append((codec_name, codec_extension, 'sd'))
  884. else:
  885. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  886. for quality in ('hd', 'sd', 'other'):
  887. if len(files[quality]) > 0:
  888. video_quality = files[quality][0][2]
  889. video_codec = files[quality][0][0]
  890. video_extension = files[quality][0][1]
  891. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  892. break
  893. else:
  894. self._downloader.trouble(u'ERROR: no known codec found')
  895. return
  896. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  897. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  898. return [{
  899. 'id': video_id,
  900. 'url': video_url,
  901. 'uploader': video_uploader,
  902. 'uploader_id': video_uploader_id,
  903. 'upload_date': video_upload_date,
  904. 'title': video_title,
  905. 'ext': video_extension,
  906. 'thumbnail': video_thumbnail,
  907. 'description': video_description,
  908. }]
  909. class ArteTvIE(InfoExtractor):
  910. """arte.tv information extractor."""
  911. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  912. _LIVE_URL = r'index-[0-9]+\.html$'
  913. IE_NAME = u'arte.tv'
  914. def __init__(self, downloader=None):
  915. InfoExtractor.__init__(self, downloader)
  916. def report_download_webpage(self, video_id):
  917. """Report webpage download."""
  918. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  919. def report_extraction(self, video_id):
  920. """Report information extraction."""
  921. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  922. def fetch_webpage(self, url):
  923. request = compat_urllib_request.Request(url)
  924. try:
  925. self.report_download_webpage(url)
  926. webpage = compat_urllib_request.urlopen(request).read()
  927. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  928. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  929. return
  930. except ValueError as err:
  931. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  932. return
  933. return webpage
  934. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  935. page = self.fetch_webpage(url)
  936. mobj = re.search(regex, page, regexFlags)
  937. info = {}
  938. if mobj is None:
  939. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  940. return
  941. for (i, key, err) in matchTuples:
  942. if mobj.group(i) is None:
  943. self._downloader.trouble(err)
  944. return
  945. else:
  946. info[key] = mobj.group(i)
  947. return info
  948. def extractLiveStream(self, url):
  949. video_lang = url.split('/')[-4]
  950. info = self.grep_webpage(
  951. url,
  952. r'src="(.*?/videothek_js.*?\.js)',
  953. 0,
  954. [
  955. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  956. ]
  957. )
  958. http_host = url.split('/')[2]
  959. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  960. info = self.grep_webpage(
  961. next_url,
  962. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  963. '(http://.*?\.swf).*?' +
  964. '(rtmp://.*?)\'',
  965. re.DOTALL,
  966. [
  967. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  968. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  969. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  970. ]
  971. )
  972. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  973. def extractPlus7Stream(self, url):
  974. video_lang = url.split('/')[-3]
  975. info = self.grep_webpage(
  976. url,
  977. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  978. 0,
  979. [
  980. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  981. ]
  982. )
  983. next_url = compat_urllib_parse.unquote(info.get('url'))
  984. info = self.grep_webpage(
  985. next_url,
  986. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  987. 0,
  988. [
  989. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  990. ]
  991. )
  992. next_url = compat_urllib_parse.unquote(info.get('url'))
  993. info = self.grep_webpage(
  994. next_url,
  995. r'<video id="(.*?)".*?>.*?' +
  996. '<name>(.*?)</name>.*?' +
  997. '<dateVideo>(.*?)</dateVideo>.*?' +
  998. '<url quality="hd">(.*?)</url>',
  999. re.DOTALL,
  1000. [
  1001. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  1002. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  1003. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  1004. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1005. ]
  1006. )
  1007. return {
  1008. 'id': info.get('id'),
  1009. 'url': compat_urllib_parse.unquote(info.get('url')),
  1010. 'uploader': u'arte.tv',
  1011. 'upload_date': info.get('date'),
  1012. 'title': info.get('title').decode('utf-8'),
  1013. 'ext': u'mp4',
  1014. 'format': u'NA',
  1015. 'player_url': None,
  1016. }
  1017. def _real_extract(self, url):
  1018. video_id = url.split('/')[-1]
  1019. self.report_extraction(video_id)
  1020. if re.search(self._LIVE_URL, video_id) is not None:
  1021. self.extractLiveStream(url)
  1022. return
  1023. else:
  1024. info = self.extractPlus7Stream(url)
  1025. return [info]
  1026. class GenericIE(InfoExtractor):
  1027. """Generic last-resort information extractor."""
  1028. _VALID_URL = r'.*'
  1029. IE_NAME = u'generic'
  1030. def __init__(self, downloader=None):
  1031. InfoExtractor.__init__(self, downloader)
  1032. def report_download_webpage(self, video_id):
  1033. """Report webpage download."""
  1034. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1035. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1036. def report_extraction(self, video_id):
  1037. """Report information extraction."""
  1038. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1039. def report_following_redirect(self, new_url):
  1040. """Report information extraction."""
  1041. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1042. def _test_redirect(self, url):
  1043. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1044. class HeadRequest(compat_urllib_request.Request):
  1045. def get_method(self):
  1046. return "HEAD"
  1047. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1048. """
  1049. Subclass the HTTPRedirectHandler to make it use our
  1050. HeadRequest also on the redirected URL
  1051. """
  1052. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1053. if code in (301, 302, 303, 307):
  1054. newurl = newurl.replace(' ', '%20')
  1055. newheaders = dict((k,v) for k,v in req.headers.items()
  1056. if k.lower() not in ("content-length", "content-type"))
  1057. return HeadRequest(newurl,
  1058. headers=newheaders,
  1059. origin_req_host=req.get_origin_req_host(),
  1060. unverifiable=True)
  1061. else:
  1062. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1063. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1064. """
  1065. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1066. """
  1067. def http_error_405(self, req, fp, code, msg, headers):
  1068. fp.read()
  1069. fp.close()
  1070. newheaders = dict((k,v) for k,v in req.headers.items()
  1071. if k.lower() not in ("content-length", "content-type"))
  1072. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1073. headers=newheaders,
  1074. origin_req_host=req.get_origin_req_host(),
  1075. unverifiable=True))
  1076. # Build our opener
  1077. opener = compat_urllib_request.OpenerDirector()
  1078. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1079. HTTPMethodFallback, HEADRedirectHandler,
  1080. compat_urllib_error.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1081. opener.add_handler(handler())
  1082. response = opener.open(HeadRequest(url))
  1083. new_url = response.geturl()
  1084. if url == new_url:
  1085. return False
  1086. self.report_following_redirect(new_url)
  1087. self._downloader.download([new_url])
  1088. return True
  1089. def _real_extract(self, url):
  1090. if self._test_redirect(url): return
  1091. video_id = url.split('/')[-1]
  1092. request = compat_urllib_request.Request(url)
  1093. try:
  1094. self.report_download_webpage(video_id)
  1095. webpage = compat_urllib_request.urlopen(request).read()
  1096. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1097. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1098. return
  1099. except ValueError as err:
  1100. # since this is the last-resort InfoExtractor, if
  1101. # this error is thrown, it'll be thrown here
  1102. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1103. return
  1104. self.report_extraction(video_id)
  1105. # Start with something easy: JW Player in SWFObject
  1106. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1107. if mobj is None:
  1108. # Broaden the search a little bit
  1109. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1110. if mobj is None:
  1111. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1112. return
  1113. # It's possible that one of the regexes
  1114. # matched, but returned an empty group:
  1115. if mobj.group(1) is None:
  1116. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1117. return
  1118. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1119. video_id = os.path.basename(video_url)
  1120. # here's a fun little line of code for you:
  1121. video_extension = os.path.splitext(video_id)[1][1:]
  1122. video_id = os.path.splitext(video_id)[0]
  1123. # it's tempting to parse this further, but you would
  1124. # have to take into account all the variations like
  1125. # Video Title - Site Name
  1126. # Site Name | Video Title
  1127. # Video Title - Tagline | Site Name
  1128. # and so on and so forth; it's just not practical
  1129. mobj = re.search(r'<title>(.*)</title>', webpage)
  1130. if mobj is None:
  1131. self._downloader.trouble(u'ERROR: unable to extract title')
  1132. return
  1133. video_title = mobj.group(1)
  1134. # video uploader is domain name
  1135. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1136. if mobj is None:
  1137. self._downloader.trouble(u'ERROR: unable to extract title')
  1138. return
  1139. video_uploader = mobj.group(1)
  1140. return [{
  1141. 'id': video_id,
  1142. 'url': video_url,
  1143. 'uploader': video_uploader,
  1144. 'upload_date': None,
  1145. 'title': video_title,
  1146. 'ext': video_extension,
  1147. }]
  1148. class YoutubeSearchIE(InfoExtractor):
  1149. """Information Extractor for YouTube search queries."""
  1150. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1151. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1152. _max_youtube_results = 1000
  1153. IE_NAME = u'youtube:search'
  1154. def __init__(self, downloader=None):
  1155. InfoExtractor.__init__(self, downloader)
  1156. def report_download_page(self, query, pagenum):
  1157. """Report attempt to download search page with given number."""
  1158. query = query.decode(preferredencoding())
  1159. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1160. def _real_extract(self, query):
  1161. mobj = re.match(self._VALID_URL, query)
  1162. if mobj is None:
  1163. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1164. return
  1165. prefix, query = query.split(':')
  1166. prefix = prefix[8:]
  1167. query = query.encode('utf-8')
  1168. if prefix == '':
  1169. self._download_n_results(query, 1)
  1170. return
  1171. elif prefix == 'all':
  1172. self._download_n_results(query, self._max_youtube_results)
  1173. return
  1174. else:
  1175. try:
  1176. n = int(prefix)
  1177. if n <= 0:
  1178. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1179. return
  1180. elif n > self._max_youtube_results:
  1181. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1182. n = self._max_youtube_results
  1183. self._download_n_results(query, n)
  1184. return
  1185. except ValueError: # parsing prefix as integer fails
  1186. self._download_n_results(query, 1)
  1187. return
  1188. def _download_n_results(self, query, n):
  1189. """Downloads a specified number of results for a query"""
  1190. video_ids = []
  1191. pagenum = 0
  1192. limit = n
  1193. while (50 * pagenum) < limit:
  1194. self.report_download_page(query, pagenum+1)
  1195. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1196. request = compat_urllib_request.Request(result_url)
  1197. try:
  1198. data = compat_urllib_request.urlopen(request).read()
  1199. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1200. self._downloader.trouble(u'ERROR: unable to download API page: %s' % compat_str(err))
  1201. return
  1202. api_response = json.loads(data)['data']
  1203. new_ids = list(video['id'] for video in api_response['items'])
  1204. video_ids += new_ids
  1205. limit = min(n, api_response['totalItems'])
  1206. pagenum += 1
  1207. if len(video_ids) > n:
  1208. video_ids = video_ids[:n]
  1209. for id in video_ids:
  1210. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1211. return
  1212. class GoogleSearchIE(InfoExtractor):
  1213. """Information Extractor for Google Video search queries."""
  1214. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1215. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1216. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1217. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1218. _max_google_results = 1000
  1219. IE_NAME = u'video.google:search'
  1220. def __init__(self, downloader=None):
  1221. InfoExtractor.__init__(self, downloader)
  1222. def report_download_page(self, query, pagenum):
  1223. """Report attempt to download playlist page with given number."""
  1224. query = query.decode(preferredencoding())
  1225. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1226. def _real_extract(self, query):
  1227. mobj = re.match(self._VALID_URL, query)
  1228. if mobj is None:
  1229. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1230. return
  1231. prefix, query = query.split(':')
  1232. prefix = prefix[8:]
  1233. query = query.encode('utf-8')
  1234. if prefix == '':
  1235. self._download_n_results(query, 1)
  1236. return
  1237. elif prefix == 'all':
  1238. self._download_n_results(query, self._max_google_results)
  1239. return
  1240. else:
  1241. try:
  1242. n = int(prefix)
  1243. if n <= 0:
  1244. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1245. return
  1246. elif n > self._max_google_results:
  1247. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1248. n = self._max_google_results
  1249. self._download_n_results(query, n)
  1250. return
  1251. except ValueError: # parsing prefix as integer fails
  1252. self._download_n_results(query, 1)
  1253. return
  1254. def _download_n_results(self, query, n):
  1255. """Downloads a specified number of results for a query"""
  1256. video_ids = []
  1257. pagenum = 0
  1258. while True:
  1259. self.report_download_page(query, pagenum)
  1260. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1261. request = compat_urllib_request.Request(result_url)
  1262. try:
  1263. page = compat_urllib_request.urlopen(request).read()
  1264. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1265. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1266. return
  1267. # Extract video identifiers
  1268. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1269. video_id = mobj.group(1)
  1270. if video_id not in video_ids:
  1271. video_ids.append(video_id)
  1272. if len(video_ids) == n:
  1273. # Specified n videos reached
  1274. for id in video_ids:
  1275. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1276. return
  1277. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1278. for id in video_ids:
  1279. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1280. return
  1281. pagenum = pagenum + 1
  1282. class YahooSearchIE(InfoExtractor):
  1283. """Information Extractor for Yahoo! Video search queries."""
  1284. _WORKING = False
  1285. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1286. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1287. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1288. _MORE_PAGES_INDICATOR = r'\s*Next'
  1289. _max_yahoo_results = 1000
  1290. IE_NAME = u'video.yahoo:search'
  1291. def __init__(self, downloader=None):
  1292. InfoExtractor.__init__(self, downloader)
  1293. def report_download_page(self, query, pagenum):
  1294. """Report attempt to download playlist page with given number."""
  1295. query = query.decode(preferredencoding())
  1296. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1297. def _real_extract(self, query):
  1298. mobj = re.match(self._VALID_URL, query)
  1299. if mobj is None:
  1300. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1301. return
  1302. prefix, query = query.split(':')
  1303. prefix = prefix[8:]
  1304. query = query.encode('utf-8')
  1305. if prefix == '':
  1306. self._download_n_results(query, 1)
  1307. return
  1308. elif prefix == 'all':
  1309. self._download_n_results(query, self._max_yahoo_results)
  1310. return
  1311. else:
  1312. try:
  1313. n = int(prefix)
  1314. if n <= 0:
  1315. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1316. return
  1317. elif n > self._max_yahoo_results:
  1318. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1319. n = self._max_yahoo_results
  1320. self._download_n_results(query, n)
  1321. return
  1322. except ValueError: # parsing prefix as integer fails
  1323. self._download_n_results(query, 1)
  1324. return
  1325. def _download_n_results(self, query, n):
  1326. """Downloads a specified number of results for a query"""
  1327. video_ids = []
  1328. already_seen = set()
  1329. pagenum = 1
  1330. while True:
  1331. self.report_download_page(query, pagenum)
  1332. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1333. request = compat_urllib_request.Request(result_url)
  1334. try:
  1335. page = compat_urllib_request.urlopen(request).read()
  1336. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1337. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1338. return
  1339. # Extract video identifiers
  1340. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1341. video_id = mobj.group(1)
  1342. if video_id not in already_seen:
  1343. video_ids.append(video_id)
  1344. already_seen.add(video_id)
  1345. if len(video_ids) == n:
  1346. # Specified n videos reached
  1347. for id in video_ids:
  1348. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1349. return
  1350. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1351. for id in video_ids:
  1352. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1353. return
  1354. pagenum = pagenum + 1
  1355. class YoutubePlaylistIE(InfoExtractor):
  1356. """Information Extractor for YouTube playlists."""
  1357. _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|EC)?|PL|EC)([0-9A-Za-z-_]{10,})(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1358. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1359. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;([^&"]+&amp;)*list=.*?%s'
  1360. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1361. IE_NAME = u'youtube:playlist'
  1362. def __init__(self, downloader=None):
  1363. InfoExtractor.__init__(self, downloader)
  1364. def report_download_page(self, playlist_id, pagenum):
  1365. """Report attempt to download playlist page with given number."""
  1366. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1367. def _real_extract(self, url):
  1368. # Extract playlist id
  1369. mobj = re.match(self._VALID_URL, url)
  1370. if mobj is None:
  1371. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1372. return
  1373. # Single video case
  1374. if mobj.group(3) is not None:
  1375. self._downloader.download([mobj.group(3)])
  1376. return
  1377. # Download playlist pages
  1378. # prefix is 'p' as default for playlists but there are other types that need extra care
  1379. playlist_prefix = mobj.group(1)
  1380. if playlist_prefix == 'a':
  1381. playlist_access = 'artist'
  1382. else:
  1383. playlist_prefix = 'p'
  1384. playlist_access = 'view_play_list'
  1385. playlist_id = mobj.group(2)
  1386. video_ids = []
  1387. pagenum = 1
  1388. while True:
  1389. self.report_download_page(playlist_id, pagenum)
  1390. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  1391. request = compat_urllib_request.Request(url)
  1392. try:
  1393. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1394. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1395. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1396. return
  1397. # Extract video identifiers
  1398. ids_in_page = []
  1399. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  1400. if mobj.group(1) not in ids_in_page:
  1401. ids_in_page.append(mobj.group(1))
  1402. video_ids.extend(ids_in_page)
  1403. if self._MORE_PAGES_INDICATOR not in page:
  1404. break
  1405. pagenum = pagenum + 1
  1406. total = len(video_ids)
  1407. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1408. playlistend = self._downloader.params.get('playlistend', -1)
  1409. if playlistend == -1:
  1410. video_ids = video_ids[playliststart:]
  1411. else:
  1412. video_ids = video_ids[playliststart:playlistend]
  1413. if len(video_ids) == total:
  1414. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos' % (playlist_id, total))
  1415. else:
  1416. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos, downloading %i' % (playlist_id, total, len(video_ids)))
  1417. for id in video_ids:
  1418. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1419. return
  1420. class YoutubeChannelIE(InfoExtractor):
  1421. """Information Extractor for YouTube channels."""
  1422. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1423. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1424. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1425. IE_NAME = u'youtube:channel'
  1426. def report_download_page(self, channel_id, pagenum):
  1427. """Report attempt to download channel page with given number."""
  1428. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1429. def _real_extract(self, url):
  1430. # Extract channel id
  1431. mobj = re.match(self._VALID_URL, url)
  1432. if mobj is None:
  1433. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1434. return
  1435. # Download channel pages
  1436. channel_id = mobj.group(1)
  1437. video_ids = []
  1438. pagenum = 1
  1439. while True:
  1440. self.report_download_page(channel_id, pagenum)
  1441. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1442. request = compat_urllib_request.Request(url)
  1443. try:
  1444. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1445. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1446. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1447. return
  1448. # Extract video identifiers
  1449. ids_in_page = []
  1450. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1451. if mobj.group(1) not in ids_in_page:
  1452. ids_in_page.append(mobj.group(1))
  1453. video_ids.extend(ids_in_page)
  1454. if self._MORE_PAGES_INDICATOR not in page:
  1455. break
  1456. pagenum = pagenum + 1
  1457. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1458. for id in video_ids:
  1459. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1460. return
  1461. class YoutubeUserIE(InfoExtractor):
  1462. """Information Extractor for YouTube users."""
  1463. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1464. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1465. _GDATA_PAGE_SIZE = 50
  1466. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1467. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1468. IE_NAME = u'youtube:user'
  1469. def __init__(self, downloader=None):
  1470. InfoExtractor.__init__(self, downloader)
  1471. def report_download_page(self, username, start_index):
  1472. """Report attempt to download user page."""
  1473. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1474. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1475. def _real_extract(self, url):
  1476. # Extract username
  1477. mobj = re.match(self._VALID_URL, url)
  1478. if mobj is None:
  1479. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1480. return
  1481. username = mobj.group(1)
  1482. # Download video ids using YouTube Data API. Result size per
  1483. # query is limited (currently to 50 videos) so we need to query
  1484. # page by page until there are no video ids - it means we got
  1485. # all of them.
  1486. video_ids = []
  1487. pagenum = 0
  1488. while True:
  1489. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1490. self.report_download_page(username, start_index)
  1491. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1492. try:
  1493. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1494. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1495. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1496. return
  1497. # Extract video identifiers
  1498. ids_in_page = []
  1499. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1500. if mobj.group(1) not in ids_in_page:
  1501. ids_in_page.append(mobj.group(1))
  1502. video_ids.extend(ids_in_page)
  1503. # A little optimization - if current page is not
  1504. # "full", ie. does not contain PAGE_SIZE video ids then
  1505. # we can assume that this page is the last one - there
  1506. # are no more ids on further pages - no need to query
  1507. # again.
  1508. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1509. break
  1510. pagenum += 1
  1511. all_ids_count = len(video_ids)
  1512. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1513. playlistend = self._downloader.params.get('playlistend', -1)
  1514. if playlistend == -1:
  1515. video_ids = video_ids[playliststart:]
  1516. else:
  1517. video_ids = video_ids[playliststart:playlistend]
  1518. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1519. (username, all_ids_count, len(video_ids)))
  1520. for video_id in video_ids:
  1521. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1522. class BlipTVUserIE(InfoExtractor):
  1523. """Information Extractor for blip.tv users."""
  1524. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1525. _PAGE_SIZE = 12
  1526. IE_NAME = u'blip.tv:user'
  1527. def __init__(self, downloader=None):
  1528. InfoExtractor.__init__(self, downloader)
  1529. def report_download_page(self, username, pagenum):
  1530. """Report attempt to download user page."""
  1531. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1532. (self.IE_NAME, username, pagenum))
  1533. def _real_extract(self, url):
  1534. # Extract username
  1535. mobj = re.match(self._VALID_URL, url)
  1536. if mobj is None:
  1537. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1538. return
  1539. username = mobj.group(1)
  1540. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1541. request = compat_urllib_request.Request(url)
  1542. try:
  1543. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1544. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1545. page_base = page_base % mobj.group(1)
  1546. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1547. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1548. return
  1549. # Download video ids using BlipTV Ajax calls. Result size per
  1550. # query is limited (currently to 12 videos) so we need to query
  1551. # page by page until there are no video ids - it means we got
  1552. # all of them.
  1553. video_ids = []
  1554. pagenum = 1
  1555. while True:
  1556. self.report_download_page(username, pagenum)
  1557. request = compat_urllib_request.Request( page_base + "&page=" + str(pagenum) )
  1558. try:
  1559. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1560. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1561. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1562. return
  1563. # Extract video identifiers
  1564. ids_in_page = []
  1565. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1566. if mobj.group(1) not in ids_in_page:
  1567. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1568. video_ids.extend(ids_in_page)
  1569. # A little optimization - if current page is not
  1570. # "full", ie. does not contain PAGE_SIZE video ids then
  1571. # we can assume that this page is the last one - there
  1572. # are no more ids on further pages - no need to query
  1573. # again.
  1574. if len(ids_in_page) < self._PAGE_SIZE:
  1575. break
  1576. pagenum += 1
  1577. all_ids_count = len(video_ids)
  1578. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1579. playlistend = self._downloader.params.get('playlistend', -1)
  1580. if playlistend == -1:
  1581. video_ids = video_ids[playliststart:]
  1582. else:
  1583. video_ids = video_ids[playliststart:playlistend]
  1584. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1585. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1586. for video_id in video_ids:
  1587. self._downloader.download([u'http://blip.tv/'+video_id])
  1588. class DepositFilesIE(InfoExtractor):
  1589. """Information extractor for depositfiles.com"""
  1590. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1591. IE_NAME = u'DepositFiles'
  1592. def __init__(self, downloader=None):
  1593. InfoExtractor.__init__(self, downloader)
  1594. def report_download_webpage(self, file_id):
  1595. """Report webpage download."""
  1596. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1597. def report_extraction(self, file_id):
  1598. """Report information extraction."""
  1599. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1600. def _real_extract(self, url):
  1601. file_id = url.split('/')[-1]
  1602. # Rebuild url in english locale
  1603. url = 'http://depositfiles.com/en/files/' + file_id
  1604. # Retrieve file webpage with 'Free download' button pressed
  1605. free_download_indication = { 'gateway_result' : '1' }
  1606. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1607. try:
  1608. self.report_download_webpage(file_id)
  1609. webpage = compat_urllib_request.urlopen(request).read()
  1610. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1611. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1612. return
  1613. # Search for the real file URL
  1614. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1615. if (mobj is None) or (mobj.group(1) is None):
  1616. # Try to figure out reason of the error.
  1617. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1618. if (mobj is not None) and (mobj.group(1) is not None):
  1619. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1620. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1621. else:
  1622. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1623. return
  1624. file_url = mobj.group(1)
  1625. file_extension = os.path.splitext(file_url)[1][1:]
  1626. # Search for file title
  1627. mobj = re.search(r'<b title="(.*?)">', webpage)
  1628. if mobj is None:
  1629. self._downloader.trouble(u'ERROR: unable to extract title')
  1630. return
  1631. file_title = mobj.group(1).decode('utf-8')
  1632. return [{
  1633. 'id': file_id.decode('utf-8'),
  1634. 'url': file_url.decode('utf-8'),
  1635. 'uploader': None,
  1636. 'upload_date': None,
  1637. 'title': file_title,
  1638. 'ext': file_extension.decode('utf-8'),
  1639. }]
  1640. class FacebookIE(InfoExtractor):
  1641. """Information Extractor for Facebook"""
  1642. _WORKING = False
  1643. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1644. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1645. _NETRC_MACHINE = 'facebook'
  1646. _available_formats = ['video', 'highqual', 'lowqual']
  1647. _video_extensions = {
  1648. 'video': 'mp4',
  1649. 'highqual': 'mp4',
  1650. 'lowqual': 'mp4',
  1651. }
  1652. IE_NAME = u'facebook'
  1653. def __init__(self, downloader=None):
  1654. InfoExtractor.__init__(self, downloader)
  1655. def _reporter(self, message):
  1656. """Add header and report message."""
  1657. self._downloader.to_screen(u'[facebook] %s' % message)
  1658. def report_login(self):
  1659. """Report attempt to log in."""
  1660. self._reporter(u'Logging in')
  1661. def report_video_webpage_download(self, video_id):
  1662. """Report attempt to download video webpage."""
  1663. self._reporter(u'%s: Downloading video webpage' % video_id)
  1664. def report_information_extraction(self, video_id):
  1665. """Report attempt to extract video information."""
  1666. self._reporter(u'%s: Extracting video information' % video_id)
  1667. def _parse_page(self, video_webpage):
  1668. """Extract video information from page"""
  1669. # General data
  1670. data = {'title': r'\("video_title", "(.*?)"\)',
  1671. 'description': r'<div class="datawrap">(.*?)</div>',
  1672. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1673. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1674. }
  1675. video_info = {}
  1676. for piece in data.keys():
  1677. mobj = re.search(data[piece], video_webpage)
  1678. if mobj is not None:
  1679. video_info[piece] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1680. # Video urls
  1681. video_urls = {}
  1682. for fmt in self._available_formats:
  1683. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1684. if mobj is not None:
  1685. # URL is in a Javascript segment inside an escaped Unicode format within
  1686. # the generally utf-8 page
  1687. video_urls[fmt] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1688. video_info['video_urls'] = video_urls
  1689. return video_info
  1690. def _real_initialize(self):
  1691. if self._downloader is None:
  1692. return
  1693. useremail = None
  1694. password = None
  1695. downloader_params = self._downloader.params
  1696. # Attempt to use provided username and password or .netrc data
  1697. if downloader_params.get('username', None) is not None:
  1698. useremail = downloader_params['username']
  1699. password = downloader_params['password']
  1700. elif downloader_params.get('usenetrc', False):
  1701. try:
  1702. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1703. if info is not None:
  1704. useremail = info[0]
  1705. password = info[2]
  1706. else:
  1707. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1708. except (IOError, netrc.NetrcParseError) as err:
  1709. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  1710. return
  1711. if useremail is None:
  1712. return
  1713. # Log in
  1714. login_form = {
  1715. 'email': useremail,
  1716. 'pass': password,
  1717. 'login': 'Log+In'
  1718. }
  1719. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1720. try:
  1721. self.report_login()
  1722. login_results = compat_urllib_request.urlopen(request).read()
  1723. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1724. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1725. return
  1726. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1727. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  1728. return
  1729. def _real_extract(self, url):
  1730. mobj = re.match(self._VALID_URL, url)
  1731. if mobj is None:
  1732. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1733. return
  1734. video_id = mobj.group('ID')
  1735. # Get video webpage
  1736. self.report_video_webpage_download(video_id)
  1737. request = compat_urllib_request.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1738. try:
  1739. page = compat_urllib_request.urlopen(request)
  1740. video_webpage = page.read()
  1741. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1742. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  1743. return
  1744. # Start extracting information
  1745. self.report_information_extraction(video_id)
  1746. # Extract information
  1747. video_info = self._parse_page(video_webpage)
  1748. # uploader
  1749. if 'owner' not in video_info:
  1750. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1751. return
  1752. video_uploader = video_info['owner']
  1753. # title
  1754. if 'title' not in video_info:
  1755. self._downloader.trouble(u'ERROR: unable to extract video title')
  1756. return
  1757. video_title = video_info['title']
  1758. video_title = video_title.decode('utf-8')
  1759. # thumbnail image
  1760. if 'thumbnail' not in video_info:
  1761. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1762. video_thumbnail = ''
  1763. else:
  1764. video_thumbnail = video_info['thumbnail']
  1765. # upload date
  1766. upload_date = None
  1767. if 'upload_date' in video_info:
  1768. upload_time = video_info['upload_date']
  1769. timetuple = email.utils.parsedate_tz(upload_time)
  1770. if timetuple is not None:
  1771. try:
  1772. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1773. except:
  1774. pass
  1775. # description
  1776. video_description = video_info.get('description', 'No description available.')
  1777. url_map = video_info['video_urls']
  1778. if url_map:
  1779. # Decide which formats to download
  1780. req_format = self._downloader.params.get('format', None)
  1781. format_limit = self._downloader.params.get('format_limit', None)
  1782. if format_limit is not None and format_limit in self._available_formats:
  1783. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1784. else:
  1785. format_list = self._available_formats
  1786. existing_formats = [x for x in format_list if x in url_map]
  1787. if len(existing_formats) == 0:
  1788. self._downloader.trouble(u'ERROR: no known formats available for video')
  1789. return
  1790. if req_format is None:
  1791. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1792. elif req_format == 'worst':
  1793. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1794. elif req_format == '-1':
  1795. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1796. else:
  1797. # Specific format
  1798. if req_format not in url_map:
  1799. self._downloader.trouble(u'ERROR: requested format not available')
  1800. return
  1801. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1802. results = []
  1803. for format_param, video_real_url in video_url_list:
  1804. # Extension
  1805. video_extension = self._video_extensions.get(format_param, 'mp4')
  1806. results.append({
  1807. 'id': video_id.decode('utf-8'),
  1808. 'url': video_real_url.decode('utf-8'),
  1809. 'uploader': video_uploader.decode('utf-8'),
  1810. 'upload_date': upload_date,
  1811. 'title': video_title,
  1812. 'ext': video_extension.decode('utf-8'),
  1813. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1814. 'thumbnail': video_thumbnail.decode('utf-8'),
  1815. 'description': video_description.decode('utf-8'),
  1816. })
  1817. return results
  1818. class BlipTVIE(InfoExtractor):
  1819. """Information extractor for blip.tv"""
  1820. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1821. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1822. IE_NAME = u'blip.tv'
  1823. def report_extraction(self, file_id):
  1824. """Report information extraction."""
  1825. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1826. def report_direct_download(self, title):
  1827. """Report information extraction."""
  1828. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1829. def _real_extract(self, url):
  1830. mobj = re.match(self._VALID_URL, url)
  1831. if mobj is None:
  1832. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1833. return
  1834. if '?' in url:
  1835. cchar = '&'
  1836. else:
  1837. cchar = '?'
  1838. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1839. request = compat_urllib_request.Request(json_url)
  1840. self.report_extraction(mobj.group(1))
  1841. info = None
  1842. try:
  1843. urlh = compat_urllib_request.urlopen(request)
  1844. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1845. basename = url.split('/')[-1]
  1846. title,ext = os.path.splitext(basename)
  1847. title = title.decode('UTF-8')
  1848. ext = ext.replace('.', '')
  1849. self.report_direct_download(title)
  1850. info = {
  1851. 'id': title,
  1852. 'url': url,
  1853. 'uploader': None,
  1854. 'upload_date': None,
  1855. 'title': title,
  1856. 'ext': ext,
  1857. 'urlhandle': urlh
  1858. }
  1859. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1860. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1861. return
  1862. if info is None: # Regular URL
  1863. try:
  1864. json_code_bytes = urlh.read()
  1865. json_code = json_code_bytes.decode('utf-8')
  1866. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1867. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1868. return
  1869. try:
  1870. json_data = json.loads(json_code)
  1871. if 'Post' in json_data:
  1872. data = json_data['Post']
  1873. else:
  1874. data = json_data
  1875. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1876. video_url = data['media']['url']
  1877. umobj = re.match(self._URL_EXT, video_url)
  1878. if umobj is None:
  1879. raise ValueError('Can not determine filename extension')
  1880. ext = umobj.group(1)
  1881. info = {
  1882. 'id': data['item_id'],
  1883. 'url': video_url,
  1884. 'uploader': data['display_name'],
  1885. 'upload_date': upload_date,
  1886. 'title': data['title'],
  1887. 'ext': ext,
  1888. 'format': data['media']['mimeType'],
  1889. 'thumbnail': data['thumbnailUrl'],
  1890. 'description': data['description'],
  1891. 'player_url': data['embedUrl']
  1892. }
  1893. except (ValueError,KeyError) as err:
  1894. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1895. return
  1896. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1897. return [info]
  1898. class MyVideoIE(InfoExtractor):
  1899. """Information Extractor for myvideo.de."""
  1900. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1901. IE_NAME = u'myvideo'
  1902. def __init__(self, downloader=None):
  1903. InfoExtractor.__init__(self, downloader)
  1904. def report_download_webpage(self, video_id):
  1905. """Report webpage download."""
  1906. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1907. def report_extraction(self, video_id):
  1908. """Report information extraction."""
  1909. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1910. def _real_extract(self,url):
  1911. mobj = re.match(self._VALID_URL, url)
  1912. if mobj is None:
  1913. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1914. return
  1915. video_id = mobj.group(1)
  1916. # Get video webpage
  1917. request = compat_urllib_request.Request('http://www.myvideo.de/watch/%s' % video_id)
  1918. try:
  1919. self.report_download_webpage(video_id)
  1920. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1921. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1922. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1923. return
  1924. self.report_extraction(video_id)
  1925. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1926. webpage)
  1927. if mobj is None:
  1928. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1929. return
  1930. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1931. mobj = re.search('<title>([^<]+)</title>', webpage)
  1932. if mobj is None:
  1933. self._downloader.trouble(u'ERROR: unable to extract title')
  1934. return
  1935. video_title = mobj.group(1)
  1936. return [{
  1937. 'id': video_id,
  1938. 'url': video_url,
  1939. 'uploader': None,
  1940. 'upload_date': None,
  1941. 'title': video_title,
  1942. 'ext': u'flv',
  1943. }]
  1944. class ComedyCentralIE(InfoExtractor):
  1945. """Information extractor for The Daily Show and Colbert Report """
  1946. # urls can be abbreviations like :thedailyshow or :colbert
  1947. # urls for episodes like:
  1948. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1949. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1950. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1951. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1952. |(https?://)?(www\.)?
  1953. (?P<showname>thedailyshow|colbertnation)\.com/
  1954. (full-episodes/(?P<episode>.*)|
  1955. (?P<clip>
  1956. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1957. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1958. $"""
  1959. IE_NAME = u'comedycentral'
  1960. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1961. _video_extensions = {
  1962. '3500': 'mp4',
  1963. '2200': 'mp4',
  1964. '1700': 'mp4',
  1965. '1200': 'mp4',
  1966. '750': 'mp4',
  1967. '400': 'mp4',
  1968. }
  1969. _video_dimensions = {
  1970. '3500': '1280x720',
  1971. '2200': '960x540',
  1972. '1700': '768x432',
  1973. '1200': '640x360',
  1974. '750': '512x288',
  1975. '400': '384x216',
  1976. }
  1977. def suitable(self, url):
  1978. """Receives a URL and returns True if suitable for this IE."""
  1979. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  1980. def report_extraction(self, episode_id):
  1981. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1982. def report_config_download(self, episode_id):
  1983. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  1984. def report_index_download(self, episode_id):
  1985. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1986. def report_player_url(self, episode_id):
  1987. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  1988. def _print_formats(self, formats):
  1989. print('Available formats:')
  1990. for x in formats:
  1991. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1992. def _real_extract(self, url):
  1993. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1994. if mobj is None:
  1995. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1996. return
  1997. if mobj.group('shortname'):
  1998. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1999. url = u'http://www.thedailyshow.com/full-episodes/'
  2000. else:
  2001. url = u'http://www.colbertnation.com/full-episodes/'
  2002. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2003. assert mobj is not None
  2004. if mobj.group('clip'):
  2005. if mobj.group('showname') == 'thedailyshow':
  2006. epTitle = mobj.group('tdstitle')
  2007. else:
  2008. epTitle = mobj.group('cntitle')
  2009. dlNewest = False
  2010. else:
  2011. dlNewest = not mobj.group('episode')
  2012. if dlNewest:
  2013. epTitle = mobj.group('showname')
  2014. else:
  2015. epTitle = mobj.group('episode')
  2016. req = compat_urllib_request.Request(url)
  2017. self.report_extraction(epTitle)
  2018. try:
  2019. htmlHandle = compat_urllib_request.urlopen(req)
  2020. html = htmlHandle.read()
  2021. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2022. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2023. return
  2024. if dlNewest:
  2025. url = htmlHandle.geturl()
  2026. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2027. if mobj is None:
  2028. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2029. return
  2030. if mobj.group('episode') == '':
  2031. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2032. return
  2033. epTitle = mobj.group('episode')
  2034. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', html)
  2035. if len(mMovieParams) == 0:
  2036. # The Colbert Report embeds the information in a without
  2037. # a URL prefix; so extract the alternate reference
  2038. # and then add the URL prefix manually.
  2039. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', html)
  2040. if len(altMovieParams) == 0:
  2041. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2042. return
  2043. else:
  2044. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2045. playerUrl_raw = mMovieParams[0][0]
  2046. self.report_player_url(epTitle)
  2047. try:
  2048. urlHandle = compat_urllib_request.urlopen(playerUrl_raw)
  2049. playerUrl = urlHandle.geturl()
  2050. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2051. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + compat_str(err))
  2052. return
  2053. uri = mMovieParams[0][1]
  2054. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2055. self.report_index_download(epTitle)
  2056. try:
  2057. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2058. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2059. self._downloader.trouble(u'ERROR: unable to download episode index: ' + compat_str(err))
  2060. return
  2061. results = []
  2062. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2063. itemEls = idoc.findall('.//item')
  2064. for itemEl in itemEls:
  2065. mediaId = itemEl.findall('./guid')[0].text
  2066. shortMediaId = mediaId.split(':')[-1]
  2067. showId = mediaId.split(':')[-2].replace('.com', '')
  2068. officialTitle = itemEl.findall('./title')[0].text
  2069. officialDate = itemEl.findall('./pubDate')[0].text
  2070. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2071. compat_urllib_parse.urlencode({'uri': mediaId}))
  2072. configReq = compat_urllib_request.Request(configUrl)
  2073. self.report_config_download(epTitle)
  2074. try:
  2075. configXml = compat_urllib_request.urlopen(configReq).read()
  2076. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2077. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2078. return
  2079. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2080. turls = []
  2081. for rendition in cdoc.findall('.//rendition'):
  2082. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2083. turls.append(finfo)
  2084. if len(turls) == 0:
  2085. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2086. continue
  2087. if self._downloader.params.get('listformats', None):
  2088. self._print_formats([i[0] for i in turls])
  2089. return
  2090. # For now, just pick the highest bitrate
  2091. format,video_url = turls[-1]
  2092. # Get the format arg from the arg stream
  2093. req_format = self._downloader.params.get('format', None)
  2094. # Select format if we can find one
  2095. for f,v in turls:
  2096. if f == req_format:
  2097. format, video_url = f, v
  2098. break
  2099. # Patch to download from alternative CDN, which does not
  2100. # break on current RTMPDump builds
  2101. broken_cdn = "rtmpe://viacomccstrmfs.fplive.net/viacomccstrm/gsp.comedystor/"
  2102. better_cdn = "rtmpe://cp10740.edgefcs.net/ondemand/mtvnorigin/gsp.comedystor/"
  2103. if video_url.startswith(broken_cdn):
  2104. video_url = video_url.replace(broken_cdn, better_cdn)
  2105. effTitle = showId + u'-' + epTitle
  2106. info = {
  2107. 'id': shortMediaId,
  2108. 'url': video_url,
  2109. 'uploader': showId,
  2110. 'upload_date': officialDate,
  2111. 'title': effTitle,
  2112. 'ext': 'mp4',
  2113. 'format': format,
  2114. 'thumbnail': None,
  2115. 'description': officialTitle,
  2116. 'player_url': None #playerUrl
  2117. }
  2118. results.append(info)
  2119. return results
  2120. class EscapistIE(InfoExtractor):
  2121. """Information extractor for The Escapist """
  2122. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2123. IE_NAME = u'escapist'
  2124. def report_extraction(self, showName):
  2125. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2126. def report_config_download(self, showName):
  2127. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2128. def _real_extract(self, url):
  2129. mobj = re.match(self._VALID_URL, url)
  2130. if mobj is None:
  2131. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2132. return
  2133. showName = mobj.group('showname')
  2134. videoId = mobj.group('episode')
  2135. self.report_extraction(showName)
  2136. try:
  2137. webPage = compat_urllib_request.urlopen(url)
  2138. webPageBytes = webPage.read()
  2139. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2140. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2141. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2142. self._downloader.trouble(u'ERROR: unable to download webpage: ' + compat_str(err))
  2143. return
  2144. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2145. description = unescapeHTML(descMatch.group(1))
  2146. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2147. imgUrl = unescapeHTML(imgMatch.group(1))
  2148. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2149. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2150. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2151. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2152. self.report_config_download(showName)
  2153. try:
  2154. configJSON = compat_urllib_request.urlopen(configUrl)
  2155. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2156. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2157. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2158. self._downloader.trouble(u'ERROR: unable to download configuration: ' + compat_str(err))
  2159. return
  2160. # Technically, it's JavaScript, not JSON
  2161. configJSON = configJSON.replace("'", '"')
  2162. try:
  2163. config = json.loads(configJSON)
  2164. except (ValueError,) as err:
  2165. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + compat_str(err))
  2166. return
  2167. playlist = config['playlist']
  2168. videoUrl = playlist[1]['url']
  2169. info = {
  2170. 'id': videoId,
  2171. 'url': videoUrl,
  2172. 'uploader': showName,
  2173. 'upload_date': None,
  2174. 'title': showName,
  2175. 'ext': 'flv',
  2176. 'thumbnail': imgUrl,
  2177. 'description': description,
  2178. 'player_url': playerUrl,
  2179. }
  2180. return [info]
  2181. class CollegeHumorIE(InfoExtractor):
  2182. """Information extractor for collegehumor.com"""
  2183. _WORKING = False
  2184. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2185. IE_NAME = u'collegehumor'
  2186. def report_manifest(self, video_id):
  2187. """Report information extraction."""
  2188. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2189. def report_extraction(self, video_id):
  2190. """Report information extraction."""
  2191. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2192. def _real_extract(self, url):
  2193. mobj = re.match(self._VALID_URL, url)
  2194. if mobj is None:
  2195. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2196. return
  2197. video_id = mobj.group('videoid')
  2198. info = {
  2199. 'id': video_id,
  2200. 'uploader': None,
  2201. 'upload_date': None,
  2202. }
  2203. self.report_extraction(video_id)
  2204. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2205. try:
  2206. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2207. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2208. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2209. return
  2210. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2211. try:
  2212. videoNode = mdoc.findall('./video')[0]
  2213. info['description'] = videoNode.findall('./description')[0].text
  2214. info['title'] = videoNode.findall('./caption')[0].text
  2215. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2216. manifest_url = videoNode.findall('./file')[0].text
  2217. except IndexError:
  2218. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2219. return
  2220. manifest_url += '?hdcore=2.10.3'
  2221. self.report_manifest(video_id)
  2222. try:
  2223. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2224. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2225. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2226. return
  2227. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2228. try:
  2229. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2230. node_id = media_node.attrib['url']
  2231. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2232. except IndexError as err:
  2233. self._downloader.trouble(u'\nERROR: Invalid manifest file')
  2234. return
  2235. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2236. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2237. info['url'] = url
  2238. info['ext'] = 'f4f'
  2239. return [info]
  2240. class XVideosIE(InfoExtractor):
  2241. """Information extractor for xvideos.com"""
  2242. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2243. IE_NAME = u'xvideos'
  2244. def report_webpage(self, video_id):
  2245. """Report information extraction."""
  2246. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2247. def report_extraction(self, video_id):
  2248. """Report information extraction."""
  2249. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2250. def _real_extract(self, url):
  2251. mobj = re.match(self._VALID_URL, url)
  2252. if mobj is None:
  2253. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2254. return
  2255. video_id = mobj.group(1)
  2256. self.report_webpage(video_id)
  2257. request = compat_urllib_request.Request(r'http://www.xvideos.com/video' + video_id)
  2258. try:
  2259. webpage_bytes = compat_urllib_request.urlopen(request).read()
  2260. webpage = webpage_bytes.decode('utf-8', 'replace')
  2261. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2262. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2263. return
  2264. self.report_extraction(video_id)
  2265. # Extract video URL
  2266. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2267. if mobj is None:
  2268. self._downloader.trouble(u'ERROR: unable to extract video url')
  2269. return
  2270. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2271. # Extract title
  2272. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2273. if mobj is None:
  2274. self._downloader.trouble(u'ERROR: unable to extract video title')
  2275. return
  2276. video_title = mobj.group(1)
  2277. # Extract video thumbnail
  2278. 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)
  2279. if mobj is None:
  2280. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2281. return
  2282. video_thumbnail = mobj.group(0)
  2283. info = {
  2284. 'id': video_id,
  2285. 'url': video_url,
  2286. 'uploader': None,
  2287. 'upload_date': None,
  2288. 'title': video_title,
  2289. 'ext': 'flv',
  2290. 'thumbnail': video_thumbnail,
  2291. 'description': None,
  2292. }
  2293. return [info]
  2294. class SoundcloudIE(InfoExtractor):
  2295. """Information extractor for soundcloud.com
  2296. To access the media, the uid of the song and a stream token
  2297. must be extracted from the page source and the script must make
  2298. a request to media.soundcloud.com/crossdomain.xml. Then
  2299. the media can be grabbed by requesting from an url composed
  2300. of the stream token and uid
  2301. """
  2302. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2303. IE_NAME = u'soundcloud'
  2304. def __init__(self, downloader=None):
  2305. InfoExtractor.__init__(self, downloader)
  2306. def report_resolve(self, video_id):
  2307. """Report information extraction."""
  2308. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2309. def report_extraction(self, video_id):
  2310. """Report information extraction."""
  2311. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2312. def _real_extract(self, url):
  2313. mobj = re.match(self._VALID_URL, url)
  2314. if mobj is None:
  2315. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2316. return
  2317. # extract uploader (which is in the url)
  2318. uploader = mobj.group(1)
  2319. # extract simple title (uploader + slug of song title)
  2320. slug_title = mobj.group(2)
  2321. simple_title = uploader + u'-' + slug_title
  2322. self.report_resolve('%s/%s' % (uploader, slug_title))
  2323. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2324. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2325. request = compat_urllib_request.Request(resolv_url)
  2326. try:
  2327. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2328. info_json = info_json_bytes.decode('utf-8')
  2329. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2330. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2331. return
  2332. info = json.loads(info_json)
  2333. video_id = info['id']
  2334. self.report_extraction('%s/%s' % (uploader, slug_title))
  2335. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2336. request = compat_urllib_request.Request(streams_url)
  2337. try:
  2338. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2339. stream_json = stream_json_bytes.decode('utf-8')
  2340. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2341. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2342. return
  2343. streams = json.loads(stream_json)
  2344. mediaURL = streams['http_mp3_128_url']
  2345. return [{
  2346. 'id': info['id'],
  2347. 'url': mediaURL,
  2348. 'uploader': info['user']['username'],
  2349. 'upload_date': info['created_at'],
  2350. 'title': info['title'],
  2351. 'ext': u'mp3',
  2352. 'description': info['description'],
  2353. }]
  2354. class InfoQIE(InfoExtractor):
  2355. """Information extractor for infoq.com"""
  2356. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2357. IE_NAME = u'infoq'
  2358. def report_webpage(self, video_id):
  2359. """Report information extraction."""
  2360. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2361. def report_extraction(self, video_id):
  2362. """Report information extraction."""
  2363. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2364. def _real_extract(self, url):
  2365. mobj = re.match(self._VALID_URL, url)
  2366. if mobj is None:
  2367. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2368. return
  2369. self.report_webpage(url)
  2370. request = compat_urllib_request.Request(url)
  2371. try:
  2372. webpage = compat_urllib_request.urlopen(request).read()
  2373. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2374. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2375. return
  2376. self.report_extraction(url)
  2377. # Extract video URL
  2378. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2379. if mobj is None:
  2380. self._downloader.trouble(u'ERROR: unable to extract video url')
  2381. return
  2382. video_url = 'rtmpe://video.infoq.com/cfx/st/' + compat_urllib_parse.unquote(mobj.group(1).decode('base64'))
  2383. # Extract title
  2384. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2385. if mobj is None:
  2386. self._downloader.trouble(u'ERROR: unable to extract video title')
  2387. return
  2388. video_title = mobj.group(1).decode('utf-8')
  2389. # Extract description
  2390. video_description = u'No description available.'
  2391. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2392. if mobj is not None:
  2393. video_description = mobj.group(1).decode('utf-8')
  2394. video_filename = video_url.split('/')[-1]
  2395. video_id, extension = video_filename.split('.')
  2396. info = {
  2397. 'id': video_id,
  2398. 'url': video_url,
  2399. 'uploader': None,
  2400. 'upload_date': None,
  2401. 'title': video_title,
  2402. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2403. 'thumbnail': None,
  2404. 'description': video_description,
  2405. }
  2406. return [info]
  2407. class MixcloudIE(InfoExtractor):
  2408. """Information extractor for www.mixcloud.com"""
  2409. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2410. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2411. IE_NAME = u'mixcloud'
  2412. def __init__(self, downloader=None):
  2413. InfoExtractor.__init__(self, downloader)
  2414. def report_download_json(self, file_id):
  2415. """Report JSON download."""
  2416. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2417. def report_extraction(self, file_id):
  2418. """Report information extraction."""
  2419. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2420. def get_urls(self, jsonData, fmt, bitrate='best'):
  2421. """Get urls from 'audio_formats' section in json"""
  2422. file_url = None
  2423. try:
  2424. bitrate_list = jsonData[fmt]
  2425. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2426. bitrate = max(bitrate_list) # select highest
  2427. url_list = jsonData[fmt][bitrate]
  2428. except TypeError: # we have no bitrate info.
  2429. url_list = jsonData[fmt]
  2430. return url_list
  2431. def check_urls(self, url_list):
  2432. """Returns 1st active url from list"""
  2433. for url in url_list:
  2434. try:
  2435. compat_urllib_request.urlopen(url)
  2436. return url
  2437. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2438. url = None
  2439. return None
  2440. def _print_formats(self, formats):
  2441. print('Available formats:')
  2442. for fmt in formats.keys():
  2443. for b in formats[fmt]:
  2444. try:
  2445. ext = formats[fmt][b][0]
  2446. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2447. except TypeError: # we have no bitrate info
  2448. ext = formats[fmt][0]
  2449. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2450. break
  2451. def _real_extract(self, url):
  2452. mobj = re.match(self._VALID_URL, url)
  2453. if mobj is None:
  2454. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2455. return
  2456. # extract uploader & filename from url
  2457. uploader = mobj.group(1).decode('utf-8')
  2458. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2459. # construct API request
  2460. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2461. # retrieve .json file with links to files
  2462. request = compat_urllib_request.Request(file_url)
  2463. try:
  2464. self.report_download_json(file_url)
  2465. jsonData = compat_urllib_request.urlopen(request).read()
  2466. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2467. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2468. return
  2469. # parse JSON
  2470. json_data = json.loads(jsonData)
  2471. player_url = json_data['player_swf_url']
  2472. formats = dict(json_data['audio_formats'])
  2473. req_format = self._downloader.params.get('format', None)
  2474. bitrate = None
  2475. if self._downloader.params.get('listformats', None):
  2476. self._print_formats(formats)
  2477. return
  2478. if req_format is None or req_format == 'best':
  2479. for format_param in formats.keys():
  2480. url_list = self.get_urls(formats, format_param)
  2481. # check urls
  2482. file_url = self.check_urls(url_list)
  2483. if file_url is not None:
  2484. break # got it!
  2485. else:
  2486. if req_format not in formats:
  2487. self._downloader.trouble(u'ERROR: format is not available')
  2488. return
  2489. url_list = self.get_urls(formats, req_format)
  2490. file_url = self.check_urls(url_list)
  2491. format_param = req_format
  2492. return [{
  2493. 'id': file_id.decode('utf-8'),
  2494. 'url': file_url.decode('utf-8'),
  2495. 'uploader': uploader.decode('utf-8'),
  2496. 'upload_date': None,
  2497. 'title': json_data['name'],
  2498. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2499. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2500. 'thumbnail': json_data['thumbnail_url'],
  2501. 'description': json_data['description'],
  2502. 'player_url': player_url.decode('utf-8'),
  2503. }]
  2504. class StanfordOpenClassroomIE(InfoExtractor):
  2505. """Information extractor for Stanford's Open ClassRoom"""
  2506. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2507. IE_NAME = u'stanfordoc'
  2508. def report_download_webpage(self, objid):
  2509. """Report information extraction."""
  2510. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2511. def report_extraction(self, video_id):
  2512. """Report information extraction."""
  2513. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2514. def _real_extract(self, url):
  2515. mobj = re.match(self._VALID_URL, url)
  2516. if mobj is None:
  2517. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2518. return
  2519. if mobj.group('course') and mobj.group('video'): # A specific video
  2520. course = mobj.group('course')
  2521. video = mobj.group('video')
  2522. info = {
  2523. 'id': course + '_' + video,
  2524. 'uploader': None,
  2525. 'upload_date': None,
  2526. }
  2527. self.report_extraction(info['id'])
  2528. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2529. xmlUrl = baseUrl + video + '.xml'
  2530. try:
  2531. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2532. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2533. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2534. return
  2535. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2536. try:
  2537. info['title'] = mdoc.findall('./title')[0].text
  2538. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2539. except IndexError:
  2540. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2541. return
  2542. info['ext'] = info['url'].rpartition('.')[2]
  2543. return [info]
  2544. elif mobj.group('course'): # A course page
  2545. course = mobj.group('course')
  2546. info = {
  2547. 'id': course,
  2548. 'type': 'playlist',
  2549. 'uploader': None,
  2550. 'upload_date': None,
  2551. }
  2552. self.report_download_webpage(info['id'])
  2553. try:
  2554. coursepage = compat_urllib_request.urlopen(url).read()
  2555. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2556. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2557. return
  2558. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2559. if m:
  2560. info['title'] = unescapeHTML(m.group(1))
  2561. else:
  2562. info['title'] = info['id']
  2563. m = re.search('<description>([^<]+)</description>', coursepage)
  2564. if m:
  2565. info['description'] = unescapeHTML(m.group(1))
  2566. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2567. info['list'] = [
  2568. {
  2569. 'type': 'reference',
  2570. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2571. }
  2572. for vpage in links]
  2573. results = []
  2574. for entry in info['list']:
  2575. assert entry['type'] == 'reference'
  2576. results += self.extract(entry['url'])
  2577. return results
  2578. else: # Root page
  2579. info = {
  2580. 'id': 'Stanford OpenClassroom',
  2581. 'type': 'playlist',
  2582. 'uploader': None,
  2583. 'upload_date': None,
  2584. }
  2585. self.report_download_webpage(info['id'])
  2586. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2587. try:
  2588. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2589. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2590. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2591. return
  2592. info['title'] = info['id']
  2593. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2594. info['list'] = [
  2595. {
  2596. 'type': 'reference',
  2597. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2598. }
  2599. for cpage in links]
  2600. results = []
  2601. for entry in info['list']:
  2602. assert entry['type'] == 'reference'
  2603. results += self.extract(entry['url'])
  2604. return results
  2605. class MTVIE(InfoExtractor):
  2606. """Information extractor for MTV.com"""
  2607. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2608. IE_NAME = u'mtv'
  2609. def report_webpage(self, video_id):
  2610. """Report information extraction."""
  2611. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2612. def report_extraction(self, video_id):
  2613. """Report information extraction."""
  2614. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2615. def _real_extract(self, url):
  2616. mobj = re.match(self._VALID_URL, url)
  2617. if mobj is None:
  2618. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2619. return
  2620. if not mobj.group('proto'):
  2621. url = 'http://' + url
  2622. video_id = mobj.group('videoid')
  2623. self.report_webpage(video_id)
  2624. request = compat_urllib_request.Request(url)
  2625. try:
  2626. webpage = compat_urllib_request.urlopen(request).read()
  2627. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2628. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2629. return
  2630. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2631. if mobj is None:
  2632. self._downloader.trouble(u'ERROR: unable to extract song name')
  2633. return
  2634. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2635. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2636. if mobj is None:
  2637. self._downloader.trouble(u'ERROR: unable to extract performer')
  2638. return
  2639. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2640. video_title = performer + ' - ' + song_name
  2641. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2642. if mobj is None:
  2643. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2644. return
  2645. mtvn_uri = mobj.group(1)
  2646. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2647. if mobj is None:
  2648. self._downloader.trouble(u'ERROR: unable to extract content id')
  2649. return
  2650. content_id = mobj.group(1)
  2651. 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
  2652. self.report_extraction(video_id)
  2653. request = compat_urllib_request.Request(videogen_url)
  2654. try:
  2655. metadataXml = compat_urllib_request.urlopen(request).read()
  2656. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2657. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2658. return
  2659. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2660. renditions = mdoc.findall('.//rendition')
  2661. # For now, always pick the highest quality.
  2662. rendition = renditions[-1]
  2663. try:
  2664. _,_,ext = rendition.attrib['type'].partition('/')
  2665. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2666. video_url = rendition.find('./src').text
  2667. except KeyError:
  2668. self._downloader.trouble('Invalid rendition field.')
  2669. return
  2670. info = {
  2671. 'id': video_id,
  2672. 'url': video_url,
  2673. 'uploader': performer,
  2674. 'upload_date': None,
  2675. 'title': video_title,
  2676. 'ext': ext,
  2677. 'format': format,
  2678. }
  2679. return [info]
  2680. class YoukuIE(InfoExtractor):
  2681. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2682. IE_NAME = u'Youku'
  2683. def __init__(self, downloader=None):
  2684. InfoExtractor.__init__(self, downloader)
  2685. def report_download_webpage(self, file_id):
  2686. """Report webpage download."""
  2687. self._downloader.to_screen(u'[Youku] %s: Downloading webpage' % file_id)
  2688. def report_extraction(self, file_id):
  2689. """Report information extraction."""
  2690. self._downloader.to_screen(u'[Youku] %s: Extracting information' % file_id)
  2691. def _gen_sid(self):
  2692. nowTime = int(time.time() * 1000)
  2693. random1 = random.randint(1000,1998)
  2694. random2 = random.randint(1000,9999)
  2695. return "%d%d%d" %(nowTime,random1,random2)
  2696. def _get_file_ID_mix_string(self, seed):
  2697. mixed = []
  2698. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2699. seed = float(seed)
  2700. for i in range(len(source)):
  2701. seed = (seed * 211 + 30031 ) % 65536
  2702. index = math.floor(seed / 65536 * len(source) )
  2703. mixed.append(source[int(index)])
  2704. source.remove(source[int(index)])
  2705. #return ''.join(mixed)
  2706. return mixed
  2707. def _get_file_id(self, fileId, seed):
  2708. mixed = self._get_file_ID_mix_string(seed)
  2709. ids = fileId.split('*')
  2710. realId = []
  2711. for ch in ids:
  2712. if ch:
  2713. realId.append(mixed[int(ch)])
  2714. return ''.join(realId)
  2715. def _real_extract(self, url):
  2716. mobj = re.match(self._VALID_URL, url)
  2717. if mobj is None:
  2718. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2719. return
  2720. video_id = mobj.group('ID')
  2721. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2722. request = compat_urllib_request.Request(info_url, None, std_headers)
  2723. try:
  2724. self.report_download_webpage(video_id)
  2725. jsondata = compat_urllib_request.urlopen(request).read()
  2726. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2727. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2728. return
  2729. self.report_extraction(video_id)
  2730. try:
  2731. jsonstr = jsondata.decode('utf-8')
  2732. config = json.loads(jsonstr)
  2733. video_title = config['data'][0]['title']
  2734. seed = config['data'][0]['seed']
  2735. format = self._downloader.params.get('format', None)
  2736. supported_format = list(config['data'][0]['streamfileids'].keys())
  2737. if format is None or format == 'best':
  2738. if 'hd2' in supported_format:
  2739. format = 'hd2'
  2740. else:
  2741. format = 'flv'
  2742. ext = u'flv'
  2743. elif format == 'worst':
  2744. format = 'mp4'
  2745. ext = u'mp4'
  2746. else:
  2747. format = 'flv'
  2748. ext = u'flv'
  2749. fileid = config['data'][0]['streamfileids'][format]
  2750. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2751. except (UnicodeDecodeError, ValueError, KeyError):
  2752. self._downloader.trouble(u'ERROR: unable to extract info section')
  2753. return
  2754. files_info=[]
  2755. sid = self._gen_sid()
  2756. fileid = self._get_file_id(fileid, seed)
  2757. #column 8,9 of fileid represent the segment number
  2758. #fileid[7:9] should be changed
  2759. for index, key in enumerate(keys):
  2760. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2761. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2762. info = {
  2763. 'id': '%s_part%02d' % (video_id, index),
  2764. 'url': download_url,
  2765. 'uploader': None,
  2766. 'upload_date': None,
  2767. 'title': video_title,
  2768. 'ext': ext,
  2769. }
  2770. files_info.append(info)
  2771. return files_info
  2772. class XNXXIE(InfoExtractor):
  2773. """Information extractor for xnxx.com"""
  2774. _VALID_URL = r'^http://video\.xnxx\.com/video([0-9]+)/(.*)'
  2775. IE_NAME = u'xnxx'
  2776. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2777. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2778. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2779. def report_webpage(self, video_id):
  2780. """Report information extraction"""
  2781. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2782. def report_extraction(self, video_id):
  2783. """Report information extraction"""
  2784. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2785. def _real_extract(self, url):
  2786. mobj = re.match(self._VALID_URL, url)
  2787. if mobj is None:
  2788. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2789. return
  2790. video_id = mobj.group(1)
  2791. self.report_webpage(video_id)
  2792. # Get webpage content
  2793. try:
  2794. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2795. webpage = webpage_bytes.decode('utf-8')
  2796. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2797. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2798. return
  2799. result = re.search(self.VIDEO_URL_RE, webpage)
  2800. if result is None:
  2801. self._downloader.trouble(u'ERROR: unable to extract video url')
  2802. return
  2803. video_url = compat_urllib_parse.unquote(result.group(1))
  2804. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2805. if result is None:
  2806. self._downloader.trouble(u'ERROR: unable to extract video title')
  2807. return
  2808. video_title = result.group(1)
  2809. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2810. if result is None:
  2811. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2812. return
  2813. video_thumbnail = result.group(1)
  2814. return [{
  2815. 'id': video_id,
  2816. 'url': video_url,
  2817. 'uploader': None,
  2818. 'upload_date': None,
  2819. 'title': video_title,
  2820. 'ext': 'flv',
  2821. 'thumbnail': video_thumbnail,
  2822. 'description': None,
  2823. }]
  2824. class GooglePlusIE(InfoExtractor):
  2825. """Information extractor for plus.google.com."""
  2826. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2827. IE_NAME = u'plus.google'
  2828. def __init__(self, downloader=None):
  2829. InfoExtractor.__init__(self, downloader)
  2830. def report_extract_entry(self, url):
  2831. """Report downloading extry"""
  2832. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url)
  2833. def report_date(self, upload_date):
  2834. """Report downloading extry"""
  2835. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2836. def report_uploader(self, uploader):
  2837. """Report downloading extry"""
  2838. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader)
  2839. def report_title(self, video_title):
  2840. """Report downloading extry"""
  2841. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title)
  2842. def report_extract_vid_page(self, video_page):
  2843. """Report information extraction."""
  2844. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page)
  2845. def _real_extract(self, url):
  2846. # Extract id from URL
  2847. mobj = re.match(self._VALID_URL, url)
  2848. if mobj is None:
  2849. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2850. return
  2851. post_url = mobj.group(0)
  2852. video_id = mobj.group(1)
  2853. video_extension = 'flv'
  2854. # Step 1, Retrieve post webpage to extract further information
  2855. self.report_extract_entry(post_url)
  2856. request = compat_urllib_request.Request(post_url)
  2857. try:
  2858. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2859. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2860. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2861. return
  2862. # Extract update date
  2863. upload_date = None
  2864. pattern = 'title="Timestamp">(.*?)</a>'
  2865. mobj = re.search(pattern, webpage)
  2866. if mobj:
  2867. upload_date = mobj.group(1)
  2868. # Convert timestring to a format suitable for filename
  2869. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2870. upload_date = upload_date.strftime('%Y%m%d')
  2871. self.report_date(upload_date)
  2872. # Extract uploader
  2873. uploader = None
  2874. pattern = r'rel\="author".*?>(.*?)</a>'
  2875. mobj = re.search(pattern, webpage)
  2876. if mobj:
  2877. uploader = mobj.group(1)
  2878. self.report_uploader(uploader)
  2879. # Extract title
  2880. # Get the first line for title
  2881. video_title = u'NA'
  2882. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2883. mobj = re.search(pattern, webpage)
  2884. if mobj:
  2885. video_title = mobj.group(1)
  2886. self.report_title(video_title)
  2887. # Step 2, Stimulate clicking the image box to launch video
  2888. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2889. mobj = re.search(pattern, webpage)
  2890. if mobj is None:
  2891. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2892. video_page = mobj.group(1)
  2893. request = compat_urllib_request.Request(video_page)
  2894. try:
  2895. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2896. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2897. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2898. return
  2899. self.report_extract_vid_page(video_page)
  2900. # Extract video links on video page
  2901. """Extract video links of all sizes"""
  2902. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2903. mobj = re.findall(pattern, webpage)
  2904. if len(mobj) == 0:
  2905. self._downloader.trouble(u'ERROR: unable to extract video links')
  2906. # Sort in resolution
  2907. links = sorted(mobj)
  2908. # Choose the lowest of the sort, i.e. highest resolution
  2909. video_url = links[-1]
  2910. # Only get the url. The resolution part in the tuple has no use anymore
  2911. video_url = video_url[-1]
  2912. # Treat escaped \u0026 style hex
  2913. try:
  2914. video_url = video_url.decode("unicode_escape")
  2915. except AttributeError: # Python 3
  2916. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2917. return [{
  2918. 'id': video_id,
  2919. 'url': video_url,
  2920. 'uploader': uploader,
  2921. 'upload_date': upload_date,
  2922. 'title': video_title,
  2923. 'ext': video_extension,
  2924. }]
  2925. class NBAIE(InfoExtractor):
  2926. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2927. IE_NAME = u'nba'
  2928. def report_extraction(self, video_id):
  2929. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2930. def _real_extract(self, url):
  2931. mobj = re.match(self._VALID_URL, url)
  2932. if mobj is None:
  2933. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2934. return
  2935. video_id = mobj.group(1)
  2936. if video_id.endswith('/index.html'):
  2937. video_id = video_id[:-len('/index.html')]
  2938. self.report_extraction(video_id)
  2939. try:
  2940. urlh = compat_urllib_request.urlopen(url)
  2941. webpage_bytes = urlh.read()
  2942. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2943. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2944. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2945. return
  2946. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2947. def _findProp(rexp, default=None):
  2948. m = re.search(rexp, webpage)
  2949. if m:
  2950. return unescapeHTML(m.group(1))
  2951. else:
  2952. return default
  2953. shortened_video_id = video_id.rpartition('/')[2]
  2954. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2955. info = {
  2956. 'id': shortened_video_id,
  2957. 'url': video_url,
  2958. 'ext': 'mp4',
  2959. 'title': title,
  2960. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2961. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2962. }
  2963. return [info]
  2964. class JustinTVIE(InfoExtractor):
  2965. """Information extractor for justin.tv and twitch.tv"""
  2966. # TODO: One broadcast may be split into multiple videos. The key
  2967. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2968. # starts at 1 and increases. Can we treat all parts as one video?
  2969. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2970. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  2971. _JUSTIN_PAGE_LIMIT = 100
  2972. IE_NAME = u'justin.tv'
  2973. def report_extraction(self, file_id):
  2974. """Report information extraction."""
  2975. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2976. def report_download_page(self, channel, offset):
  2977. """Report attempt to download a single page of videos."""
  2978. self._downloader.to_screen(u'[%s] %s: Downloading video information from %d to %d' %
  2979. (self.IE_NAME, channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  2980. # Return count of items, list of *valid* items
  2981. def _parse_page(self, url):
  2982. try:
  2983. urlh = compat_urllib_request.urlopen(url)
  2984. webpage_bytes = urlh.read()
  2985. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2986. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2987. self._downloader.trouble(u'ERROR: unable to download video info JSON: %s' % compat_str(err))
  2988. return
  2989. response = json.loads(webpage)
  2990. info = []
  2991. for clip in response:
  2992. video_url = clip['video_file_url']
  2993. if video_url:
  2994. video_extension = os.path.splitext(video_url)[1][1:]
  2995. video_date = re.sub('-', '', clip['created_on'][:10])
  2996. info.append({
  2997. 'id': clip['id'],
  2998. 'url': video_url,
  2999. 'title': clip['title'],
  3000. 'uploader': clip.get('user_id', clip.get('channel_id')),
  3001. 'upload_date': video_date,
  3002. 'ext': video_extension,
  3003. })
  3004. return (len(response), info)
  3005. def _real_extract(self, url):
  3006. mobj = re.match(self._VALID_URL, url)
  3007. if mobj is None:
  3008. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3009. return
  3010. api = 'http://api.justin.tv'
  3011. video_id = mobj.group(mobj.lastindex)
  3012. paged = False
  3013. if mobj.lastindex == 1:
  3014. paged = True
  3015. api += '/channel/archives/%s.json'
  3016. else:
  3017. api += '/clip/show/%s.json'
  3018. api = api % (video_id,)
  3019. self.report_extraction(video_id)
  3020. info = []
  3021. offset = 0
  3022. limit = self._JUSTIN_PAGE_LIMIT
  3023. while True:
  3024. if paged:
  3025. self.report_download_page(video_id, offset)
  3026. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  3027. page_count, page_info = self._parse_page(page_url)
  3028. info.extend(page_info)
  3029. if not paged or page_count != limit:
  3030. break
  3031. offset += limit
  3032. return info
  3033. class FunnyOrDieIE(InfoExtractor):
  3034. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  3035. IE_NAME = u'FunnyOrDie'
  3036. def report_extraction(self, video_id):
  3037. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3038. def _real_extract(self, url):
  3039. mobj = re.match(self._VALID_URL, url)
  3040. if mobj is None:
  3041. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3042. return
  3043. video_id = mobj.group('id')
  3044. self.report_extraction(video_id)
  3045. try:
  3046. urlh = compat_urllib_request.urlopen(url)
  3047. webpage_bytes = urlh.read()
  3048. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3049. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3050. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  3051. return
  3052. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  3053. if not m:
  3054. self._downloader.trouble(u'ERROR: unable to find video information')
  3055. video_url = unescapeHTML(m.group('url'))
  3056. m = re.search(r"class='player_page_h1'>\s+<a.*?>(?P<title>.*?)</a>", webpage)
  3057. if not m:
  3058. self._downloader.trouble(u'Cannot find video title')
  3059. title = unescapeHTML(m.group('title'))
  3060. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3061. if m:
  3062. desc = unescapeHTML(m.group('desc'))
  3063. else:
  3064. desc = None
  3065. info = {
  3066. 'id': video_id,
  3067. 'url': video_url,
  3068. 'ext': 'mp4',
  3069. 'title': title,
  3070. 'description': desc,
  3071. }
  3072. return [info]
  3073. class TweetReelIE(InfoExtractor):
  3074. _VALID_URL = r'^(?:https?://)?(?:www\.)?tweetreel\.com/[?](?P<id>[0-9a-z]+)$'
  3075. def report_extraction(self, video_id):
  3076. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3077. def _real_extract(self, url):
  3078. mobj = re.match(self._VALID_URL, url)
  3079. if mobj is None:
  3080. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3081. return
  3082. video_id = mobj.group('id')
  3083. self.report_extraction(video_id)
  3084. try:
  3085. urlh = compat_urllib_request.urlopen(url)
  3086. webpage_bytes = urlh.read()
  3087. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3088. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3089. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  3090. return
  3091. m = re.search(r'<div id="left" status_id="([0-9]+)">', webpage)
  3092. if not m:
  3093. self._downloader.trouble(u'ERROR: Cannot find status ID')
  3094. status_id = m.group(1)
  3095. m = re.search(r'<div class="tweet_text">(.*?)</div>', webpage, flags=re.DOTALL)
  3096. if not m:
  3097. self._downloader.trouble(u'WARNING: Cannot find description')
  3098. desc = unescapeHTML(re.sub('<a.*?</a>', '', m.group(1))).strip()
  3099. m = re.search(r'<div class="tweet_info">.*?from <a target="_blank" href="https?://twitter.com/(?P<uploader_id>.+?)">(?P<uploader>.+?)</a>', webpage, flags=re.DOTALL)
  3100. if not m:
  3101. self._downloader.trouble(u'ERROR: Cannot find uploader')
  3102. uploader = unescapeHTML(m.group('uploader'))
  3103. uploader_id = unescapeHTML(m.group('uploader_id'))
  3104. m = re.search(r'<span unixtime="([0-9]+)"', webpage)
  3105. if not m:
  3106. self._downloader.trouble(u'ERROR: Cannot find upload date')
  3107. upload_date = datetime.datetime.fromtimestamp(int(m.group(1))).strftime('%Y%m%d')
  3108. title = desc
  3109. video_url = 'http://files.tweetreel.com/video/' + status_id + '.mov'
  3110. info = {
  3111. 'id': video_id,
  3112. 'url': video_url,
  3113. 'ext': 'mov',
  3114. 'title': title,
  3115. 'description': desc,
  3116. 'uploader': uploader,
  3117. 'uploader_id': uploader_id,
  3118. 'internal_id': status_id,
  3119. 'upload_date': upload_date
  3120. }
  3121. return [info]
  3122. class SteamIE(InfoExtractor):
  3123. _VALID_URL = r"""http://store.steampowered.com/
  3124. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  3125. (?P<gameID>\d+)/?
  3126. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  3127. """
  3128. IE_NAME = u'Steam'
  3129. def suitable(self, url):
  3130. """Receives a URL and returns True if suitable for this IE."""
  3131. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  3132. def report_download_video_page(self, game_id):
  3133. self._downloader.to_screen(u'[%s] %s: Downloading video page' % (self.IE_NAME, game_id))
  3134. def _real_extract(self, url):
  3135. m = re.match(self._VALID_URL, url, re.VERBOSE)
  3136. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  3137. gameID = m.group('gameID')
  3138. videourl = 'http://store.steampowered.com/video/%s/' % gameID
  3139. try:
  3140. self.report_download_video_page(gameID)
  3141. urlh = compat_urllib_request.urlopen(videourl)
  3142. webpage_bytes = urlh.read()
  3143. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3144. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3145. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  3146. return
  3147. mweb = re.finditer(urlRE, webpage)
  3148. namesRE = r'<span class=\"title\">(?P<videoName>[\w:/\.\?=\+\s-]+)</span>'
  3149. titles = list(re.finditer(namesRE, webpage))
  3150. videos = []
  3151. i = 0
  3152. for vid in mweb:
  3153. video_id = vid.group('videoID')
  3154. title = titles[i].group('videoName')
  3155. video_url=vid.group('videoURL')
  3156. if not video_url:
  3157. self._downloader.trouble(u'ERROR: Cannot find video url for %s' % video_id)
  3158. i += 1
  3159. info = {
  3160. 'id':video_id,
  3161. 'url':video_url,
  3162. 'ext': 'flv',
  3163. 'title': title
  3164. }
  3165. videos.append(info)
  3166. return videos
  3167. class UstreamIE(InfoExtractor):
  3168. _VALID_URL = r'http://www.ustream.tv/recorded/(?P<videoID>\d+)'
  3169. IE_NAME = u'ustream'
  3170. def _real_extract(self, url):
  3171. m = re.match(self._VALID_URL, url)
  3172. video_id = m.group('videoID')
  3173. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  3174. try:
  3175. urlh = compat_urllib_request.urlopen(url)
  3176. webpage_bytes = urlh.read()
  3177. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3178. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3179. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  3180. return
  3181. m = re.search(r'data-title="(?P<title>.+)"',webpage)
  3182. title = m.group('title')
  3183. m = re.search(r'<a class="state" data-content-type="channel" data-content-id="(?P<uploader>\d+)"',webpage)
  3184. uploader = m.group('uploader')
  3185. info = {
  3186. 'id':video_id,
  3187. 'url':video_url,
  3188. 'ext': 'flv',
  3189. 'title': title,
  3190. 'uploader': uploader
  3191. }
  3192. return [info]
  3193. def gen_extractors():
  3194. """ Return a list of an instance of every supported extractor.
  3195. The order does matter; the first extractor matched is the one handling the URL.
  3196. """
  3197. return [
  3198. YoutubePlaylistIE(),
  3199. YoutubeChannelIE(),
  3200. YoutubeUserIE(),
  3201. YoutubeSearchIE(),
  3202. YoutubeIE(),
  3203. MetacafeIE(),
  3204. DailymotionIE(),
  3205. GoogleSearchIE(),
  3206. PhotobucketIE(),
  3207. YahooIE(),
  3208. YahooSearchIE(),
  3209. DepositFilesIE(),
  3210. FacebookIE(),
  3211. BlipTVUserIE(),
  3212. BlipTVIE(),
  3213. VimeoIE(),
  3214. MyVideoIE(),
  3215. ComedyCentralIE(),
  3216. EscapistIE(),
  3217. CollegeHumorIE(),
  3218. XVideosIE(),
  3219. SoundcloudIE(),
  3220. InfoQIE(),
  3221. MixcloudIE(),
  3222. StanfordOpenClassroomIE(),
  3223. MTVIE(),
  3224. YoukuIE(),
  3225. XNXXIE(),
  3226. GooglePlusIE(),
  3227. ArteTvIE(),
  3228. NBAIE(),
  3229. JustinTVIE(),
  3230. FunnyOrDieIE(),
  3231. TweetReelIE(),
  3232. SteamIE(),
  3233. UstreamIE(),
  3234. GenericIE()
  3235. ]