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.

267 lines
7.2 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. try:
  18. import json
  19. except ImportError: # Python <2.6, use trivialjson (https://github.com/phihag/trivialjson):
  20. import trivialjson as json
  21. std_headers = {
  22. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:5.0.1) Gecko/20100101 Firefox/5.0.1',
  23. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  24. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  25. 'Accept-Encoding': 'gzip, deflate',
  26. 'Accept-Language': 'en-us,en;q=0.5',
  27. }
  28. def preferredencoding():
  29. """Get preferred encoding.
  30. Returns the best encoding scheme for the system, based on
  31. locale.getpreferredencoding() and some further tweaks.
  32. """
  33. def yield_preferredencoding():
  34. try:
  35. pref = locale.getpreferredencoding()
  36. u'TEST'.encode(pref)
  37. except:
  38. pref = 'UTF-8'
  39. while True:
  40. yield pref
  41. return yield_preferredencoding().next()
  42. def htmlentity_transform(matchobj):
  43. """Transforms an HTML entity to a Unicode character.
  44. This function receives a match object and is intended to be used with
  45. the re.sub() function.
  46. """
  47. entity = matchobj.group(1)
  48. # Known non-numeric HTML entity
  49. if entity in htmlentitydefs.name2codepoint:
  50. return unichr(htmlentitydefs.name2codepoint[entity])
  51. # Unicode character
  52. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  53. if mobj is not None:
  54. numstr = mobj.group(1)
  55. if numstr.startswith(u'x'):
  56. base = 16
  57. numstr = u'0%s' % numstr
  58. else:
  59. base = 10
  60. return unichr(long(numstr, base))
  61. # Unknown entity in name, return its literal representation
  62. return (u'&%s;' % entity)
  63. def sanitize_title(utitle):
  64. """Sanitizes a video title so it could be used as part of a filename."""
  65. utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
  66. return utitle.replace(unicode(os.sep), u'%')
  67. def sanitize_open(filename, open_mode):
  68. """Try to open the given filename, and slightly tweak it if this fails.
  69. Attempts to open the given filename. If this fails, it tries to change
  70. the filename slightly, step by step, until it's either able to open it
  71. or it fails and raises a final exception, like the standard open()
  72. function.
  73. It returns the tuple (stream, definitive_file_name).
  74. """
  75. try:
  76. if filename == u'-':
  77. if sys.platform == 'win32':
  78. import msvcrt
  79. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  80. return (sys.stdout, filename)
  81. stream = open(encodeFilename(filename), open_mode)
  82. return (stream, filename)
  83. except (IOError, OSError), err:
  84. # In case of error, try to remove win32 forbidden chars
  85. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  86. # An exception here should be caught in the caller
  87. stream = open(encodeFilename(filename), open_mode)
  88. return (stream, filename)
  89. def timeconvert(timestr):
  90. """Convert RFC 2822 defined time string into system timestamp"""
  91. timestamp = None
  92. timetuple = email.utils.parsedate_tz(timestr)
  93. if timetuple is not None:
  94. timestamp = email.utils.mktime_tz(timetuple)
  95. return timestamp
  96. def simplify_title(title):
  97. expr = re.compile(ur'[^\w\d_\-]+', flags=re.UNICODE)
  98. return expr.sub(u'_', title).strip(u'_')
  99. def orderedSet(iterable):
  100. """ Remove all duplicates from the input iterable """
  101. res = []
  102. for el in iterable:
  103. if el not in res:
  104. res.append(el)
  105. return res
  106. def unescapeHTML(s):
  107. """
  108. @param s a string (of type unicode)
  109. """
  110. assert type(s) == type(u'')
  111. htmlParser = HTMLParser.HTMLParser()
  112. return htmlParser.unescape(s)
  113. def encodeFilename(s):
  114. """
  115. @param s The name of the file (of type unicode)
  116. """
  117. assert type(s) == type(u'')
  118. if sys.platform == 'win32' and sys.getwindowsversion().major >= 5:
  119. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  120. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  121. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  122. return s
  123. else:
  124. return s.encode(sys.getfilesystemencoding(), 'ignore')
  125. class DownloadError(Exception):
  126. """Download Error exception.
  127. This exception may be thrown by FileDownloader objects if they are not
  128. configured to continue on errors. They will contain the appropriate
  129. error message.
  130. """
  131. pass
  132. class SameFileError(Exception):
  133. """Same File exception.
  134. This exception will be thrown by FileDownloader objects if they detect
  135. multiple files would have to be downloaded to the same file on disk.
  136. """
  137. pass
  138. class PostProcessingError(Exception):
  139. """Post Processing exception.
  140. This exception may be raised by PostProcessor's .run() method to
  141. indicate an error in the postprocessing task.
  142. """
  143. pass
  144. class MaxDownloadsReached(Exception):
  145. """ --max-downloads limit has been reached. """
  146. pass
  147. class UnavailableVideoError(Exception):
  148. """Unavailable Format exception.
  149. This exception will be thrown when a video is requested
  150. in a format that is not available for that video.
  151. """
  152. pass
  153. class ContentTooShortError(Exception):
  154. """Content Too Short exception.
  155. This exception may be raised by FileDownloader objects when a file they
  156. download is too small for what the server announced first, indicating
  157. the connection was probably interrupted.
  158. """
  159. # Both in bytes
  160. downloaded = None
  161. expected = None
  162. def __init__(self, downloaded, expected):
  163. self.downloaded = downloaded
  164. self.expected = expected
  165. class YoutubeDLHandler(urllib2.HTTPHandler):
  166. """Handler for HTTP requests and responses.
  167. This class, when installed with an OpenerDirector, automatically adds
  168. the standard headers to every HTTP request and handles gzipped and
  169. deflated responses from web servers. If compression is to be avoided in
  170. a particular request, the original request in the program code only has
  171. to include the HTTP header "Youtubedl-No-Compression", which will be
  172. removed before making the real request.
  173. Part of this code was copied from:
  174. http://techknack.net/python-urllib2-handlers/
  175. Andrew Rowls, the author of that code, agreed to release it to the
  176. public domain.
  177. """
  178. @staticmethod
  179. def deflate(data):
  180. try:
  181. return zlib.decompress(data, -zlib.MAX_WBITS)
  182. except zlib.error:
  183. return zlib.decompress(data)
  184. @staticmethod
  185. def addinfourl_wrapper(stream, headers, url, code):
  186. if hasattr(urllib2.addinfourl, 'getcode'):
  187. return urllib2.addinfourl(stream, headers, url, code)
  188. ret = urllib2.addinfourl(stream, headers, url)
  189. ret.code = code
  190. return ret
  191. def http_request(self, req):
  192. for h in std_headers:
  193. if h in req.headers:
  194. del req.headers[h]
  195. req.add_header(h, std_headers[h])
  196. if 'Youtubedl-no-compression' in req.headers:
  197. if 'Accept-encoding' in req.headers:
  198. del req.headers['Accept-encoding']
  199. del req.headers['Youtubedl-no-compression']
  200. return req
  201. def http_response(self, req, resp):
  202. old_resp = resp
  203. # gzip
  204. if resp.headers.get('Content-encoding', '') == 'gzip':
  205. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  206. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  207. resp.msg = old_resp.msg
  208. # deflate
  209. if resp.headers.get('Content-encoding', '') == 'deflate':
  210. gz = StringIO.StringIO(self.deflate(resp.read()))
  211. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  212. resp.msg = old_resp.msg
  213. return resp