InfoExtractors.py 144 KB

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