InfoExtractors.py 151 KB

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