InfoExtractors.py 96 KB

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