InfoExtractors.py 114 KB

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