InfoExtractors.py 121 KB

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