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.

808 lines
26 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import email.utils
  5. import errno
  6. import gzip
  7. import io
  8. import json
  9. import locale
  10. import os
  11. import platform
  12. import re
  13. import socket
  14. import sys
  15. import traceback
  16. import zlib
  17. try:
  18. import urllib.request as compat_urllib_request
  19. except ImportError: # Python 2
  20. import urllib2 as compat_urllib_request
  21. try:
  22. import urllib.error as compat_urllib_error
  23. except ImportError: # Python 2
  24. import urllib2 as compat_urllib_error
  25. try:
  26. import urllib.parse as compat_urllib_parse
  27. except ImportError: # Python 2
  28. import urllib as compat_urllib_parse
  29. try:
  30. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  31. except ImportError: # Python 2
  32. from urlparse import urlparse as compat_urllib_parse_urlparse
  33. try:
  34. import urllib.parse as compat_urlparse
  35. except ImportError: # Python 2
  36. import urlparse as compat_urlparse
  37. try:
  38. import http.cookiejar as compat_cookiejar
  39. except ImportError: # Python 2
  40. import cookielib as compat_cookiejar
  41. try:
  42. import html.entities as compat_html_entities
  43. except ImportError: # Python 2
  44. import htmlentitydefs as compat_html_entities
  45. try:
  46. import html.parser as compat_html_parser
  47. except ImportError: # Python 2
  48. import HTMLParser as compat_html_parser
  49. try:
  50. import http.client as compat_http_client
  51. except ImportError: # Python 2
  52. import httplib as compat_http_client
  53. try:
  54. from urllib.error import HTTPError as compat_HTTPError
  55. except ImportError: # Python 2
  56. from urllib2 import HTTPError as compat_HTTPError
  57. try:
  58. from subprocess import DEVNULL
  59. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  60. except ImportError:
  61. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  62. try:
  63. from urllib.parse import parse_qs as compat_parse_qs
  64. except ImportError: # Python 2
  65. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  66. # Python 2's version is apparently totally broken
  67. def _unquote(string, encoding='utf-8', errors='replace'):
  68. if string == '':
  69. return string
  70. res = string.split('%')
  71. if len(res) == 1:
  72. return string
  73. if encoding is None:
  74. encoding = 'utf-8'
  75. if errors is None:
  76. errors = 'replace'
  77. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  78. pct_sequence = b''
  79. string = res[0]
  80. for item in res[1:]:
  81. try:
  82. if not item:
  83. raise ValueError
  84. pct_sequence += item[:2].decode('hex')
  85. rest = item[2:]
  86. if not rest:
  87. # This segment was just a single percent-encoded character.
  88. # May be part of a sequence of code units, so delay decoding.
  89. # (Stored in pct_sequence).
  90. continue
  91. except ValueError:
  92. rest = '%' + item
  93. # Encountered non-percent-encoded characters. Flush the current
  94. # pct_sequence.
  95. string += pct_sequence.decode(encoding, errors) + rest
  96. pct_sequence = b''
  97. if pct_sequence:
  98. # Flush the final pct_sequence
  99. string += pct_sequence.decode(encoding, errors)
  100. return string
  101. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  102. encoding='utf-8', errors='replace'):
  103. qs, _coerce_result = qs, unicode
  104. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  105. r = []
  106. for name_value in pairs:
  107. if not name_value and not strict_parsing:
  108. continue
  109. nv = name_value.split('=', 1)
  110. if len(nv) != 2:
  111. if strict_parsing:
  112. raise ValueError("bad query field: %r" % (name_value,))
  113. # Handle case of a control-name with no equal sign
  114. if keep_blank_values:
  115. nv.append('')
  116. else:
  117. continue
  118. if len(nv[1]) or keep_blank_values:
  119. name = nv[0].replace('+', ' ')
  120. name = _unquote(name, encoding=encoding, errors=errors)
  121. name = _coerce_result(name)
  122. value = nv[1].replace('+', ' ')
  123. value = _unquote(value, encoding=encoding, errors=errors)
  124. value = _coerce_result(value)
  125. r.append((name, value))
  126. return r
  127. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  128. encoding='utf-8', errors='replace'):
  129. parsed_result = {}
  130. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  131. encoding=encoding, errors=errors)
  132. for name, value in pairs:
  133. if name in parsed_result:
  134. parsed_result[name].append(value)
  135. else:
  136. parsed_result[name] = [value]
  137. return parsed_result
  138. try:
  139. compat_str = unicode # Python 2
  140. except NameError:
  141. compat_str = str
  142. try:
  143. compat_chr = unichr # Python 2
  144. except NameError:
  145. compat_chr = chr
  146. def compat_ord(c):
  147. if type(c) is int: return c
  148. else: return ord(c)
  149. # This is not clearly defined otherwise
  150. compiled_regex_type = type(re.compile(''))
  151. std_headers = {
  152. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  153. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  154. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  155. 'Accept-Encoding': 'gzip, deflate',
  156. 'Accept-Language': 'en-us,en;q=0.5',
  157. }
  158. def preferredencoding():
  159. """Get preferred encoding.
  160. Returns the best encoding scheme for the system, based on
  161. locale.getpreferredencoding() and some further tweaks.
  162. """
  163. try:
  164. pref = locale.getpreferredencoding()
  165. u'TEST'.encode(pref)
  166. except:
  167. pref = 'UTF-8'
  168. return pref
  169. if sys.version_info < (3,0):
  170. def compat_print(s):
  171. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  172. else:
  173. def compat_print(s):
  174. assert type(s) == type(u'')
  175. print(s)
  176. # In Python 2.x, json.dump expects a bytestream.
  177. # In Python 3.x, it writes to a character stream
  178. if sys.version_info < (3,0):
  179. def write_json_file(obj, fn):
  180. with open(fn, 'wb') as f:
  181. json.dump(obj, f)
  182. else:
  183. def write_json_file(obj, fn):
  184. with open(fn, 'w', encoding='utf-8') as f:
  185. json.dump(obj, f)
  186. if sys.version_info >= (2,7):
  187. def find_xpath_attr(node, xpath, key, val):
  188. """ Find the xpath xpath[@key=val] """
  189. assert re.match(r'^[a-zA-Z]+$', key)
  190. assert re.match(r'^[a-zA-Z0-9@\s]*$', val)
  191. expr = xpath + u"[@%s='%s']" % (key, val)
  192. return node.find(expr)
  193. else:
  194. def find_xpath_attr(node, xpath, key, val):
  195. for f in node.findall(xpath):
  196. if f.attrib.get(key) == val:
  197. return f
  198. return None
  199. def htmlentity_transform(matchobj):
  200. """Transforms an HTML entity to a character.
  201. This function receives a match object and is intended to be used with
  202. the re.sub() function.
  203. """
  204. entity = matchobj.group(1)
  205. # Known non-numeric HTML entity
  206. if entity in compat_html_entities.name2codepoint:
  207. return compat_chr(compat_html_entities.name2codepoint[entity])
  208. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  209. if mobj is not None:
  210. numstr = mobj.group(1)
  211. if numstr.startswith(u'x'):
  212. base = 16
  213. numstr = u'0%s' % numstr
  214. else:
  215. base = 10
  216. return compat_chr(int(numstr, base))
  217. # Unknown entity in name, return its literal representation
  218. return (u'&%s;' % entity)
  219. 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
  220. class BaseHTMLParser(compat_html_parser.HTMLParser):
  221. def __init(self):
  222. compat_html_parser.HTMLParser.__init__(self)
  223. self.html = None
  224. def loads(self, html):
  225. self.html = html
  226. self.feed(html)
  227. self.close()
  228. class AttrParser(BaseHTMLParser):
  229. """Modified HTMLParser that isolates a tag with the specified attribute"""
  230. def __init__(self, attribute, value):
  231. self.attribute = attribute
  232. self.value = value
  233. self.result = None
  234. self.started = False
  235. self.depth = {}
  236. self.watch_startpos = False
  237. self.error_count = 0
  238. BaseHTMLParser.__init__(self)
  239. def error(self, message):
  240. if self.error_count > 10 or self.started:
  241. raise compat_html_parser.HTMLParseError(message, self.getpos())
  242. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  243. self.error_count += 1
  244. self.goahead(1)
  245. def handle_starttag(self, tag, attrs):
  246. attrs = dict(attrs)
  247. if self.started:
  248. self.find_startpos(None)
  249. if self.attribute in attrs and attrs[self.attribute] == self.value:
  250. self.result = [tag]
  251. self.started = True
  252. self.watch_startpos = True
  253. if self.started:
  254. if not tag in self.depth: self.depth[tag] = 0
  255. self.depth[tag] += 1
  256. def handle_endtag(self, tag):
  257. if self.started:
  258. if tag in self.depth: self.depth[tag] -= 1
  259. if self.depth[self.result[0]] == 0:
  260. self.started = False
  261. self.result.append(self.getpos())
  262. def find_startpos(self, x):
  263. """Needed to put the start position of the result (self.result[1])
  264. after the opening tag with the requested id"""
  265. if self.watch_startpos:
  266. self.watch_startpos = False
  267. self.result.append(self.getpos())
  268. handle_entityref = handle_charref = handle_data = handle_comment = \
  269. handle_decl = handle_pi = unknown_decl = find_startpos
  270. def get_result(self):
  271. if self.result is None:
  272. return None
  273. if len(self.result) != 3:
  274. return None
  275. lines = self.html.split('\n')
  276. lines = lines[self.result[1][0]-1:self.result[2][0]]
  277. lines[0] = lines[0][self.result[1][1]:]
  278. if len(lines) == 1:
  279. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  280. lines[-1] = lines[-1][:self.result[2][1]]
  281. return '\n'.join(lines).strip()
  282. # Hack for https://github.com/rg3/youtube-dl/issues/662
  283. if sys.version_info < (2, 7, 3):
  284. AttrParser.parse_endtag = (lambda self, i:
  285. i + len("</scr'+'ipt>")
  286. if self.rawdata[i:].startswith("</scr'+'ipt>")
  287. else compat_html_parser.HTMLParser.parse_endtag(self, i))
  288. def get_element_by_id(id, html):
  289. """Return the content of the tag with the specified ID in the passed HTML document"""
  290. return get_element_by_attribute("id", id, html)
  291. def get_element_by_attribute(attribute, value, html):
  292. """Return the content of the tag with the specified attribute in the passed HTML document"""
  293. parser = AttrParser(attribute, value)
  294. try:
  295. parser.loads(html)
  296. except compat_html_parser.HTMLParseError:
  297. pass
  298. return parser.get_result()
  299. class MetaParser(BaseHTMLParser):
  300. """
  301. Modified HTMLParser that isolates a meta tag with the specified name
  302. attribute.
  303. """
  304. def __init__(self, name):
  305. BaseHTMLParser.__init__(self)
  306. self.name = name
  307. self.content = None
  308. self.result = None
  309. def handle_starttag(self, tag, attrs):
  310. if tag != 'meta':
  311. return
  312. attrs = dict(attrs)
  313. if attrs.get('name') == self.name:
  314. self.result = attrs.get('content')
  315. def get_result(self):
  316. return self.result
  317. def get_meta_content(name, html):
  318. """
  319. Return the content attribute from the meta tag with the given name attribute.
  320. """
  321. parser = MetaParser(name)
  322. try:
  323. parser.loads(html)
  324. except compat_html_parser.HTMLParseError:
  325. pass
  326. return parser.get_result()
  327. def clean_html(html):
  328. """Clean an HTML snippet into a readable string"""
  329. # Newline vs <br />
  330. html = html.replace('\n', ' ')
  331. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  332. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  333. # Strip html tags
  334. html = re.sub('<.*?>', '', html)
  335. # Replace html entities
  336. html = unescapeHTML(html)
  337. return html.strip()
  338. def sanitize_open(filename, open_mode):
  339. """Try to open the given filename, and slightly tweak it if this fails.
  340. Attempts to open the given filename. If this fails, it tries to change
  341. the filename slightly, step by step, until it's either able to open it
  342. or it fails and raises a final exception, like the standard open()
  343. function.
  344. It returns the tuple (stream, definitive_file_name).
  345. """
  346. try:
  347. if filename == u'-':
  348. if sys.platform == 'win32':
  349. import msvcrt
  350. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  351. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  352. stream = open(encodeFilename(filename), open_mode)
  353. return (stream, filename)
  354. except (IOError, OSError) as err:
  355. if err.errno in (errno.EACCES,):
  356. raise
  357. # In case of error, try to remove win32 forbidden chars
  358. alt_filename = os.path.join(
  359. re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', path_part)
  360. for path_part in os.path.split(filename)
  361. )
  362. if alt_filename == filename:
  363. raise
  364. else:
  365. # An exception here should be caught in the caller
  366. stream = open(encodeFilename(filename), open_mode)
  367. return (stream, alt_filename)
  368. def timeconvert(timestr):
  369. """Convert RFC 2822 defined time string into system timestamp"""
  370. timestamp = None
  371. timetuple = email.utils.parsedate_tz(timestr)
  372. if timetuple is not None:
  373. timestamp = email.utils.mktime_tz(timetuple)
  374. return timestamp
  375. def sanitize_filename(s, restricted=False, is_id=False):
  376. """Sanitizes a string so it could be used as part of a filename.
  377. If restricted is set, use a stricter subset of allowed characters.
  378. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  379. """
  380. def replace_insane(char):
  381. if char == '?' or ord(char) < 32 or ord(char) == 127:
  382. return ''
  383. elif char == '"':
  384. return '' if restricted else '\''
  385. elif char == ':':
  386. return '_-' if restricted else ' -'
  387. elif char in '\\/|*<>':
  388. return '_'
  389. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  390. return '_'
  391. if restricted and ord(char) > 127:
  392. return '_'
  393. return char
  394. result = u''.join(map(replace_insane, s))
  395. if not is_id:
  396. while '__' in result:
  397. result = result.replace('__', '_')
  398. result = result.strip('_')
  399. # Common case of "Foreign band name - English song title"
  400. if restricted and result.startswith('-_'):
  401. result = result[2:]
  402. if not result:
  403. result = '_'
  404. return result
  405. def orderedSet(iterable):
  406. """ Remove all duplicates from the input iterable """
  407. res = []
  408. for el in iterable:
  409. if el not in res:
  410. res.append(el)
  411. return res
  412. def unescapeHTML(s):
  413. """
  414. @param s a string
  415. """
  416. assert type(s) == type(u'')
  417. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  418. return result
  419. def encodeFilename(s):
  420. """
  421. @param s The name of the file
  422. """
  423. assert type(s) == type(u'')
  424. # Python 3 has a Unicode API
  425. if sys.version_info >= (3, 0):
  426. return s
  427. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  428. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  429. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  430. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  431. return s
  432. else:
  433. encoding = sys.getfilesystemencoding()
  434. if encoding is None:
  435. encoding = 'utf-8'
  436. return s.encode(encoding, 'ignore')
  437. def decodeOption(optval):
  438. if optval is None:
  439. return optval
  440. if isinstance(optval, bytes):
  441. optval = optval.decode(preferredencoding())
  442. assert isinstance(optval, compat_str)
  443. return optval
  444. def formatSeconds(secs):
  445. if secs > 3600:
  446. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  447. elif secs > 60:
  448. return '%d:%02d' % (secs // 60, secs % 60)
  449. else:
  450. return '%d' % secs
  451. def make_HTTPS_handler(opts):
  452. if sys.version_info < (3,2):
  453. # Python's 2.x handler is very simplistic
  454. return compat_urllib_request.HTTPSHandler()
  455. else:
  456. import ssl
  457. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  458. context.set_default_verify_paths()
  459. context.verify_mode = (ssl.CERT_NONE
  460. if opts.no_check_certificate
  461. else ssl.CERT_REQUIRED)
  462. return compat_urllib_request.HTTPSHandler(context=context)
  463. class ExtractorError(Exception):
  464. """Error during info extraction."""
  465. def __init__(self, msg, tb=None, expected=False, cause=None):
  466. """ tb, if given, is the original traceback (so that it can be printed out).
  467. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  468. """
  469. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  470. expected = True
  471. if not expected:
  472. 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.'
  473. super(ExtractorError, self).__init__(msg)
  474. self.traceback = tb
  475. self.exc_info = sys.exc_info() # preserve original exception
  476. self.cause = cause
  477. def format_traceback(self):
  478. if self.traceback is None:
  479. return None
  480. return u''.join(traceback.format_tb(self.traceback))
  481. class DownloadError(Exception):
  482. """Download Error exception.
  483. This exception may be thrown by FileDownloader objects if they are not
  484. configured to continue on errors. They will contain the appropriate
  485. error message.
  486. """
  487. def __init__(self, msg, exc_info=None):
  488. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  489. super(DownloadError, self).__init__(msg)
  490. self.exc_info = exc_info
  491. class SameFileError(Exception):
  492. """Same File exception.
  493. This exception will be thrown by FileDownloader objects if they detect
  494. multiple files would have to be downloaded to the same file on disk.
  495. """
  496. pass
  497. class PostProcessingError(Exception):
  498. """Post Processing exception.
  499. This exception may be raised by PostProcessor's .run() method to
  500. indicate an error in the postprocessing task.
  501. """
  502. def __init__(self, msg):
  503. self.msg = msg
  504. class MaxDownloadsReached(Exception):
  505. """ --max-downloads limit has been reached. """
  506. pass
  507. class UnavailableVideoError(Exception):
  508. """Unavailable Format exception.
  509. This exception will be thrown when a video is requested
  510. in a format that is not available for that video.
  511. """
  512. pass
  513. class ContentTooShortError(Exception):
  514. """Content Too Short exception.
  515. This exception may be raised by FileDownloader objects when a file they
  516. download is too small for what the server announced first, indicating
  517. the connection was probably interrupted.
  518. """
  519. # Both in bytes
  520. downloaded = None
  521. expected = None
  522. def __init__(self, downloaded, expected):
  523. self.downloaded = downloaded
  524. self.expected = expected
  525. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  526. """Handler for HTTP requests and responses.
  527. This class, when installed with an OpenerDirector, automatically adds
  528. the standard headers to every HTTP request and handles gzipped and
  529. deflated responses from web servers. If compression is to be avoided in
  530. a particular request, the original request in the program code only has
  531. to include the HTTP header "Youtubedl-No-Compression", which will be
  532. removed before making the real request.
  533. Part of this code was copied from:
  534. http://techknack.net/python-urllib2-handlers/
  535. Andrew Rowls, the author of that code, agreed to release it to the
  536. public domain.
  537. """
  538. @staticmethod
  539. def deflate(data):
  540. try:
  541. return zlib.decompress(data, -zlib.MAX_WBITS)
  542. except zlib.error:
  543. return zlib.decompress(data)
  544. @staticmethod
  545. def addinfourl_wrapper(stream, headers, url, code):
  546. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  547. return compat_urllib_request.addinfourl(stream, headers, url, code)
  548. ret = compat_urllib_request.addinfourl(stream, headers, url)
  549. ret.code = code
  550. return ret
  551. def http_request(self, req):
  552. for h,v in std_headers.items():
  553. if h in req.headers:
  554. del req.headers[h]
  555. req.add_header(h, v)
  556. if 'Youtubedl-no-compression' in req.headers:
  557. if 'Accept-encoding' in req.headers:
  558. del req.headers['Accept-encoding']
  559. del req.headers['Youtubedl-no-compression']
  560. if 'Youtubedl-user-agent' in req.headers:
  561. if 'User-agent' in req.headers:
  562. del req.headers['User-agent']
  563. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  564. del req.headers['Youtubedl-user-agent']
  565. return req
  566. def http_response(self, req, resp):
  567. old_resp = resp
  568. # gzip
  569. if resp.headers.get('Content-encoding', '') == 'gzip':
  570. content = resp.read()
  571. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  572. try:
  573. uncompressed = io.BytesIO(gz.read())
  574. except IOError as original_ioerror:
  575. # There may be junk add the end of the file
  576. # See http://stackoverflow.com/q/4928560/35070 for details
  577. for i in range(1, 1024):
  578. try:
  579. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  580. uncompressed = io.BytesIO(gz.read())
  581. except IOError:
  582. continue
  583. break
  584. else:
  585. raise original_ioerror
  586. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  587. resp.msg = old_resp.msg
  588. # deflate
  589. if resp.headers.get('Content-encoding', '') == 'deflate':
  590. gz = io.BytesIO(self.deflate(resp.read()))
  591. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  592. resp.msg = old_resp.msg
  593. return resp
  594. https_request = http_request
  595. https_response = http_response
  596. def unified_strdate(date_str):
  597. """Return a string with the date in the format YYYYMMDD"""
  598. upload_date = None
  599. #Replace commas
  600. date_str = date_str.replace(',',' ')
  601. # %z (UTC offset) is only supported in python>=3.2
  602. date_str = re.sub(r' (\+|-)[\d]*$', '', date_str)
  603. format_expressions = [
  604. '%d %B %Y',
  605. '%B %d %Y',
  606. '%b %d %Y',
  607. '%Y-%m-%d',
  608. '%d/%m/%Y',
  609. '%Y/%m/%d %H:%M:%S',
  610. '%d.%m.%Y %H:%M',
  611. '%Y-%m-%dT%H:%M:%SZ',
  612. ]
  613. for expression in format_expressions:
  614. try:
  615. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  616. except:
  617. pass
  618. return upload_date
  619. def determine_ext(url, default_ext=u'unknown_video'):
  620. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  621. if re.match(r'^[A-Za-z0-9]+$', guess):
  622. return guess
  623. else:
  624. return default_ext
  625. def subtitles_filename(filename, sub_lang, sub_format):
  626. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  627. def date_from_str(date_str):
  628. """
  629. Return a datetime object from a string in the format YYYYMMDD or
  630. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  631. today = datetime.date.today()
  632. if date_str == 'now'or date_str == 'today':
  633. return today
  634. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  635. if match is not None:
  636. sign = match.group('sign')
  637. time = int(match.group('time'))
  638. if sign == '-':
  639. time = -time
  640. unit = match.group('unit')
  641. #A bad aproximation?
  642. if unit == 'month':
  643. unit = 'day'
  644. time *= 30
  645. elif unit == 'year':
  646. unit = 'day'
  647. time *= 365
  648. unit += 's'
  649. delta = datetime.timedelta(**{unit: time})
  650. return today + delta
  651. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  652. class DateRange(object):
  653. """Represents a time interval between two dates"""
  654. def __init__(self, start=None, end=None):
  655. """start and end must be strings in the format accepted by date"""
  656. if start is not None:
  657. self.start = date_from_str(start)
  658. else:
  659. self.start = datetime.datetime.min.date()
  660. if end is not None:
  661. self.end = date_from_str(end)
  662. else:
  663. self.end = datetime.datetime.max.date()
  664. if self.start > self.end:
  665. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  666. @classmethod
  667. def day(cls, day):
  668. """Returns a range that only contains the given day"""
  669. return cls(day,day)
  670. def __contains__(self, date):
  671. """Check if the date is in the range"""
  672. if not isinstance(date, datetime.date):
  673. date = date_from_str(date)
  674. return self.start <= date <= self.end
  675. def __str__(self):
  676. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  677. def platform_name():
  678. """ Returns the platform name as a compat_str """
  679. res = platform.platform()
  680. if isinstance(res, bytes):
  681. res = res.decode(preferredencoding())
  682. assert isinstance(res, compat_str)
  683. return res
  684. def bytes_to_intlist(bs):
  685. if not bs:
  686. return []
  687. if isinstance(bs[0], int): # Python 3
  688. return list(bs)
  689. else:
  690. return [ord(c) for c in bs]
  691. def intlist_to_bytes(xs):
  692. if not xs:
  693. return b''
  694. if isinstance(chr(0), bytes): # Python 2
  695. return ''.join([chr(x) for x in xs])
  696. else:
  697. return bytes(xs)