InfoExtractors.py 147 KB

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