InfoExtractors.py 121 KB

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