InfoExtractors.py 106 KB

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