InfoExtractors.py 97 KB

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