utils.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. class IDParser(HTMLParser.HTMLParser):
  64. """Modified HTMLParser that isolates a tag with the specified id"""
  65. def __init__(self, id):
  66. self.id = id
  67. self.result = None
  68. self.started = False
  69. self.depth = {}
  70. self.html = None
  71. self.watch_startpos = False
  72. HTMLParser.HTMLParser.__init__(self)
  73. def loads(self, html):
  74. self.html = html
  75. self.feed(html)
  76. self.close()
  77. def handle_starttag(self, tag, attrs):
  78. attrs = dict(attrs)
  79. if self.started:
  80. self.find_startpos(None)
  81. if 'id' in attrs and attrs['id'] == self.id:
  82. self.result = [tag]
  83. self.started = True
  84. self.watch_startpos = True
  85. if self.started:
  86. if not tag in self.depth: self.depth[tag] = 0
  87. self.depth[tag] += 1
  88. def handle_endtag(self, tag):
  89. if self.started:
  90. if tag in self.depth: self.depth[tag] -= 1
  91. if self.depth[self.result[0]] == 0:
  92. self.started = False
  93. self.result.append(self.getpos())
  94. def find_startpos(self, x):
  95. """Needed to put the start position of the result (self.result[1])
  96. after the opening tag with the requested id"""
  97. if self.watch_startpos:
  98. self.watch_startpos = False
  99. self.result.append(self.getpos())
  100. handle_entityref = handle_charref = handle_data = handle_comment = \
  101. handle_decl = handle_pi = unknown_decl = find_startpos
  102. def get_result(self):
  103. if self.result == None: return None
  104. if len(self.result) != 3: return None
  105. lines = self.html.split('\n')
  106. lines = lines[self.result[1][0]-1:self.result[2][0]]
  107. lines[0] = lines[0][self.result[1][1]:]
  108. if len(lines) == 1:
  109. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  110. lines[-1] = lines[-1][:self.result[2][1]]
  111. return '\n'.join(lines).strip()
  112. def get_element_by_id(id, html):
  113. """Return the content of the tag with the specified id in the passed HTML document"""
  114. parser = IDParser(id)
  115. try:
  116. parser.loads(html)
  117. except HTMLParser.HTMLParseError:
  118. pass
  119. return parser.get_result()
  120. def clean_html(html):
  121. """Clean an HTML snippet into a readable string"""
  122. # Newline vs <br />
  123. html = html.replace('\n', ' ')
  124. html = re.sub('\s*<\s*br\s*/?\s*>\s*', '\n', html)
  125. # Strip html tags
  126. html = re.sub('<.*?>', '', html)
  127. # Replace html entities
  128. html = unescapeHTML(html)
  129. return html
  130. def sanitize_title(utitle):
  131. """Sanitizes a video title so it could be used as part of a filename."""
  132. utitle = unescapeHTML(utitle)
  133. return utitle.replace(unicode(os.sep), u'%')
  134. def sanitize_open(filename, open_mode):
  135. """Try to open the given filename, and slightly tweak it if this fails.
  136. Attempts to open the given filename. If this fails, it tries to change
  137. the filename slightly, step by step, until it's either able to open it
  138. or it fails and raises a final exception, like the standard open()
  139. function.
  140. It returns the tuple (stream, definitive_file_name).
  141. """
  142. try:
  143. if filename == u'-':
  144. if sys.platform == 'win32':
  145. import msvcrt
  146. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  147. return (sys.stdout, filename)
  148. stream = open(encodeFilename(filename), open_mode)
  149. return (stream, filename)
  150. except (IOError, OSError), err:
  151. # In case of error, try to remove win32 forbidden chars
  152. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  153. # An exception here should be caught in the caller
  154. stream = open(encodeFilename(filename), open_mode)
  155. return (stream, filename)
  156. def timeconvert(timestr):
  157. """Convert RFC 2822 defined time string into system timestamp"""
  158. timestamp = None
  159. timetuple = email.utils.parsedate_tz(timestr)
  160. if timetuple is not None:
  161. timestamp = email.utils.mktime_tz(timetuple)
  162. return timestamp
  163. def simplify_title(title):
  164. expr = re.compile(ur'[^\w\d_\-]+', flags=re.UNICODE)
  165. return expr.sub(u'_', title).strip(u'_')
  166. def orderedSet(iterable):
  167. """ Remove all duplicates from the input iterable """
  168. res = []
  169. for el in iterable:
  170. if el not in res:
  171. res.append(el)
  172. return res
  173. def unescapeHTML(s):
  174. """
  175. @param s a string (of type unicode)
  176. """
  177. assert type(s) == type(u'')
  178. result = re.sub(ur'(?u)&(.+?);', htmlentity_transform, s)
  179. return result
  180. def encodeFilename(s):
  181. """
  182. @param s The name of the file (of type unicode)
  183. """
  184. assert type(s) == type(u'')
  185. if sys.platform == 'win32' and sys.getwindowsversion().major >= 5:
  186. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  187. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  188. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  189. return s
  190. else:
  191. return s.encode(sys.getfilesystemencoding(), 'ignore')
  192. class DownloadError(Exception):
  193. """Download Error exception.
  194. This exception may be thrown by FileDownloader objects if they are not
  195. configured to continue on errors. They will contain the appropriate
  196. error message.
  197. """
  198. pass
  199. class SameFileError(Exception):
  200. """Same File exception.
  201. This exception will be thrown by FileDownloader objects if they detect
  202. multiple files would have to be downloaded to the same file on disk.
  203. """
  204. pass
  205. class PostProcessingError(Exception):
  206. """Post Processing exception.
  207. This exception may be raised by PostProcessor's .run() method to
  208. indicate an error in the postprocessing task.
  209. """
  210. pass
  211. class MaxDownloadsReached(Exception):
  212. """ --max-downloads limit has been reached. """
  213. pass
  214. class UnavailableVideoError(Exception):
  215. """Unavailable Format exception.
  216. This exception will be thrown when a video is requested
  217. in a format that is not available for that video.
  218. """
  219. pass
  220. class ContentTooShortError(Exception):
  221. """Content Too Short exception.
  222. This exception may be raised by FileDownloader objects when a file they
  223. download is too small for what the server announced first, indicating
  224. the connection was probably interrupted.
  225. """
  226. # Both in bytes
  227. downloaded = None
  228. expected = None
  229. def __init__(self, downloaded, expected):
  230. self.downloaded = downloaded
  231. self.expected = expected
  232. class YoutubeDLHandler(urllib2.HTTPHandler):
  233. """Handler for HTTP requests and responses.
  234. This class, when installed with an OpenerDirector, automatically adds
  235. the standard headers to every HTTP request and handles gzipped and
  236. deflated responses from web servers. If compression is to be avoided in
  237. a particular request, the original request in the program code only has
  238. to include the HTTP header "Youtubedl-No-Compression", which will be
  239. removed before making the real request.
  240. Part of this code was copied from:
  241. http://techknack.net/python-urllib2-handlers/
  242. Andrew Rowls, the author of that code, agreed to release it to the
  243. public domain.
  244. """
  245. @staticmethod
  246. def deflate(data):
  247. try:
  248. return zlib.decompress(data, -zlib.MAX_WBITS)
  249. except zlib.error:
  250. return zlib.decompress(data)
  251. @staticmethod
  252. def addinfourl_wrapper(stream, headers, url, code):
  253. if hasattr(urllib2.addinfourl, 'getcode'):
  254. return urllib2.addinfourl(stream, headers, url, code)
  255. ret = urllib2.addinfourl(stream, headers, url)
  256. ret.code = code
  257. return ret
  258. def http_request(self, req):
  259. for h in std_headers:
  260. if h in req.headers:
  261. del req.headers[h]
  262. req.add_header(h, std_headers[h])
  263. if 'Youtubedl-no-compression' in req.headers:
  264. if 'Accept-encoding' in req.headers:
  265. del req.headers['Accept-encoding']
  266. del req.headers['Youtubedl-no-compression']
  267. return req
  268. def http_response(self, req, resp):
  269. old_resp = resp
  270. # gzip
  271. if resp.headers.get('Content-encoding', '') == 'gzip':
  272. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  273. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  274. resp.msg = old_resp.msg
  275. # deflate
  276. if resp.headers.get('Content-encoding', '') == 'deflate':
  277. gz = StringIO.StringIO(self.deflate(resp.read()))
  278. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  279. resp.msg = old_resp.msg
  280. return resp