You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

375 lines
10 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import gzip
  4. import htmlentitydefs
  5. import HTMLParser
  6. import locale
  7. import os
  8. import re
  9. import sys
  10. import zlib
  11. import urllib2
  12. import email.utils
  13. try:
  14. import cStringIO as StringIO
  15. except ImportError:
  16. import StringIO
  17. std_headers = {
  18. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:5.0.1) Gecko/20100101 Firefox/5.0.1',
  19. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  20. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  21. 'Accept-Encoding': 'gzip, deflate',
  22. 'Accept-Language': 'en-us,en;q=0.5',
  23. }
  24. def preferredencoding():
  25. """Get preferred encoding.
  26. Returns the best encoding scheme for the system, based on
  27. locale.getpreferredencoding() and some further tweaks.
  28. """
  29. def yield_preferredencoding():
  30. try:
  31. pref = locale.getpreferredencoding()
  32. u'TEST'.encode(pref)
  33. except:
  34. pref = 'UTF-8'
  35. while True:
  36. yield pref
  37. return yield_preferredencoding().next()
  38. def htmlentity_transform(matchobj):
  39. """Transforms an HTML entity to a Unicode character.
  40. This function receives a match object and is intended to be used with
  41. the re.sub() function.
  42. """
  43. entity = matchobj.group(1)
  44. # Known non-numeric HTML entity
  45. if entity in htmlentitydefs.name2codepoint:
  46. return unichr(htmlentitydefs.name2codepoint[entity])
  47. # Unicode character
  48. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  49. if mobj is not None:
  50. numstr = mobj.group(1)
  51. if numstr.startswith(u'x'):
  52. base = 16
  53. numstr = u'0%s' % numstr
  54. else:
  55. base = 10
  56. return unichr(long(numstr, base))
  57. # Unknown entity in name, return its literal representation
  58. return (u'&%s;' % entity)
  59. def sanitize_title(utitle):
  60. """Sanitizes a video title so it could be used as part of a filename."""
  61. utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
  62. return utitle.replace(unicode(os.sep), u'%')
  63. def sanitize_open(filename, open_mode):
  64. """Try to open the given filename, and slightly tweak it if this fails.
  65. Attempts to open the given filename. If this fails, it tries to change
  66. the filename slightly, step by step, until it's either able to open it
  67. or it fails and raises a final exception, like the standard open()
  68. function.
  69. It returns the tuple (stream, definitive_file_name).
  70. """
  71. try:
  72. if filename == u'-':
  73. if sys.platform == 'win32':
  74. import msvcrt
  75. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  76. return (sys.stdout, filename)
  77. stream = open(encodeFilename(filename), open_mode)
  78. return (stream, filename)
  79. except (IOError, OSError), err:
  80. # In case of error, try to remove win32 forbidden chars
  81. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  82. # An exception here should be caught in the caller
  83. stream = open(encodeFilename(filename), open_mode)
  84. return (stream, filename)
  85. def timeconvert(timestr):
  86. """Convert RFC 2822 defined time string into system timestamp"""
  87. timestamp = None
  88. timetuple = email.utils.parsedate_tz(timestr)
  89. if timetuple is not None:
  90. timestamp = email.utils.mktime_tz(timetuple)
  91. return timestamp
  92. def simplify_title(title):
  93. expr = re.compile(ur'[^\w\d_\-]+', flags=re.UNICODE)
  94. return expr.sub(u'_', title).strip(u'_')
  95. def orderedSet(iterable):
  96. """ Remove all duplicates from the input iterable """
  97. res = []
  98. for el in iterable:
  99. if el not in res:
  100. res.append(el)
  101. return res
  102. def unescapeHTML(s):
  103. """
  104. @param s a string (of type unicode)
  105. """
  106. assert type(s) == type(u'')
  107. htmlParser = HTMLParser.HTMLParser()
  108. return htmlParser.unescape(s)
  109. def encodeFilename(s):
  110. """
  111. @param s The name of the file (of type unicode)
  112. """
  113. assert type(s) == type(u'')
  114. if sys.platform == 'win32' and sys.getwindowsversion().major >= 5:
  115. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  116. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  117. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  118. return s
  119. else:
  120. return s.encode(sys.getfilesystemencoding(), 'ignore')
  121. class DownloadError(Exception):
  122. """Download Error exception.
  123. This exception may be thrown by FileDownloader objects if they are not
  124. configured to continue on errors. They will contain the appropriate
  125. error message.
  126. """
  127. pass
  128. class SameFileError(Exception):
  129. """Same File exception.
  130. This exception will be thrown by FileDownloader objects if they detect
  131. multiple files would have to be downloaded to the same file on disk.
  132. """
  133. pass
  134. class PostProcessingError(Exception):
  135. """Post Processing exception.
  136. This exception may be raised by PostProcessor's .run() method to
  137. indicate an error in the postprocessing task.
  138. """
  139. pass
  140. class MaxDownloadsReached(Exception):
  141. """ --max-downloads limit has been reached. """
  142. pass
  143. class UnavailableVideoError(Exception):
  144. """Unavailable Format exception.
  145. This exception will be thrown when a video is requested
  146. in a format that is not available for that video.
  147. """
  148. pass
  149. class ContentTooShortError(Exception):
  150. """Content Too Short exception.
  151. This exception may be raised by FileDownloader objects when a file they
  152. download is too small for what the server announced first, indicating
  153. the connection was probably interrupted.
  154. """
  155. # Both in bytes
  156. downloaded = None
  157. expected = None
  158. def __init__(self, downloaded, expected):
  159. self.downloaded = downloaded
  160. self.expected = expected
  161. class YoutubeDLHandler(urllib2.HTTPHandler):
  162. """Handler for HTTP requests and responses.
  163. This class, when installed with an OpenerDirector, automatically adds
  164. the standard headers to every HTTP request and handles gzipped and
  165. deflated responses from web servers. If compression is to be avoided in
  166. a particular request, the original request in the program code only has
  167. to include the HTTP header "Youtubedl-No-Compression", which will be
  168. removed before making the real request.
  169. Part of this code was copied from:
  170. http://techknack.net/python-urllib2-handlers/
  171. Andrew Rowls, the author of that code, agreed to release it to the
  172. public domain.
  173. """
  174. @staticmethod
  175. def deflate(data):
  176. try:
  177. return zlib.decompress(data, -zlib.MAX_WBITS)
  178. except zlib.error:
  179. return zlib.decompress(data)
  180. @staticmethod
  181. def addinfourl_wrapper(stream, headers, url, code):
  182. if hasattr(urllib2.addinfourl, 'getcode'):
  183. return urllib2.addinfourl(stream, headers, url, code)
  184. ret = urllib2.addinfourl(stream, headers, url)
  185. ret.code = code
  186. return ret
  187. def http_request(self, req):
  188. for h in std_headers:
  189. if h in req.headers:
  190. del req.headers[h]
  191. req.add_header(h, std_headers[h])
  192. if 'Youtubedl-no-compression' in req.headers:
  193. if 'Accept-encoding' in req.headers:
  194. del req.headers['Accept-encoding']
  195. del req.headers['Youtubedl-no-compression']
  196. return req
  197. def http_response(self, req, resp):
  198. old_resp = resp
  199. # gzip
  200. if resp.headers.get('Content-encoding', '') == 'gzip':
  201. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  202. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  203. resp.msg = old_resp.msg
  204. # deflate
  205. if resp.headers.get('Content-encoding', '') == 'deflate':
  206. gz = StringIO.StringIO(self.deflate(resp.read()))
  207. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  208. resp.msg = old_resp.msg
  209. return resp
  210. try:
  211. import json
  212. except ImportError: # Python <2.6, use trivialjson (https://github.com/phihag/trivialjson):
  213. import re
  214. class json(object):
  215. @staticmethod
  216. def loads(s):
  217. s = s.decode('UTF-8')
  218. def raiseError(msg, i):
  219. raise ValueError(msg + ' at position ' + str(i) + ' of ' + repr(s) + ': ' + repr(s[i:]))
  220. def skipSpace(i, expectMore=True):
  221. while i < len(s) and s[i] in ' \t\r\n':
  222. i += 1
  223. if expectMore:
  224. if i >= len(s):
  225. raiseError('Premature end', i)
  226. return i
  227. def decodeEscape(match):
  228. esc = match.group(1)
  229. _STATIC = {
  230. '"': '"',
  231. '\\': '\\',
  232. '/': '/',
  233. 'b': unichr(0x8),
  234. 'f': unichr(0xc),
  235. 'n': '\n',
  236. 'r': '\r',
  237. 't': '\t',
  238. }
  239. if esc in _STATIC:
  240. return _STATIC[esc]
  241. if esc[0] == 'u':
  242. if len(esc) == 1+4:
  243. return unichr(int(esc[1:5], 16))
  244. if len(esc) == 5+6 and esc[5:7] == '\\u':
  245. hi = int(esc[1:5], 16)
  246. low = int(esc[7:11], 16)
  247. return unichr((hi - 0xd800) * 0x400 + low - 0xdc00 + 0x10000)
  248. raise ValueError('Unknown escape ' + str(esc))
  249. def parseString(i):
  250. i += 1
  251. e = i
  252. while True:
  253. e = s.index('"', e)
  254. bslashes = 0
  255. while s[e-bslashes-1] == '\\':
  256. bslashes += 1
  257. if bslashes % 2 == 1:
  258. e += 1
  259. continue
  260. break
  261. rexp = re.compile(r'\\(u[dD][89aAbB][0-9a-fA-F]{2}\\u[0-9a-fA-F]{4}|u[0-9a-fA-F]{4}|.|$)')
  262. stri = rexp.sub(decodeEscape, s[i:e])
  263. return (e+1,stri)
  264. def parseObj(i):
  265. i += 1
  266. res = {}
  267. i = skipSpace(i)
  268. if s[i] == '}': # Empty dictionary
  269. return (i+1,res)
  270. while True:
  271. if s[i] != '"':
  272. raiseError('Expected a string object key', i)
  273. i,key = parseString(i)
  274. i = skipSpace(i)
  275. if i >= len(s) or s[i] != ':':
  276. raiseError('Expected a colon', i)
  277. i,val = parse(i+1)
  278. res[key] = val
  279. i = skipSpace(i)
  280. if s[i] == '}':
  281. return (i+1, res)
  282. if s[i] != ',':
  283. raiseError('Expected comma or closing curly brace', i)
  284. i = skipSpace(i+1)
  285. def parseArray(i):
  286. res = []
  287. i = skipSpace(i+1)
  288. if s[i] == ']': # Empty array
  289. return (i+1,res)
  290. while True:
  291. i,val = parse(i)
  292. res.append(val)
  293. i = skipSpace(i) # Raise exception if premature end
  294. if s[i] == ']':
  295. return (i+1, res)
  296. if s[i] != ',':
  297. raiseError('Expected a comma or closing bracket', i)
  298. i = skipSpace(i+1)
  299. def parseDiscrete(i):
  300. for k,v in {'true': True, 'false': False, 'null': None}.items():
  301. if s.startswith(k, i):
  302. return (i+len(k), v)
  303. raiseError('Not a boolean (or null)', i)
  304. def parseNumber(i):
  305. mobj = re.match('^(-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][+-]?[0-9]+)?)', s[i:])
  306. if mobj is None:
  307. raiseError('Not a number', i)
  308. nums = mobj.group(1)
  309. if '.' in nums or 'e' in nums or 'E' in nums:
  310. return (i+len(nums), float(nums))
  311. return (i+len(nums), int(nums))
  312. CHARMAP = {'{': parseObj, '[': parseArray, '"': parseString, 't': parseDiscrete, 'f': parseDiscrete, 'n': parseDiscrete}
  313. def parse(i):
  314. i = skipSpace(i)
  315. i,res = CHARMAP.get(s[i], parseNumber)(i)
  316. i = skipSpace(i, False)
  317. return (i,res)
  318. i,res = parse(0)
  319. if i < len(s):
  320. raise ValueError('Extra data at end of input (index ' + str(i) + ' of ' + repr(s) + ': ' + repr(s[i:]) + ')')
  321. return res