InfoExtractors.py 146 KB

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