utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 email.utils
  12. import json
  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:10.0) Gecko/20100101 Firefox/10.0',
  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. try:
  25. compat_str = unicode # Python 2
  26. except NameError:
  27. compat_str = str
  28. try:
  29. import urllib.request as compat_urllib_request
  30. except ImportError: # Python 2
  31. import urllib2 as compat_urllib_request
  32. try:
  33. import urllib.error as compat_urllib_error
  34. except ImportError: # Python 2
  35. import urllib2 as compat_urllib_error
  36. try:
  37. import urllib.parse as compat_urllib_parse
  38. except ImportError: # Python 2
  39. import urllib2 as compat_urllib_parse
  40. try:
  41. import http.cookiejar as compat_cookiejar
  42. except ImportError: # Python 2
  43. import cookielib as compat_cookiejar
  44. def preferredencoding():
  45. """Get preferred encoding.
  46. Returns the best encoding scheme for the system, based on
  47. locale.getpreferredencoding() and some further tweaks.
  48. """
  49. try:
  50. pref = locale.getpreferredencoding()
  51. u'TEST'.encode(pref)
  52. except:
  53. pref = 'UTF-8'
  54. return pref
  55. def htmlentity_transform(matchobj):
  56. """Transforms an HTML entity to a character.
  57. This function receives a match object and is intended to be used with
  58. the re.sub() function.
  59. """
  60. entity = matchobj.group(1)
  61. # Known non-numeric HTML entity
  62. if entity in htmlentitydefs.name2codepoint:
  63. return unichr(htmlentitydefs.name2codepoint[entity])
  64. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  65. if mobj is not None:
  66. numstr = mobj.group(1)
  67. if numstr.startswith(u'x'):
  68. base = 16
  69. numstr = u'0%s' % numstr
  70. else:
  71. base = 10
  72. return unichr(int(numstr, base))
  73. # Unknown entity in name, return its literal representation
  74. return (u'&%s;' % entity)
  75. HTMLParser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  76. class IDParser(HTMLParser.HTMLParser):
  77. """Modified HTMLParser that isolates a tag with the specified id"""
  78. def __init__(self, id):
  79. self.id = id
  80. self.result = None
  81. self.started = False
  82. self.depth = {}
  83. self.html = None
  84. self.watch_startpos = False
  85. self.error_count = 0
  86. HTMLParser.HTMLParser.__init__(self)
  87. def error(self, message):
  88. if self.error_count > 10 or self.started:
  89. raise HTMLParser.HTMLParseError(message, self.getpos())
  90. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  91. self.error_count += 1
  92. self.goahead(1)
  93. def loads(self, html):
  94. self.html = html
  95. self.feed(html)
  96. self.close()
  97. def handle_starttag(self, tag, attrs):
  98. attrs = dict(attrs)
  99. if self.started:
  100. self.find_startpos(None)
  101. if 'id' in attrs and attrs['id'] == self.id:
  102. self.result = [tag]
  103. self.started = True
  104. self.watch_startpos = True
  105. if self.started:
  106. if not tag in self.depth: self.depth[tag] = 0
  107. self.depth[tag] += 1
  108. def handle_endtag(self, tag):
  109. if self.started:
  110. if tag in self.depth: self.depth[tag] -= 1
  111. if self.depth[self.result[0]] == 0:
  112. self.started = False
  113. self.result.append(self.getpos())
  114. def find_startpos(self, x):
  115. """Needed to put the start position of the result (self.result[1])
  116. after the opening tag with the requested id"""
  117. if self.watch_startpos:
  118. self.watch_startpos = False
  119. self.result.append(self.getpos())
  120. handle_entityref = handle_charref = handle_data = handle_comment = \
  121. handle_decl = handle_pi = unknown_decl = find_startpos
  122. def get_result(self):
  123. if self.result is None:
  124. return None
  125. if len(self.result) != 3:
  126. return None
  127. lines = self.html.split('\n')
  128. lines = lines[self.result[1][0]-1:self.result[2][0]]
  129. lines[0] = lines[0][self.result[1][1]:]
  130. if len(lines) == 1:
  131. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  132. lines[-1] = lines[-1][:self.result[2][1]]
  133. return '\n'.join(lines).strip()
  134. def get_element_by_id(id, html):
  135. """Return the content of the tag with the specified id in the passed HTML document"""
  136. parser = IDParser(id)
  137. try:
  138. parser.loads(html)
  139. except HTMLParser.HTMLParseError:
  140. pass
  141. return parser.get_result()
  142. def clean_html(html):
  143. """Clean an HTML snippet into a readable string"""
  144. # Newline vs <br />
  145. html = html.replace('\n', ' ')
  146. html = re.sub('\s*<\s*br\s*/?\s*>\s*', '\n', html)
  147. # Strip html tags
  148. html = re.sub('<.*?>', '', html)
  149. # Replace html entities
  150. html = unescapeHTML(html)
  151. return html
  152. def sanitize_open(filename, open_mode):
  153. """Try to open the given filename, and slightly tweak it if this fails.
  154. Attempts to open the given filename. If this fails, it tries to change
  155. the filename slightly, step by step, until it's either able to open it
  156. or it fails and raises a final exception, like the standard open()
  157. function.
  158. It returns the tuple (stream, definitive_file_name).
  159. """
  160. try:
  161. if filename == u'-':
  162. if sys.platform == 'win32':
  163. import msvcrt
  164. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  165. return (sys.stdout, filename)
  166. stream = open(encodeFilename(filename), open_mode)
  167. return (stream, filename)
  168. except (IOError, OSError) as err:
  169. # In case of error, try to remove win32 forbidden chars
  170. filename = re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', filename)
  171. # An exception here should be caught in the caller
  172. stream = open(encodeFilename(filename), open_mode)
  173. return (stream, filename)
  174. def timeconvert(timestr):
  175. """Convert RFC 2822 defined time string into system timestamp"""
  176. timestamp = None
  177. timetuple = email.utils.parsedate_tz(timestr)
  178. if timetuple is not None:
  179. timestamp = email.utils.mktime_tz(timetuple)
  180. return timestamp
  181. def sanitize_filename(s, restricted=False):
  182. """Sanitizes a string so it could be used as part of a filename.
  183. If restricted is set, use a stricter subset of allowed characters.
  184. """
  185. def replace_insane(char):
  186. if char == '?' or ord(char) < 32 or ord(char) == 127:
  187. return ''
  188. elif char == '"':
  189. return '' if restricted else '\''
  190. elif char == ':':
  191. return '_-' if restricted else ' -'
  192. elif char in '\\/|*<>':
  193. return '_'
  194. if restricted and (char in '!&\'' or char.isspace()):
  195. return '_'
  196. if restricted and ord(char) > 127:
  197. return '_'
  198. return char
  199. result = u''.join(map(replace_insane, s))
  200. while '__' in result:
  201. result = result.replace('__', '_')
  202. result = result.strip('_')
  203. # Common case of "Foreign band name - English song title"
  204. if restricted and result.startswith('-_'):
  205. result = result[2:]
  206. if not result:
  207. result = '_'
  208. return result
  209. def orderedSet(iterable):
  210. """ Remove all duplicates from the input iterable """
  211. res = []
  212. for el in iterable:
  213. if el not in res:
  214. res.append(el)
  215. return res
  216. def unescapeHTML(s):
  217. """
  218. @param s a string
  219. """
  220. assert type(s) == type(u'')
  221. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  222. return result
  223. def encodeFilename(s):
  224. """
  225. @param s The name of the file
  226. """
  227. assert type(s) == type(u'')
  228. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  229. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  230. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  231. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  232. return s
  233. else:
  234. return s.encode(sys.getfilesystemencoding(), 'ignore')
  235. class DownloadError(Exception):
  236. """Download Error exception.
  237. This exception may be thrown by FileDownloader objects if they are not
  238. configured to continue on errors. They will contain the appropriate
  239. error message.
  240. """
  241. pass
  242. class SameFileError(Exception):
  243. """Same File exception.
  244. This exception will be thrown by FileDownloader objects if they detect
  245. multiple files would have to be downloaded to the same file on disk.
  246. """
  247. pass
  248. class PostProcessingError(Exception):
  249. """Post Processing exception.
  250. This exception may be raised by PostProcessor's .run() method to
  251. indicate an error in the postprocessing task.
  252. """
  253. pass
  254. class MaxDownloadsReached(Exception):
  255. """ --max-downloads limit has been reached. """
  256. pass
  257. class UnavailableVideoError(Exception):
  258. """Unavailable Format exception.
  259. This exception will be thrown when a video is requested
  260. in a format that is not available for that video.
  261. """
  262. pass
  263. class ContentTooShortError(Exception):
  264. """Content Too Short exception.
  265. This exception may be raised by FileDownloader objects when a file they
  266. download is too small for what the server announced first, indicating
  267. the connection was probably interrupted.
  268. """
  269. # Both in bytes
  270. downloaded = None
  271. expected = None
  272. def __init__(self, downloaded, expected):
  273. self.downloaded = downloaded
  274. self.expected = expected
  275. class Trouble(Exception):
  276. """Trouble helper exception
  277. This is an exception to be handled with
  278. FileDownloader.trouble
  279. """
  280. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  281. """Handler for HTTP requests and responses.
  282. This class, when installed with an OpenerDirector, automatically adds
  283. the standard headers to every HTTP request and handles gzipped and
  284. deflated responses from web servers. If compression is to be avoided in
  285. a particular request, the original request in the program code only has
  286. to include the HTTP header "Youtubedl-No-Compression", which will be
  287. removed before making the real request.
  288. Part of this code was copied from:
  289. http://techknack.net/python-urllib2-handlers/
  290. Andrew Rowls, the author of that code, agreed to release it to the
  291. public domain.
  292. """
  293. @staticmethod
  294. def deflate(data):
  295. try:
  296. return zlib.decompress(data, -zlib.MAX_WBITS)
  297. except zlib.error:
  298. return zlib.decompress(data)
  299. @staticmethod
  300. def addinfourl_wrapper(stream, headers, url, code):
  301. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  302. return compat_urllib_request.addinfourl(stream, headers, url, code)
  303. ret = compat_urllib_request.addinfourl(stream, headers, url)
  304. ret.code = code
  305. return ret
  306. def http_request(self, req):
  307. for h in std_headers:
  308. if h in req.headers:
  309. del req.headers[h]
  310. req.add_header(h, std_headers[h])
  311. if 'Youtubedl-no-compression' in req.headers:
  312. if 'Accept-encoding' in req.headers:
  313. del req.headers['Accept-encoding']
  314. del req.headers['Youtubedl-no-compression']
  315. return req
  316. def http_response(self, req, resp):
  317. old_resp = resp
  318. # gzip
  319. if resp.headers.get('Content-encoding', '') == 'gzip':
  320. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  321. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  322. resp.msg = old_resp.msg
  323. # deflate
  324. if resp.headers.get('Content-encoding', '') == 'deflate':
  325. gz = StringIO.StringIO(self.deflate(resp.read()))
  326. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  327. resp.msg = old_resp.msg
  328. return resp