InfoExtractors.py 103 KB

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