InfoExtractors.py 97 KB

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