InfoExtractors.py 122 KB

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