InfoExtractors.py 156 KB

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