InfoExtractors.py 147 KB

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