InfoExtractors.py 112 KB

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