InfoExtractors.py 106 KB

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