utils.py 12 KB

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