InfoExtractors.py 147 KB

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