InfoExtractors.py 97 KB

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