InfoExtractors.py 97 KB

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