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.

1399 lines
43 KiB

10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import calendar
  5. import codecs
  6. import contextlib
  7. import ctypes
  8. import datetime
  9. import email.utils
  10. import errno
  11. import gzip
  12. import itertools
  13. import io
  14. import json
  15. import locale
  16. import math
  17. import os
  18. import pipes
  19. import platform
  20. import re
  21. import ssl
  22. import socket
  23. import struct
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import traceback
  28. import xml.etree.ElementTree
  29. import zlib
  30. from .compat import (
  31. compat_chr,
  32. compat_getenv,
  33. compat_html_entities,
  34. compat_html_parser,
  35. compat_parse_qs,
  36. compat_str,
  37. compat_urllib_error,
  38. compat_urllib_parse,
  39. compat_urllib_parse_urlparse,
  40. compat_urllib_request,
  41. compat_urlparse,
  42. )
  43. # This is not clearly defined otherwise
  44. compiled_regex_type = type(re.compile(''))
  45. std_headers = {
  46. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  47. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  48. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  49. 'Accept-Encoding': 'gzip, deflate',
  50. 'Accept-Language': 'en-us,en;q=0.5',
  51. }
  52. def preferredencoding():
  53. """Get preferred encoding.
  54. Returns the best encoding scheme for the system, based on
  55. locale.getpreferredencoding() and some further tweaks.
  56. """
  57. try:
  58. pref = locale.getpreferredencoding()
  59. u'TEST'.encode(pref)
  60. except:
  61. pref = 'UTF-8'
  62. return pref
  63. def write_json_file(obj, fn):
  64. """ Encode obj as JSON and write it to fn, atomically """
  65. args = {
  66. 'suffix': '.tmp',
  67. 'prefix': os.path.basename(fn) + '.',
  68. 'dir': os.path.dirname(fn),
  69. 'delete': False,
  70. }
  71. # In Python 2.x, json.dump expects a bytestream.
  72. # In Python 3.x, it writes to a character stream
  73. if sys.version_info < (3, 0):
  74. args['mode'] = 'wb'
  75. else:
  76. args.update({
  77. 'mode': 'w',
  78. 'encoding': 'utf-8',
  79. })
  80. tf = tempfile.NamedTemporaryFile(**args)
  81. try:
  82. with tf:
  83. json.dump(obj, tf)
  84. os.rename(tf.name, fn)
  85. except:
  86. try:
  87. os.remove(tf.name)
  88. except OSError:
  89. pass
  90. raise
  91. if sys.version_info >= (2, 7):
  92. def find_xpath_attr(node, xpath, key, val):
  93. """ Find the xpath xpath[@key=val] """
  94. assert re.match(r'^[a-zA-Z-]+$', key)
  95. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  96. expr = xpath + u"[@%s='%s']" % (key, val)
  97. return node.find(expr)
  98. else:
  99. def find_xpath_attr(node, xpath, key, val):
  100. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  101. # .//node does not match if a node is a direct child of . !
  102. if isinstance(xpath, unicode):
  103. xpath = xpath.encode('ascii')
  104. for f in node.findall(xpath):
  105. if f.attrib.get(key) == val:
  106. return f
  107. return None
  108. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  109. # the namespace parameter
  110. def xpath_with_ns(path, ns_map):
  111. components = [c.split(':') for c in path.split('/')]
  112. replaced = []
  113. for c in components:
  114. if len(c) == 1:
  115. replaced.append(c[0])
  116. else:
  117. ns, tag = c
  118. replaced.append('{%s}%s' % (ns_map[ns], tag))
  119. return '/'.join(replaced)
  120. def xpath_text(node, xpath, name=None, fatal=False):
  121. if sys.version_info < (2, 7): # Crazy 2.6
  122. xpath = xpath.encode('ascii')
  123. n = node.find(xpath)
  124. if n is None:
  125. if fatal:
  126. name = xpath if name is None else name
  127. raise ExtractorError('Could not find XML element %s' % name)
  128. else:
  129. return None
  130. return n.text
  131. def get_element_by_id(id, html):
  132. """Return the content of the tag with the specified ID in the passed HTML document"""
  133. return get_element_by_attribute("id", id, html)
  134. def get_element_by_attribute(attribute, value, html):
  135. """Return the content of the tag with the specified attribute in the passed HTML document"""
  136. m = re.search(r'''(?xs)
  137. <([a-zA-Z0-9:._-]+)
  138. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  139. \s+%s=['"]?%s['"]?
  140. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  141. \s*>
  142. (?P<content>.*?)
  143. </\1>
  144. ''' % (re.escape(attribute), re.escape(value)), html)
  145. if not m:
  146. return None
  147. res = m.group('content')
  148. if res.startswith('"') or res.startswith("'"):
  149. res = res[1:-1]
  150. return unescapeHTML(res)
  151. def clean_html(html):
  152. """Clean an HTML snippet into a readable string"""
  153. # Newline vs <br />
  154. html = html.replace('\n', ' ')
  155. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  156. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  157. # Strip html tags
  158. html = re.sub('<.*?>', '', html)
  159. # Replace html entities
  160. html = unescapeHTML(html)
  161. return html.strip()
  162. def sanitize_open(filename, open_mode):
  163. """Try to open the given filename, and slightly tweak it if this fails.
  164. Attempts to open the given filename. If this fails, it tries to change
  165. the filename slightly, step by step, until it's either able to open it
  166. or it fails and raises a final exception, like the standard open()
  167. function.
  168. It returns the tuple (stream, definitive_file_name).
  169. """
  170. try:
  171. if filename == u'-':
  172. if sys.platform == 'win32':
  173. import msvcrt
  174. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  175. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  176. stream = open(encodeFilename(filename), open_mode)
  177. return (stream, filename)
  178. except (IOError, OSError) as err:
  179. if err.errno in (errno.EACCES,):
  180. raise
  181. # In case of error, try to remove win32 forbidden chars
  182. alt_filename = os.path.join(
  183. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  184. for path_part in os.path.split(filename)
  185. )
  186. if alt_filename == filename:
  187. raise
  188. else:
  189. # An exception here should be caught in the caller
  190. stream = open(encodeFilename(filename), open_mode)
  191. return (stream, alt_filename)
  192. def timeconvert(timestr):
  193. """Convert RFC 2822 defined time string into system timestamp"""
  194. timestamp = None
  195. timetuple = email.utils.parsedate_tz(timestr)
  196. if timetuple is not None:
  197. timestamp = email.utils.mktime_tz(timetuple)
  198. return timestamp
  199. def sanitize_filename(s, restricted=False, is_id=False):
  200. """Sanitizes a string so it could be used as part of a filename.
  201. If restricted is set, use a stricter subset of allowed characters.
  202. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  203. """
  204. def replace_insane(char):
  205. if char == '?' or ord(char) < 32 or ord(char) == 127:
  206. return ''
  207. elif char == '"':
  208. return '' if restricted else '\''
  209. elif char == ':':
  210. return '_-' if restricted else ' -'
  211. elif char in '\\/|*<>':
  212. return '_'
  213. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  214. return '_'
  215. if restricted and ord(char) > 127:
  216. return '_'
  217. return char
  218. result = u''.join(map(replace_insane, s))
  219. if not is_id:
  220. while '__' in result:
  221. result = result.replace('__', '_')
  222. result = result.strip('_')
  223. # Common case of "Foreign band name - English song title"
  224. if restricted and result.startswith('-_'):
  225. result = result[2:]
  226. if not result:
  227. result = '_'
  228. return result
  229. def orderedSet(iterable):
  230. """ Remove all duplicates from the input iterable """
  231. res = []
  232. for el in iterable:
  233. if el not in res:
  234. res.append(el)
  235. return res
  236. def _htmlentity_transform(entity):
  237. """Transforms an HTML entity to a character."""
  238. # Known non-numeric HTML entity
  239. if entity in compat_html_entities.name2codepoint:
  240. return compat_chr(compat_html_entities.name2codepoint[entity])
  241. mobj = re.match(r'#(x?[0-9]+)', entity)
  242. if mobj is not None:
  243. numstr = mobj.group(1)
  244. if numstr.startswith(u'x'):
  245. base = 16
  246. numstr = u'0%s' % numstr
  247. else:
  248. base = 10
  249. return compat_chr(int(numstr, base))
  250. # Unknown entity in name, return its literal representation
  251. return (u'&%s;' % entity)
  252. def unescapeHTML(s):
  253. if s is None:
  254. return None
  255. assert type(s) == compat_str
  256. return re.sub(
  257. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  258. def encodeFilename(s, for_subprocess=False):
  259. """
  260. @param s The name of the file
  261. """
  262. assert type(s) == compat_str
  263. # Python 3 has a Unicode API
  264. if sys.version_info >= (3, 0):
  265. return s
  266. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  267. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  268. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  269. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  270. if not for_subprocess:
  271. return s
  272. else:
  273. # For subprocess calls, encode with locale encoding
  274. # Refer to http://stackoverflow.com/a/9951851/35070
  275. encoding = preferredencoding()
  276. else:
  277. encoding = sys.getfilesystemencoding()
  278. if encoding is None:
  279. encoding = 'utf-8'
  280. return s.encode(encoding, 'ignore')
  281. def encodeArgument(s):
  282. if not isinstance(s, compat_str):
  283. # Legacy code that uses byte strings
  284. # Uncomment the following line after fixing all post processors
  285. #assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  286. s = s.decode('ascii')
  287. return encodeFilename(s, True)
  288. def decodeOption(optval):
  289. if optval is None:
  290. return optval
  291. if isinstance(optval, bytes):
  292. optval = optval.decode(preferredencoding())
  293. assert isinstance(optval, compat_str)
  294. return optval
  295. def formatSeconds(secs):
  296. if secs > 3600:
  297. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  298. elif secs > 60:
  299. return '%d:%02d' % (secs // 60, secs % 60)
  300. else:
  301. return '%d' % secs
  302. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  303. if sys.version_info < (3, 2):
  304. import httplib
  305. class HTTPSConnectionV3(httplib.HTTPSConnection):
  306. def __init__(self, *args, **kwargs):
  307. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  308. def connect(self):
  309. sock = socket.create_connection((self.host, self.port), self.timeout)
  310. if getattr(self, '_tunnel_host', False):
  311. self.sock = sock
  312. self._tunnel()
  313. try:
  314. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  315. except ssl.SSLError:
  316. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  317. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  318. def https_open(self, req):
  319. return self.do_open(HTTPSConnectionV3, req)
  320. return HTTPSHandlerV3(**kwargs)
  321. elif hasattr(ssl, 'create_default_context'): # Python >= 3.4
  322. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  323. context.options &= ~ssl.OP_NO_SSLv3 # Allow older, not-as-secure SSLv3
  324. if opts_no_check_certificate:
  325. context.verify_mode = ssl.CERT_NONE
  326. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  327. else: # Python < 3.4
  328. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  329. context.verify_mode = (ssl.CERT_NONE
  330. if opts_no_check_certificate
  331. else ssl.CERT_REQUIRED)
  332. context.set_default_verify_paths()
  333. try:
  334. context.load_default_certs()
  335. except AttributeError:
  336. pass # Python < 3.4
  337. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  338. class ExtractorError(Exception):
  339. """Error during info extraction."""
  340. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  341. """ tb, if given, is the original traceback (so that it can be printed out).
  342. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  343. """
  344. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  345. expected = True
  346. if video_id is not None:
  347. msg = video_id + ': ' + msg
  348. if cause:
  349. msg += u' (caused by %r)' % cause
  350. if not expected:
  351. msg = msg + u'; please report this issue on https://yt-dl.org/bug . Be sure to call youtube-dl with the --verbose flag and include its complete output. Make sure you are using the latest version; type youtube-dl -U to update.'
  352. super(ExtractorError, self).__init__(msg)
  353. self.traceback = tb
  354. self.exc_info = sys.exc_info() # preserve original exception
  355. self.cause = cause
  356. self.video_id = video_id
  357. def format_traceback(self):
  358. if self.traceback is None:
  359. return None
  360. return u''.join(traceback.format_tb(self.traceback))
  361. class RegexNotFoundError(ExtractorError):
  362. """Error when a regex didn't match"""
  363. pass
  364. class DownloadError(Exception):
  365. """Download Error exception.
  366. This exception may be thrown by FileDownloader objects if they are not
  367. configured to continue on errors. They will contain the appropriate
  368. error message.
  369. """
  370. def __init__(self, msg, exc_info=None):
  371. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  372. super(DownloadError, self).__init__(msg)
  373. self.exc_info = exc_info
  374. class SameFileError(Exception):
  375. """Same File exception.
  376. This exception will be thrown by FileDownloader objects if they detect
  377. multiple files would have to be downloaded to the same file on disk.
  378. """
  379. pass
  380. class PostProcessingError(Exception):
  381. """Post Processing exception.
  382. This exception may be raised by PostProcessor's .run() method to
  383. indicate an error in the postprocessing task.
  384. """
  385. def __init__(self, msg):
  386. self.msg = msg
  387. class MaxDownloadsReached(Exception):
  388. """ --max-downloads limit has been reached. """
  389. pass
  390. class UnavailableVideoError(Exception):
  391. """Unavailable Format exception.
  392. This exception will be thrown when a video is requested
  393. in a format that is not available for that video.
  394. """
  395. pass
  396. class ContentTooShortError(Exception):
  397. """Content Too Short exception.
  398. This exception may be raised by FileDownloader objects when a file they
  399. download is too small for what the server announced first, indicating
  400. the connection was probably interrupted.
  401. """
  402. # Both in bytes
  403. downloaded = None
  404. expected = None
  405. def __init__(self, downloaded, expected):
  406. self.downloaded = downloaded
  407. self.expected = expected
  408. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  409. """Handler for HTTP requests and responses.
  410. This class, when installed with an OpenerDirector, automatically adds
  411. the standard headers to every HTTP request and handles gzipped and
  412. deflated responses from web servers. If compression is to be avoided in
  413. a particular request, the original request in the program code only has
  414. to include the HTTP header "Youtubedl-No-Compression", which will be
  415. removed before making the real request.
  416. Part of this code was copied from:
  417. http://techknack.net/python-urllib2-handlers/
  418. Andrew Rowls, the author of that code, agreed to release it to the
  419. public domain.
  420. """
  421. @staticmethod
  422. def deflate(data):
  423. try:
  424. return zlib.decompress(data, -zlib.MAX_WBITS)
  425. except zlib.error:
  426. return zlib.decompress(data)
  427. @staticmethod
  428. def addinfourl_wrapper(stream, headers, url, code):
  429. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  430. return compat_urllib_request.addinfourl(stream, headers, url, code)
  431. ret = compat_urllib_request.addinfourl(stream, headers, url)
  432. ret.code = code
  433. return ret
  434. def http_request(self, req):
  435. for h, v in std_headers.items():
  436. if h not in req.headers:
  437. req.add_header(h, v)
  438. if 'Youtubedl-no-compression' in req.headers:
  439. if 'Accept-encoding' in req.headers:
  440. del req.headers['Accept-encoding']
  441. del req.headers['Youtubedl-no-compression']
  442. if 'Youtubedl-user-agent' in req.headers:
  443. if 'User-agent' in req.headers:
  444. del req.headers['User-agent']
  445. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  446. del req.headers['Youtubedl-user-agent']
  447. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  448. # Python 2.6 is brain-dead when it comes to fragments
  449. req._Request__original = req._Request__original.partition('#')[0]
  450. req._Request__r_type = req._Request__r_type.partition('#')[0]
  451. return req
  452. def http_response(self, req, resp):
  453. old_resp = resp
  454. # gzip
  455. if resp.headers.get('Content-encoding', '') == 'gzip':
  456. content = resp.read()
  457. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  458. try:
  459. uncompressed = io.BytesIO(gz.read())
  460. except IOError as original_ioerror:
  461. # There may be junk add the end of the file
  462. # See http://stackoverflow.com/q/4928560/35070 for details
  463. for i in range(1, 1024):
  464. try:
  465. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  466. uncompressed = io.BytesIO(gz.read())
  467. except IOError:
  468. continue
  469. break
  470. else:
  471. raise original_ioerror
  472. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  473. resp.msg = old_resp.msg
  474. # deflate
  475. if resp.headers.get('Content-encoding', '') == 'deflate':
  476. gz = io.BytesIO(self.deflate(resp.read()))
  477. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  478. resp.msg = old_resp.msg
  479. return resp
  480. https_request = http_request
  481. https_response = http_response
  482. def parse_iso8601(date_str, delimiter='T'):
  483. """ Return a UNIX timestamp from the given date """
  484. if date_str is None:
  485. return None
  486. m = re.search(
  487. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  488. date_str)
  489. if not m:
  490. timezone = datetime.timedelta()
  491. else:
  492. date_str = date_str[:-len(m.group(0))]
  493. if not m.group('sign'):
  494. timezone = datetime.timedelta()
  495. else:
  496. sign = 1 if m.group('sign') == '+' else -1
  497. timezone = datetime.timedelta(
  498. hours=sign * int(m.group('hours')),
  499. minutes=sign * int(m.group('minutes')))
  500. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  501. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  502. return calendar.timegm(dt.timetuple())
  503. def unified_strdate(date_str):
  504. """Return a string with the date in the format YYYYMMDD"""
  505. if date_str is None:
  506. return None
  507. upload_date = None
  508. #Replace commas
  509. date_str = date_str.replace(',', ' ')
  510. # %z (UTC offset) is only supported in python>=3.2
  511. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  512. format_expressions = [
  513. '%d %B %Y',
  514. '%d %b %Y',
  515. '%B %d %Y',
  516. '%b %d %Y',
  517. '%b %dst %Y %I:%M%p',
  518. '%b %dnd %Y %I:%M%p',
  519. '%b %dth %Y %I:%M%p',
  520. '%Y-%m-%d',
  521. '%Y/%m/%d',
  522. '%d.%m.%Y',
  523. '%d/%m/%Y',
  524. '%d/%m/%y',
  525. '%Y/%m/%d %H:%M:%S',
  526. '%d/%m/%Y %H:%M:%S',
  527. '%Y-%m-%d %H:%M:%S',
  528. '%Y-%m-%d %H:%M:%S.%f',
  529. '%d.%m.%Y %H:%M',
  530. '%d.%m.%Y %H.%M',
  531. '%Y-%m-%dT%H:%M:%SZ',
  532. '%Y-%m-%dT%H:%M:%S.%fZ',
  533. '%Y-%m-%dT%H:%M:%S.%f0Z',
  534. '%Y-%m-%dT%H:%M:%S',
  535. '%Y-%m-%dT%H:%M:%S.%f',
  536. '%Y-%m-%dT%H:%M',
  537. ]
  538. for expression in format_expressions:
  539. try:
  540. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  541. except ValueError:
  542. pass
  543. if upload_date is None:
  544. timetuple = email.utils.parsedate_tz(date_str)
  545. if timetuple:
  546. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  547. return upload_date
  548. def determine_ext(url, default_ext=u'unknown_video'):
  549. if url is None:
  550. return default_ext
  551. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  552. if re.match(r'^[A-Za-z0-9]+$', guess):
  553. return guess
  554. else:
  555. return default_ext
  556. def subtitles_filename(filename, sub_lang, sub_format):
  557. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  558. def date_from_str(date_str):
  559. """
  560. Return a datetime object from a string in the format YYYYMMDD or
  561. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  562. today = datetime.date.today()
  563. if date_str == 'now'or date_str == 'today':
  564. return today
  565. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  566. if match is not None:
  567. sign = match.group('sign')
  568. time = int(match.group('time'))
  569. if sign == '-':
  570. time = -time
  571. unit = match.group('unit')
  572. #A bad aproximation?
  573. if unit == 'month':
  574. unit = 'day'
  575. time *= 30
  576. elif unit == 'year':
  577. unit = 'day'
  578. time *= 365
  579. unit += 's'
  580. delta = datetime.timedelta(**{unit: time})
  581. return today + delta
  582. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  583. def hyphenate_date(date_str):
  584. """
  585. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  586. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  587. if match is not None:
  588. return '-'.join(match.groups())
  589. else:
  590. return date_str
  591. class DateRange(object):
  592. """Represents a time interval between two dates"""
  593. def __init__(self, start=None, end=None):
  594. """start and end must be strings in the format accepted by date"""
  595. if start is not None:
  596. self.start = date_from_str(start)
  597. else:
  598. self.start = datetime.datetime.min.date()
  599. if end is not None:
  600. self.end = date_from_str(end)
  601. else:
  602. self.end = datetime.datetime.max.date()
  603. if self.start > self.end:
  604. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  605. @classmethod
  606. def day(cls, day):
  607. """Returns a range that only contains the given day"""
  608. return cls(day,day)
  609. def __contains__(self, date):
  610. """Check if the date is in the range"""
  611. if not isinstance(date, datetime.date):
  612. date = date_from_str(date)
  613. return self.start <= date <= self.end
  614. def __str__(self):
  615. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  616. def platform_name():
  617. """ Returns the platform name as a compat_str """
  618. res = platform.platform()
  619. if isinstance(res, bytes):
  620. res = res.decode(preferredencoding())
  621. assert isinstance(res, compat_str)
  622. return res
  623. def _windows_write_string(s, out):
  624. """ Returns True if the string was written using special methods,
  625. False if it has yet to be written out."""
  626. # Adapted from http://stackoverflow.com/a/3259271/35070
  627. import ctypes
  628. import ctypes.wintypes
  629. WIN_OUTPUT_IDS = {
  630. 1: -11,
  631. 2: -12,
  632. }
  633. try:
  634. fileno = out.fileno()
  635. except AttributeError:
  636. # If the output stream doesn't have a fileno, it's virtual
  637. return False
  638. if fileno not in WIN_OUTPUT_IDS:
  639. return False
  640. GetStdHandle = ctypes.WINFUNCTYPE(
  641. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  642. ("GetStdHandle", ctypes.windll.kernel32))
  643. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  644. WriteConsoleW = ctypes.WINFUNCTYPE(
  645. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  646. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  647. ctypes.wintypes.LPVOID)(("WriteConsoleW", ctypes.windll.kernel32))
  648. written = ctypes.wintypes.DWORD(0)
  649. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(("GetFileType", ctypes.windll.kernel32))
  650. FILE_TYPE_CHAR = 0x0002
  651. FILE_TYPE_REMOTE = 0x8000
  652. GetConsoleMode = ctypes.WINFUNCTYPE(
  653. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  654. ctypes.POINTER(ctypes.wintypes.DWORD))(
  655. ("GetConsoleMode", ctypes.windll.kernel32))
  656. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  657. def not_a_console(handle):
  658. if handle == INVALID_HANDLE_VALUE or handle is None:
  659. return True
  660. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  661. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  662. if not_a_console(h):
  663. return False
  664. def next_nonbmp_pos(s):
  665. try:
  666. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  667. except StopIteration:
  668. return len(s)
  669. while s:
  670. count = min(next_nonbmp_pos(s), 1024)
  671. ret = WriteConsoleW(
  672. h, s, count if count else 2, ctypes.byref(written), None)
  673. if ret == 0:
  674. raise OSError('Failed to write string')
  675. if not count: # We just wrote a non-BMP character
  676. assert written.value == 2
  677. s = s[1:]
  678. else:
  679. assert written.value > 0
  680. s = s[written.value:]
  681. return True
  682. def write_string(s, out=None, encoding=None):
  683. if out is None:
  684. out = sys.stderr
  685. assert type(s) == compat_str
  686. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  687. if _windows_write_string(s, out):
  688. return
  689. if ('b' in getattr(out, 'mode', '') or
  690. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  691. byt = s.encode(encoding or preferredencoding(), 'ignore')
  692. out.write(byt)
  693. elif hasattr(out, 'buffer'):
  694. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  695. byt = s.encode(enc, 'ignore')
  696. out.buffer.write(byt)
  697. else:
  698. out.write(s)
  699. out.flush()
  700. def bytes_to_intlist(bs):
  701. if not bs:
  702. return []
  703. if isinstance(bs[0], int): # Python 3
  704. return list(bs)
  705. else:
  706. return [ord(c) for c in bs]
  707. def intlist_to_bytes(xs):
  708. if not xs:
  709. return b''
  710. if isinstance(chr(0), bytes): # Python 2
  711. return ''.join([chr(x) for x in xs])
  712. else:
  713. return bytes(xs)
  714. # Cross-platform file locking
  715. if sys.platform == 'win32':
  716. import ctypes.wintypes
  717. import msvcrt
  718. class OVERLAPPED(ctypes.Structure):
  719. _fields_ = [
  720. ('Internal', ctypes.wintypes.LPVOID),
  721. ('InternalHigh', ctypes.wintypes.LPVOID),
  722. ('Offset', ctypes.wintypes.DWORD),
  723. ('OffsetHigh', ctypes.wintypes.DWORD),
  724. ('hEvent', ctypes.wintypes.HANDLE),
  725. ]
  726. kernel32 = ctypes.windll.kernel32
  727. LockFileEx = kernel32.LockFileEx
  728. LockFileEx.argtypes = [
  729. ctypes.wintypes.HANDLE, # hFile
  730. ctypes.wintypes.DWORD, # dwFlags
  731. ctypes.wintypes.DWORD, # dwReserved
  732. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  733. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  734. ctypes.POINTER(OVERLAPPED) # Overlapped
  735. ]
  736. LockFileEx.restype = ctypes.wintypes.BOOL
  737. UnlockFileEx = kernel32.UnlockFileEx
  738. UnlockFileEx.argtypes = [
  739. ctypes.wintypes.HANDLE, # hFile
  740. ctypes.wintypes.DWORD, # dwReserved
  741. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  742. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  743. ctypes.POINTER(OVERLAPPED) # Overlapped
  744. ]
  745. UnlockFileEx.restype = ctypes.wintypes.BOOL
  746. whole_low = 0xffffffff
  747. whole_high = 0x7fffffff
  748. def _lock_file(f, exclusive):
  749. overlapped = OVERLAPPED()
  750. overlapped.Offset = 0
  751. overlapped.OffsetHigh = 0
  752. overlapped.hEvent = 0
  753. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  754. handle = msvcrt.get_osfhandle(f.fileno())
  755. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  756. whole_low, whole_high, f._lock_file_overlapped_p):
  757. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  758. def _unlock_file(f):
  759. assert f._lock_file_overlapped_p
  760. handle = msvcrt.get_osfhandle(f.fileno())
  761. if not UnlockFileEx(handle, 0,
  762. whole_low, whole_high, f._lock_file_overlapped_p):
  763. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  764. else:
  765. import fcntl
  766. def _lock_file(f, exclusive):
  767. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  768. def _unlock_file(f):
  769. fcntl.flock(f, fcntl.LOCK_UN)
  770. class locked_file(object):
  771. def __init__(self, filename, mode, encoding=None):
  772. assert mode in ['r', 'a', 'w']
  773. self.f = io.open(filename, mode, encoding=encoding)
  774. self.mode = mode
  775. def __enter__(self):
  776. exclusive = self.mode != 'r'
  777. try:
  778. _lock_file(self.f, exclusive)
  779. except IOError:
  780. self.f.close()
  781. raise
  782. return self
  783. def __exit__(self, etype, value, traceback):
  784. try:
  785. _unlock_file(self.f)
  786. finally:
  787. self.f.close()
  788. def __iter__(self):
  789. return iter(self.f)
  790. def write(self, *args):
  791. return self.f.write(*args)
  792. def read(self, *args):
  793. return self.f.read(*args)
  794. def get_filesystem_encoding():
  795. encoding = sys.getfilesystemencoding()
  796. return encoding if encoding is not None else 'utf-8'
  797. def shell_quote(args):
  798. quoted_args = []
  799. encoding = get_filesystem_encoding()
  800. for a in args:
  801. if isinstance(a, bytes):
  802. # We may get a filename encoded with 'encodeFilename'
  803. a = a.decode(encoding)
  804. quoted_args.append(pipes.quote(a))
  805. return u' '.join(quoted_args)
  806. def takewhile_inclusive(pred, seq):
  807. """ Like itertools.takewhile, but include the latest evaluated element
  808. (the first element so that Not pred(e)) """
  809. for e in seq:
  810. yield e
  811. if not pred(e):
  812. return
  813. def smuggle_url(url, data):
  814. """ Pass additional data in a URL for internal use. """
  815. sdata = compat_urllib_parse.urlencode(
  816. {u'__youtubedl_smuggle': json.dumps(data)})
  817. return url + u'#' + sdata
  818. def unsmuggle_url(smug_url, default=None):
  819. if not '#__youtubedl_smuggle' in smug_url:
  820. return smug_url, default
  821. url, _, sdata = smug_url.rpartition(u'#')
  822. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  823. data = json.loads(jsond)
  824. return url, data
  825. def format_bytes(bytes):
  826. if bytes is None:
  827. return u'N/A'
  828. if type(bytes) is str:
  829. bytes = float(bytes)
  830. if bytes == 0.0:
  831. exponent = 0
  832. else:
  833. exponent = int(math.log(bytes, 1024.0))
  834. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  835. converted = float(bytes) / float(1024 ** exponent)
  836. return u'%.2f%s' % (converted, suffix)
  837. def get_term_width():
  838. columns = compat_getenv('COLUMNS', None)
  839. if columns:
  840. return int(columns)
  841. try:
  842. sp = subprocess.Popen(
  843. ['stty', 'size'],
  844. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  845. out, err = sp.communicate()
  846. return int(out.split()[1])
  847. except:
  848. pass
  849. return None
  850. def month_by_name(name):
  851. """ Return the number of a month by (locale-independently) English name """
  852. ENGLISH_NAMES = [
  853. u'January', u'February', u'March', u'April', u'May', u'June',
  854. u'July', u'August', u'September', u'October', u'November', u'December']
  855. try:
  856. return ENGLISH_NAMES.index(name) + 1
  857. except ValueError:
  858. return None
  859. def fix_xml_ampersands(xml_str):
  860. """Replace all the '&' by '&amp;' in XML"""
  861. return re.sub(
  862. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  863. u'&amp;',
  864. xml_str)
  865. def setproctitle(title):
  866. assert isinstance(title, compat_str)
  867. try:
  868. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  869. except OSError:
  870. return
  871. title_bytes = title.encode('utf-8')
  872. buf = ctypes.create_string_buffer(len(title_bytes))
  873. buf.value = title_bytes
  874. try:
  875. libc.prctl(15, buf, 0, 0, 0)
  876. except AttributeError:
  877. return # Strange libc, just skip this
  878. def remove_start(s, start):
  879. if s.startswith(start):
  880. return s[len(start):]
  881. return s
  882. def remove_end(s, end):
  883. if s.endswith(end):
  884. return s[:-len(end)]
  885. return s
  886. def url_basename(url):
  887. path = compat_urlparse.urlparse(url).path
  888. return path.strip(u'/').split(u'/')[-1]
  889. class HEADRequest(compat_urllib_request.Request):
  890. def get_method(self):
  891. return "HEAD"
  892. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  893. if get_attr:
  894. if v is not None:
  895. v = getattr(v, get_attr, None)
  896. if v == '':
  897. v = None
  898. return default if v is None else (int(v) * invscale // scale)
  899. def str_or_none(v, default=None):
  900. return default if v is None else compat_str(v)
  901. def str_to_int(int_str):
  902. """ A more relaxed version of int_or_none """
  903. if int_str is None:
  904. return None
  905. int_str = re.sub(r'[,\.\+]', u'', int_str)
  906. return int(int_str)
  907. def float_or_none(v, scale=1, invscale=1, default=None):
  908. return default if v is None else (float(v) * invscale / scale)
  909. def parse_duration(s):
  910. if s is None:
  911. return None
  912. s = s.strip()
  913. m = re.match(
  914. r'(?i)(?:(?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?(?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$', s)
  915. if not m:
  916. return None
  917. res = int(m.group('secs'))
  918. if m.group('mins'):
  919. res += int(m.group('mins')) * 60
  920. if m.group('hours'):
  921. res += int(m.group('hours')) * 60 * 60
  922. if m.group('ms'):
  923. res += float(m.group('ms'))
  924. return res
  925. def prepend_extension(filename, ext):
  926. name, real_ext = os.path.splitext(filename)
  927. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  928. def check_executable(exe, args=[]):
  929. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  930. args can be a list of arguments for a short output (like -version) """
  931. try:
  932. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  933. except OSError:
  934. return False
  935. return exe
  936. def get_exe_version(exe, args=['--version'],
  937. version_re=r'version\s+([0-9._-a-zA-Z]+)',
  938. unrecognized=u'present'):
  939. """ Returns the version of the specified executable,
  940. or False if the executable is not present """
  941. try:
  942. out, err = subprocess.Popen(
  943. [exe] + args,
  944. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  945. except OSError:
  946. return False
  947. firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
  948. m = re.search(version_re, firstline)
  949. if m:
  950. return m.group(1)
  951. else:
  952. return unrecognized
  953. class PagedList(object):
  954. def __len__(self):
  955. # This is only useful for tests
  956. return len(self.getslice())
  957. class OnDemandPagedList(PagedList):
  958. def __init__(self, pagefunc, pagesize):
  959. self._pagefunc = pagefunc
  960. self._pagesize = pagesize
  961. def getslice(self, start=0, end=None):
  962. res = []
  963. for pagenum in itertools.count(start // self._pagesize):
  964. firstid = pagenum * self._pagesize
  965. nextfirstid = pagenum * self._pagesize + self._pagesize
  966. if start >= nextfirstid:
  967. continue
  968. page_results = list(self._pagefunc(pagenum))
  969. startv = (
  970. start % self._pagesize
  971. if firstid <= start < nextfirstid
  972. else 0)
  973. endv = (
  974. ((end - 1) % self._pagesize) + 1
  975. if (end is not None and firstid <= end <= nextfirstid)
  976. else None)
  977. if startv != 0 or endv is not None:
  978. page_results = page_results[startv:endv]
  979. res.extend(page_results)
  980. # A little optimization - if current page is not "full", ie. does
  981. # not contain page_size videos then we can assume that this page
  982. # is the last one - there are no more ids on further pages -
  983. # i.e. no need to query again.
  984. if len(page_results) + startv < self._pagesize:
  985. break
  986. # If we got the whole page, but the next page is not interesting,
  987. # break out early as well
  988. if end == nextfirstid:
  989. break
  990. return res
  991. class InAdvancePagedList(PagedList):
  992. def __init__(self, pagefunc, pagecount, pagesize):
  993. self._pagefunc = pagefunc
  994. self._pagecount = pagecount
  995. self._pagesize = pagesize
  996. def getslice(self, start=0, end=None):
  997. res = []
  998. start_page = start // self._pagesize
  999. end_page = (
  1000. self._pagecount if end is None else (end // self._pagesize + 1))
  1001. skip_elems = start - start_page * self._pagesize
  1002. only_more = None if end is None else end - start
  1003. for pagenum in range(start_page, end_page):
  1004. page = list(self._pagefunc(pagenum))
  1005. if skip_elems:
  1006. page = page[skip_elems:]
  1007. skip_elems = None
  1008. if only_more is not None:
  1009. if len(page) < only_more:
  1010. only_more -= len(page)
  1011. else:
  1012. page = page[:only_more]
  1013. res.extend(page)
  1014. break
  1015. res.extend(page)
  1016. return res
  1017. def uppercase_escape(s):
  1018. unicode_escape = codecs.getdecoder('unicode_escape')
  1019. return re.sub(
  1020. r'\\U[0-9a-fA-F]{8}',
  1021. lambda m: unicode_escape(m.group(0))[0],
  1022. s)
  1023. def escape_rfc3986(s):
  1024. """Escape non-ASCII characters as suggested by RFC 3986"""
  1025. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1026. s = s.encode('utf-8')
  1027. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1028. def escape_url(url):
  1029. """Escape URL as suggested by RFC 3986"""
  1030. url_parsed = compat_urllib_parse_urlparse(url)
  1031. return url_parsed._replace(
  1032. path=escape_rfc3986(url_parsed.path),
  1033. params=escape_rfc3986(url_parsed.params),
  1034. query=escape_rfc3986(url_parsed.query),
  1035. fragment=escape_rfc3986(url_parsed.fragment)
  1036. ).geturl()
  1037. try:
  1038. struct.pack(u'!I', 0)
  1039. except TypeError:
  1040. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1041. def struct_pack(spec, *args):
  1042. if isinstance(spec, compat_str):
  1043. spec = spec.encode('ascii')
  1044. return struct.pack(spec, *args)
  1045. def struct_unpack(spec, *args):
  1046. if isinstance(spec, compat_str):
  1047. spec = spec.encode('ascii')
  1048. return struct.unpack(spec, *args)
  1049. else:
  1050. struct_pack = struct.pack
  1051. struct_unpack = struct.unpack
  1052. def read_batch_urls(batch_fd):
  1053. def fixup(url):
  1054. if not isinstance(url, compat_str):
  1055. url = url.decode('utf-8', 'replace')
  1056. BOM_UTF8 = u'\xef\xbb\xbf'
  1057. if url.startswith(BOM_UTF8):
  1058. url = url[len(BOM_UTF8):]
  1059. url = url.strip()
  1060. if url.startswith(('#', ';', ']')):
  1061. return False
  1062. return url
  1063. with contextlib.closing(batch_fd) as fd:
  1064. return [url for url in map(fixup, fd) if url]
  1065. def urlencode_postdata(*args, **kargs):
  1066. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1067. try:
  1068. etree_iter = xml.etree.ElementTree.Element.iter
  1069. except AttributeError: # Python <=2.6
  1070. etree_iter = lambda n: n.findall('.//*')
  1071. def parse_xml(s):
  1072. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1073. def doctype(self, name, pubid, system):
  1074. pass # Ignore doctypes
  1075. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1076. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1077. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1078. # Fix up XML parser in Python 2.x
  1079. if sys.version_info < (3, 0):
  1080. for n in etree_iter(tree):
  1081. if n.text is not None:
  1082. if not isinstance(n.text, compat_str):
  1083. n.text = n.text.decode('utf-8')
  1084. return tree
  1085. US_RATINGS = {
  1086. 'G': 0,
  1087. 'PG': 10,
  1088. 'PG-13': 13,
  1089. 'R': 16,
  1090. 'NC': 18,
  1091. }
  1092. def parse_age_limit(s):
  1093. if s is None:
  1094. return None
  1095. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1096. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1097. def strip_jsonp(code):
  1098. return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code)
  1099. def js_to_json(code):
  1100. def fix_kv(m):
  1101. v = m.group(0)
  1102. if v in ('true', 'false', 'null'):
  1103. return v
  1104. if v.startswith('"'):
  1105. return v
  1106. if v.startswith("'"):
  1107. v = v[1:-1]
  1108. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1109. '\\\\': '\\\\',
  1110. "\\'": "'",
  1111. '"': '\\"',
  1112. }[m.group(0)], v)
  1113. return '"%s"' % v
  1114. res = re.sub(r'''(?x)
  1115. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1116. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1117. [a-zA-Z_][a-zA-Z_0-9]*
  1118. ''', fix_kv, code)
  1119. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1120. return res
  1121. def qualities(quality_ids):
  1122. """ Get a numeric quality value out of a list of possible values """
  1123. def q(qid):
  1124. try:
  1125. return quality_ids.index(qid)
  1126. except ValueError:
  1127. return -1
  1128. return q
  1129. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1130. def limit_length(s, length):
  1131. """ Add ellipses to overly long strings """
  1132. if s is None:
  1133. return None
  1134. ELLIPSES = '...'
  1135. if len(s) > length:
  1136. return s[:length - len(ELLIPSES)] + ELLIPSES
  1137. return s
  1138. def version_tuple(v):
  1139. return [int(e) for e in v.split('.')]
  1140. def is_outdated_version(version, limit, assume_new=True):
  1141. if not version:
  1142. return not assume_new
  1143. try:
  1144. return version_tuple(version) < version_tuple(limit)
  1145. except ValueError:
  1146. return not assume_new