utils.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import errno
  13. import functools
  14. import gzip
  15. import itertools
  16. import io
  17. import json
  18. import locale
  19. import math
  20. import operator
  21. import os
  22. import pipes
  23. import platform
  24. import re
  25. import ssl
  26. import socket
  27. import struct
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_basestring,
  36. compat_chr,
  37. compat_etree_fromstring,
  38. compat_html_entities,
  39. compat_http_client,
  40. compat_kwargs,
  41. compat_parse_qs,
  42. compat_socket_create_connection,
  43. compat_str,
  44. compat_urllib_error,
  45. compat_urllib_parse,
  46. compat_urllib_parse_urlparse,
  47. compat_urllib_request,
  48. compat_urlparse,
  49. shlex_quote,
  50. )
  51. # This is not clearly defined otherwise
  52. compiled_regex_type = type(re.compile(''))
  53. std_headers = {
  54. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/44.0 (Chrome)',
  55. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  56. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  57. 'Accept-Encoding': 'gzip, deflate',
  58. 'Accept-Language': 'en-us,en;q=0.5',
  59. }
  60. NO_DEFAULT = object()
  61. ENGLISH_MONTH_NAMES = [
  62. 'January', 'February', 'March', 'April', 'May', 'June',
  63. 'July', 'August', 'September', 'October', 'November', 'December']
  64. KNOWN_EXTENSIONS = (
  65. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  66. 'flv', 'f4v', 'f4a', 'f4b',
  67. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  68. 'mkv', 'mka', 'mk3d',
  69. 'avi', 'divx',
  70. 'mov',
  71. 'asf', 'wmv', 'wma',
  72. '3gp', '3g2',
  73. 'mp3',
  74. 'flac',
  75. 'ape',
  76. 'wav',
  77. 'f4f', 'f4m', 'm3u8', 'smil')
  78. def preferredencoding():
  79. """Get preferred encoding.
  80. Returns the best encoding scheme for the system, based on
  81. locale.getpreferredencoding() and some further tweaks.
  82. """
  83. try:
  84. pref = locale.getpreferredencoding()
  85. 'TEST'.encode(pref)
  86. except Exception:
  87. pref = 'UTF-8'
  88. return pref
  89. def write_json_file(obj, fn):
  90. """ Encode obj as JSON and write it to fn, atomically if possible """
  91. fn = encodeFilename(fn)
  92. if sys.version_info < (3, 0) and sys.platform != 'win32':
  93. encoding = get_filesystem_encoding()
  94. # os.path.basename returns a bytes object, but NamedTemporaryFile
  95. # will fail if the filename contains non ascii characters unless we
  96. # use a unicode object
  97. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  98. # the same for os.path.dirname
  99. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  100. else:
  101. path_basename = os.path.basename
  102. path_dirname = os.path.dirname
  103. args = {
  104. 'suffix': '.tmp',
  105. 'prefix': path_basename(fn) + '.',
  106. 'dir': path_dirname(fn),
  107. 'delete': False,
  108. }
  109. # In Python 2.x, json.dump expects a bytestream.
  110. # In Python 3.x, it writes to a character stream
  111. if sys.version_info < (3, 0):
  112. args['mode'] = 'wb'
  113. else:
  114. args.update({
  115. 'mode': 'w',
  116. 'encoding': 'utf-8',
  117. })
  118. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  119. try:
  120. with tf:
  121. json.dump(obj, tf)
  122. if sys.platform == 'win32':
  123. # Need to remove existing file on Windows, else os.rename raises
  124. # WindowsError or FileExistsError.
  125. try:
  126. os.unlink(fn)
  127. except OSError:
  128. pass
  129. os.rename(tf.name, fn)
  130. except Exception:
  131. try:
  132. os.remove(tf.name)
  133. except OSError:
  134. pass
  135. raise
  136. if sys.version_info >= (2, 7):
  137. def find_xpath_attr(node, xpath, key, val=None):
  138. """ Find the xpath xpath[@key=val] """
  139. assert re.match(r'^[a-zA-Z_-]+$', key)
  140. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  141. return node.find(expr)
  142. else:
  143. def find_xpath_attr(node, xpath, key, val=None):
  144. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  145. # .//node does not match if a node is a direct child of . !
  146. if isinstance(xpath, compat_str):
  147. xpath = xpath.encode('ascii')
  148. for f in node.findall(xpath):
  149. if key not in f.attrib:
  150. continue
  151. if val is None or f.attrib.get(key) == val:
  152. return f
  153. return None
  154. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  155. # the namespace parameter
  156. def xpath_with_ns(path, ns_map):
  157. components = [c.split(':') for c in path.split('/')]
  158. replaced = []
  159. for c in components:
  160. if len(c) == 1:
  161. replaced.append(c[0])
  162. else:
  163. ns, tag = c
  164. replaced.append('{%s}%s' % (ns_map[ns], tag))
  165. return '/'.join(replaced)
  166. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  167. def _find_xpath(xpath):
  168. if sys.version_info < (2, 7): # Crazy 2.6
  169. xpath = xpath.encode('ascii')
  170. return node.find(xpath)
  171. if isinstance(xpath, (str, compat_str)):
  172. n = _find_xpath(xpath)
  173. else:
  174. for xp in xpath:
  175. n = _find_xpath(xp)
  176. if n is not None:
  177. break
  178. if n is None:
  179. if default is not NO_DEFAULT:
  180. return default
  181. elif fatal:
  182. name = xpath if name is None else name
  183. raise ExtractorError('Could not find XML element %s' % name)
  184. else:
  185. return None
  186. return n
  187. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  188. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  189. if n is None or n == default:
  190. return n
  191. if n.text is None:
  192. if default is not NO_DEFAULT:
  193. return default
  194. elif fatal:
  195. name = xpath if name is None else name
  196. raise ExtractorError('Could not find XML element\'s text %s' % name)
  197. else:
  198. return None
  199. return n.text
  200. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  201. n = find_xpath_attr(node, xpath, key)
  202. if n is None:
  203. if default is not NO_DEFAULT:
  204. return default
  205. elif fatal:
  206. name = '%s[@%s]' % (xpath, key) if name is None else name
  207. raise ExtractorError('Could not find XML attribute %s' % name)
  208. else:
  209. return None
  210. return n.attrib[key]
  211. def get_element_by_id(id, html):
  212. """Return the content of the tag with the specified ID in the passed HTML document"""
  213. return get_element_by_attribute('id', id, html)
  214. def get_element_by_attribute(attribute, value, html):
  215. """Return the content of the tag with the specified attribute in the passed HTML document"""
  216. m = re.search(r'''(?xs)
  217. <([a-zA-Z0-9:._-]+)
  218. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  219. \s+%s=['"]?%s['"]?
  220. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  221. \s*>
  222. (?P<content>.*?)
  223. </\1>
  224. ''' % (re.escape(attribute), re.escape(value)), html)
  225. if not m:
  226. return None
  227. res = m.group('content')
  228. if res.startswith('"') or res.startswith("'"):
  229. res = res[1:-1]
  230. return unescapeHTML(res)
  231. def clean_html(html):
  232. """Clean an HTML snippet into a readable string"""
  233. if html is None: # Convenience for sanitizing descriptions etc.
  234. return html
  235. # Newline vs <br />
  236. html = html.replace('\n', ' ')
  237. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  238. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  239. # Strip html tags
  240. html = re.sub('<.*?>', '', html)
  241. # Replace html entities
  242. html = unescapeHTML(html)
  243. return html.strip()
  244. def sanitize_open(filename, open_mode):
  245. """Try to open the given filename, and slightly tweak it if this fails.
  246. Attempts to open the given filename. If this fails, it tries to change
  247. the filename slightly, step by step, until it's either able to open it
  248. or it fails and raises a final exception, like the standard open()
  249. function.
  250. It returns the tuple (stream, definitive_file_name).
  251. """
  252. try:
  253. if filename == '-':
  254. if sys.platform == 'win32':
  255. import msvcrt
  256. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  257. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  258. stream = open(encodeFilename(filename), open_mode)
  259. return (stream, filename)
  260. except (IOError, OSError) as err:
  261. if err.errno in (errno.EACCES,):
  262. raise
  263. # In case of error, try to remove win32 forbidden chars
  264. alt_filename = sanitize_path(filename)
  265. if alt_filename == filename:
  266. raise
  267. else:
  268. # An exception here should be caught in the caller
  269. stream = open(encodeFilename(alt_filename), open_mode)
  270. return (stream, alt_filename)
  271. def timeconvert(timestr):
  272. """Convert RFC 2822 defined time string into system timestamp"""
  273. timestamp = None
  274. timetuple = email.utils.parsedate_tz(timestr)
  275. if timetuple is not None:
  276. timestamp = email.utils.mktime_tz(timetuple)
  277. return timestamp
  278. def sanitize_filename(s, restricted=False, is_id=False):
  279. """Sanitizes a string so it could be used as part of a filename.
  280. If restricted is set, use a stricter subset of allowed characters.
  281. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  282. """
  283. def replace_insane(char):
  284. if char == '?' or ord(char) < 32 or ord(char) == 127:
  285. return ''
  286. elif char == '"':
  287. return '' if restricted else '\''
  288. elif char == ':':
  289. return '_-' if restricted else ' -'
  290. elif char in '\\/|*<>':
  291. return '_'
  292. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  293. return '_'
  294. if restricted and ord(char) > 127:
  295. return '_'
  296. return char
  297. # Handle timestamps
  298. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  299. result = ''.join(map(replace_insane, s))
  300. if not is_id:
  301. while '__' in result:
  302. result = result.replace('__', '_')
  303. result = result.strip('_')
  304. # Common case of "Foreign band name - English song title"
  305. if restricted and result.startswith('-_'):
  306. result = result[2:]
  307. if result.startswith('-'):
  308. result = '_' + result[len('-'):]
  309. result = result.lstrip('.')
  310. if not result:
  311. result = '_'
  312. return result
  313. def sanitize_path(s):
  314. """Sanitizes and normalizes path on Windows"""
  315. if sys.platform != 'win32':
  316. return s
  317. drive_or_unc, _ = os.path.splitdrive(s)
  318. if sys.version_info < (2, 7) and not drive_or_unc:
  319. drive_or_unc, _ = os.path.splitunc(s)
  320. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  321. if drive_or_unc:
  322. norm_path.pop(0)
  323. sanitized_path = [
  324. path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
  325. for path_part in norm_path]
  326. if drive_or_unc:
  327. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  328. return os.path.join(*sanitized_path)
  329. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  330. # unwanted failures due to missing protocol
  331. def sanitized_Request(url, *args, **kwargs):
  332. return compat_urllib_request.Request(
  333. 'http:%s' % url if url.startswith('//') else url, *args, **kwargs)
  334. def orderedSet(iterable):
  335. """ Remove all duplicates from the input iterable """
  336. res = []
  337. for el in iterable:
  338. if el not in res:
  339. res.append(el)
  340. return res
  341. def _htmlentity_transform(entity):
  342. """Transforms an HTML entity to a character."""
  343. # Known non-numeric HTML entity
  344. if entity in compat_html_entities.name2codepoint:
  345. return compat_chr(compat_html_entities.name2codepoint[entity])
  346. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  347. if mobj is not None:
  348. numstr = mobj.group(1)
  349. if numstr.startswith('x'):
  350. base = 16
  351. numstr = '0%s' % numstr
  352. else:
  353. base = 10
  354. # See https://github.com/rg3/youtube-dl/issues/7518
  355. try:
  356. return compat_chr(int(numstr, base))
  357. except ValueError:
  358. pass
  359. # Unknown entity in name, return its literal representation
  360. return '&%s;' % entity
  361. def unescapeHTML(s):
  362. if s is None:
  363. return None
  364. assert type(s) == compat_str
  365. return re.sub(
  366. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  367. def get_subprocess_encoding():
  368. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  369. # For subprocess calls, encode with locale encoding
  370. # Refer to http://stackoverflow.com/a/9951851/35070
  371. encoding = preferredencoding()
  372. else:
  373. encoding = sys.getfilesystemencoding()
  374. if encoding is None:
  375. encoding = 'utf-8'
  376. return encoding
  377. def encodeFilename(s, for_subprocess=False):
  378. """
  379. @param s The name of the file
  380. """
  381. assert type(s) == compat_str
  382. # Python 3 has a Unicode API
  383. if sys.version_info >= (3, 0):
  384. return s
  385. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  386. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  387. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  388. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  389. return s
  390. return s.encode(get_subprocess_encoding(), 'ignore')
  391. def decodeFilename(b, for_subprocess=False):
  392. if sys.version_info >= (3, 0):
  393. return b
  394. if not isinstance(b, bytes):
  395. return b
  396. return b.decode(get_subprocess_encoding(), 'ignore')
  397. def encodeArgument(s):
  398. if not isinstance(s, compat_str):
  399. # Legacy code that uses byte strings
  400. # Uncomment the following line after fixing all post processors
  401. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  402. s = s.decode('ascii')
  403. return encodeFilename(s, True)
  404. def decodeArgument(b):
  405. return decodeFilename(b, True)
  406. def decodeOption(optval):
  407. if optval is None:
  408. return optval
  409. if isinstance(optval, bytes):
  410. optval = optval.decode(preferredencoding())
  411. assert isinstance(optval, compat_str)
  412. return optval
  413. def formatSeconds(secs):
  414. if secs > 3600:
  415. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  416. elif secs > 60:
  417. return '%d:%02d' % (secs // 60, secs % 60)
  418. else:
  419. return '%d' % secs
  420. def make_HTTPS_handler(params, **kwargs):
  421. opts_no_check_certificate = params.get('nocheckcertificate', False)
  422. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  423. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  424. if opts_no_check_certificate:
  425. context.check_hostname = False
  426. context.verify_mode = ssl.CERT_NONE
  427. try:
  428. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  429. except TypeError:
  430. # Python 2.7.8
  431. # (create_default_context present but HTTPSHandler has no context=)
  432. pass
  433. if sys.version_info < (3, 2):
  434. return YoutubeDLHTTPSHandler(params, **kwargs)
  435. else: # Python < 3.4
  436. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  437. context.verify_mode = (ssl.CERT_NONE
  438. if opts_no_check_certificate
  439. else ssl.CERT_REQUIRED)
  440. context.set_default_verify_paths()
  441. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  442. def bug_reports_message():
  443. if ytdl_is_updateable():
  444. update_cmd = 'type youtube-dl -U to update'
  445. else:
  446. update_cmd = 'see https://yt-dl.org/update on how to update'
  447. msg = '; please report this issue on https://yt-dl.org/bug .'
  448. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  449. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  450. return msg
  451. class ExtractorError(Exception):
  452. """Error during info extraction."""
  453. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  454. """ tb, if given, is the original traceback (so that it can be printed out).
  455. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  456. """
  457. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  458. expected = True
  459. if video_id is not None:
  460. msg = video_id + ': ' + msg
  461. if cause:
  462. msg += ' (caused by %r)' % cause
  463. if not expected:
  464. msg += bug_reports_message()
  465. super(ExtractorError, self).__init__(msg)
  466. self.traceback = tb
  467. self.exc_info = sys.exc_info() # preserve original exception
  468. self.cause = cause
  469. self.video_id = video_id
  470. def format_traceback(self):
  471. if self.traceback is None:
  472. return None
  473. return ''.join(traceback.format_tb(self.traceback))
  474. class UnsupportedError(ExtractorError):
  475. def __init__(self, url):
  476. super(UnsupportedError, self).__init__(
  477. 'Unsupported URL: %s' % url, expected=True)
  478. self.url = url
  479. class RegexNotFoundError(ExtractorError):
  480. """Error when a regex didn't match"""
  481. pass
  482. class DownloadError(Exception):
  483. """Download Error exception.
  484. This exception may be thrown by FileDownloader objects if they are not
  485. configured to continue on errors. They will contain the appropriate
  486. error message.
  487. """
  488. def __init__(self, msg, exc_info=None):
  489. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  490. super(DownloadError, self).__init__(msg)
  491. self.exc_info = exc_info
  492. class SameFileError(Exception):
  493. """Same File exception.
  494. This exception will be thrown by FileDownloader objects if they detect
  495. multiple files would have to be downloaded to the same file on disk.
  496. """
  497. pass
  498. class PostProcessingError(Exception):
  499. """Post Processing exception.
  500. This exception may be raised by PostProcessor's .run() method to
  501. indicate an error in the postprocessing task.
  502. """
  503. def __init__(self, msg):
  504. self.msg = msg
  505. class MaxDownloadsReached(Exception):
  506. """ --max-downloads limit has been reached. """
  507. pass
  508. class UnavailableVideoError(Exception):
  509. """Unavailable Format exception.
  510. This exception will be thrown when a video is requested
  511. in a format that is not available for that video.
  512. """
  513. pass
  514. class ContentTooShortError(Exception):
  515. """Content Too Short exception.
  516. This exception may be raised by FileDownloader objects when a file they
  517. download is too small for what the server announced first, indicating
  518. the connection was probably interrupted.
  519. """
  520. def __init__(self, downloaded, expected):
  521. # Both in bytes
  522. self.downloaded = downloaded
  523. self.expected = expected
  524. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  525. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  526. # expected HTTP responses to meet HTTP/1.0 or later (see also
  527. # https://github.com/rg3/youtube-dl/issues/6727)
  528. if sys.version_info < (3, 0):
  529. kwargs[b'strict'] = True
  530. hc = http_class(*args, **kwargs)
  531. source_address = ydl_handler._params.get('source_address')
  532. if source_address is not None:
  533. sa = (source_address, 0)
  534. if hasattr(hc, 'source_address'): # Python 2.7+
  535. hc.source_address = sa
  536. else: # Python 2.6
  537. def _hc_connect(self, *args, **kwargs):
  538. sock = compat_socket_create_connection(
  539. (self.host, self.port), self.timeout, sa)
  540. if is_https:
  541. self.sock = ssl.wrap_socket(
  542. sock, self.key_file, self.cert_file,
  543. ssl_version=ssl.PROTOCOL_TLSv1)
  544. else:
  545. self.sock = sock
  546. hc.connect = functools.partial(_hc_connect, hc)
  547. return hc
  548. def handle_youtubedl_headers(headers):
  549. filtered_headers = headers
  550. if 'Youtubedl-no-compression' in filtered_headers:
  551. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  552. del filtered_headers['Youtubedl-no-compression']
  553. return filtered_headers
  554. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  555. """Handler for HTTP requests and responses.
  556. This class, when installed with an OpenerDirector, automatically adds
  557. the standard headers to every HTTP request and handles gzipped and
  558. deflated responses from web servers. If compression is to be avoided in
  559. a particular request, the original request in the program code only has
  560. to include the HTTP header "Youtubedl-no-compression", which will be
  561. removed before making the real request.
  562. Part of this code was copied from:
  563. http://techknack.net/python-urllib2-handlers/
  564. Andrew Rowls, the author of that code, agreed to release it to the
  565. public domain.
  566. """
  567. def __init__(self, params, *args, **kwargs):
  568. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  569. self._params = params
  570. def http_open(self, req):
  571. return self.do_open(functools.partial(
  572. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  573. req)
  574. @staticmethod
  575. def deflate(data):
  576. try:
  577. return zlib.decompress(data, -zlib.MAX_WBITS)
  578. except zlib.error:
  579. return zlib.decompress(data)
  580. @staticmethod
  581. def addinfourl_wrapper(stream, headers, url, code):
  582. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  583. return compat_urllib_request.addinfourl(stream, headers, url, code)
  584. ret = compat_urllib_request.addinfourl(stream, headers, url)
  585. ret.code = code
  586. return ret
  587. def http_request(self, req):
  588. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  589. # always respected by websites, some tend to give out URLs with non percent-encoded
  590. # non-ASCII characters (see telemb.py, ard.py [#3412])
  591. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  592. # To work around aforementioned issue we will replace request's original URL with
  593. # percent-encoded one
  594. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  595. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  596. url = req.get_full_url()
  597. url_escaped = escape_url(url)
  598. # Substitute URL if any change after escaping
  599. if url != url_escaped:
  600. req_type = HEADRequest if req.get_method() == 'HEAD' else compat_urllib_request.Request
  601. new_req = req_type(
  602. url_escaped, data=req.data, headers=req.headers,
  603. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  604. new_req.timeout = req.timeout
  605. req = new_req
  606. for h, v in std_headers.items():
  607. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  608. # The dict keys are capitalized because of this bug by urllib
  609. if h.capitalize() not in req.headers:
  610. req.add_header(h, v)
  611. req.headers = handle_youtubedl_headers(req.headers)
  612. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  613. # Python 2.6 is brain-dead when it comes to fragments
  614. req._Request__original = req._Request__original.partition('#')[0]
  615. req._Request__r_type = req._Request__r_type.partition('#')[0]
  616. return req
  617. def http_response(self, req, resp):
  618. old_resp = resp
  619. # gzip
  620. if resp.headers.get('Content-encoding', '') == 'gzip':
  621. content = resp.read()
  622. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  623. try:
  624. uncompressed = io.BytesIO(gz.read())
  625. except IOError as original_ioerror:
  626. # There may be junk add the end of the file
  627. # See http://stackoverflow.com/q/4928560/35070 for details
  628. for i in range(1, 1024):
  629. try:
  630. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  631. uncompressed = io.BytesIO(gz.read())
  632. except IOError:
  633. continue
  634. break
  635. else:
  636. raise original_ioerror
  637. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  638. resp.msg = old_resp.msg
  639. del resp.headers['Content-encoding']
  640. # deflate
  641. if resp.headers.get('Content-encoding', '') == 'deflate':
  642. gz = io.BytesIO(self.deflate(resp.read()))
  643. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  644. resp.msg = old_resp.msg
  645. del resp.headers['Content-encoding']
  646. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  647. # https://github.com/rg3/youtube-dl/issues/6457).
  648. if 300 <= resp.code < 400:
  649. location = resp.headers.get('Location')
  650. if location:
  651. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  652. if sys.version_info >= (3, 0):
  653. location = location.encode('iso-8859-1').decode('utf-8')
  654. location_escaped = escape_url(location)
  655. if location != location_escaped:
  656. del resp.headers['Location']
  657. resp.headers['Location'] = location_escaped
  658. return resp
  659. https_request = http_request
  660. https_response = http_response
  661. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  662. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  663. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  664. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  665. self._params = params
  666. def https_open(self, req):
  667. kwargs = {}
  668. if hasattr(self, '_context'): # python > 2.6
  669. kwargs['context'] = self._context
  670. if hasattr(self, '_check_hostname'): # python 3.x
  671. kwargs['check_hostname'] = self._check_hostname
  672. return self.do_open(functools.partial(
  673. _create_http_connection, self, self._https_conn_class, True),
  674. req, **kwargs)
  675. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  676. def __init__(self, cookiejar=None):
  677. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  678. def http_response(self, request, response):
  679. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  680. # characters in Set-Cookie HTTP header of last response (see
  681. # https://github.com/rg3/youtube-dl/issues/6769).
  682. # In order to at least prevent crashing we will percent encode Set-Cookie
  683. # header before HTTPCookieProcessor starts processing it.
  684. # if sys.version_info < (3, 0) and response.headers:
  685. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  686. # set_cookie = response.headers.get(set_cookie_header)
  687. # if set_cookie:
  688. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  689. # if set_cookie != set_cookie_escaped:
  690. # del response.headers[set_cookie_header]
  691. # response.headers[set_cookie_header] = set_cookie_escaped
  692. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  693. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  694. https_response = http_response
  695. def parse_iso8601(date_str, delimiter='T', timezone=None):
  696. """ Return a UNIX timestamp from the given date """
  697. if date_str is None:
  698. return None
  699. date_str = re.sub(r'\.[0-9]+', '', date_str)
  700. if timezone is None:
  701. m = re.search(
  702. r'(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  703. date_str)
  704. if not m:
  705. timezone = datetime.timedelta()
  706. else:
  707. date_str = date_str[:-len(m.group(0))]
  708. if not m.group('sign'):
  709. timezone = datetime.timedelta()
  710. else:
  711. sign = 1 if m.group('sign') == '+' else -1
  712. timezone = datetime.timedelta(
  713. hours=sign * int(m.group('hours')),
  714. minutes=sign * int(m.group('minutes')))
  715. try:
  716. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  717. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  718. return calendar.timegm(dt.timetuple())
  719. except ValueError:
  720. pass
  721. def unified_strdate(date_str, day_first=True):
  722. """Return a string with the date in the format YYYYMMDD"""
  723. if date_str is None:
  724. return None
  725. upload_date = None
  726. # Replace commas
  727. date_str = date_str.replace(',', ' ')
  728. # %z (UTC offset) is only supported in python>=3.2
  729. if not re.match(r'^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$', date_str):
  730. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  731. # Remove AM/PM + timezone
  732. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  733. format_expressions = [
  734. '%d %B %Y',
  735. '%d %b %Y',
  736. '%B %d %Y',
  737. '%b %d %Y',
  738. '%b %dst %Y %I:%M',
  739. '%b %dnd %Y %I:%M',
  740. '%b %dth %Y %I:%M',
  741. '%Y %m %d',
  742. '%Y-%m-%d',
  743. '%Y/%m/%d',
  744. '%Y/%m/%d %H:%M:%S',
  745. '%Y-%m-%d %H:%M:%S',
  746. '%Y-%m-%d %H:%M:%S.%f',
  747. '%d.%m.%Y %H:%M',
  748. '%d.%m.%Y %H.%M',
  749. '%Y-%m-%dT%H:%M:%SZ',
  750. '%Y-%m-%dT%H:%M:%S.%fZ',
  751. '%Y-%m-%dT%H:%M:%S.%f0Z',
  752. '%Y-%m-%dT%H:%M:%S',
  753. '%Y-%m-%dT%H:%M:%S.%f',
  754. '%Y-%m-%dT%H:%M',
  755. ]
  756. if day_first:
  757. format_expressions.extend([
  758. '%d-%m-%Y',
  759. '%d.%m.%Y',
  760. '%d/%m/%Y',
  761. '%d/%m/%y',
  762. '%d/%m/%Y %H:%M:%S',
  763. ])
  764. else:
  765. format_expressions.extend([
  766. '%m-%d-%Y',
  767. '%m.%d.%Y',
  768. '%m/%d/%Y',
  769. '%m/%d/%y',
  770. '%m/%d/%Y %H:%M:%S',
  771. ])
  772. for expression in format_expressions:
  773. try:
  774. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  775. except ValueError:
  776. pass
  777. if upload_date is None:
  778. timetuple = email.utils.parsedate_tz(date_str)
  779. if timetuple:
  780. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  781. if upload_date is not None:
  782. return compat_str(upload_date)
  783. def determine_ext(url, default_ext='unknown_video'):
  784. if url is None:
  785. return default_ext
  786. guess = url.partition('?')[0].rpartition('.')[2]
  787. if re.match(r'^[A-Za-z0-9]+$', guess):
  788. return guess
  789. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  790. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  791. return guess.rstrip('/')
  792. else:
  793. return default_ext
  794. def subtitles_filename(filename, sub_lang, sub_format):
  795. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  796. def date_from_str(date_str):
  797. """
  798. Return a datetime object from a string in the format YYYYMMDD or
  799. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  800. today = datetime.date.today()
  801. if date_str in ('now', 'today'):
  802. return today
  803. if date_str == 'yesterday':
  804. return today - datetime.timedelta(days=1)
  805. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  806. if match is not None:
  807. sign = match.group('sign')
  808. time = int(match.group('time'))
  809. if sign == '-':
  810. time = -time
  811. unit = match.group('unit')
  812. # A bad approximation?
  813. if unit == 'month':
  814. unit = 'day'
  815. time *= 30
  816. elif unit == 'year':
  817. unit = 'day'
  818. time *= 365
  819. unit += 's'
  820. delta = datetime.timedelta(**{unit: time})
  821. return today + delta
  822. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  823. def hyphenate_date(date_str):
  824. """
  825. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  826. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  827. if match is not None:
  828. return '-'.join(match.groups())
  829. else:
  830. return date_str
  831. class DateRange(object):
  832. """Represents a time interval between two dates"""
  833. def __init__(self, start=None, end=None):
  834. """start and end must be strings in the format accepted by date"""
  835. if start is not None:
  836. self.start = date_from_str(start)
  837. else:
  838. self.start = datetime.datetime.min.date()
  839. if end is not None:
  840. self.end = date_from_str(end)
  841. else:
  842. self.end = datetime.datetime.max.date()
  843. if self.start > self.end:
  844. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  845. @classmethod
  846. def day(cls, day):
  847. """Returns a range that only contains the given day"""
  848. return cls(day, day)
  849. def __contains__(self, date):
  850. """Check if the date is in the range"""
  851. if not isinstance(date, datetime.date):
  852. date = date_from_str(date)
  853. return self.start <= date <= self.end
  854. def __str__(self):
  855. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  856. def platform_name():
  857. """ Returns the platform name as a compat_str """
  858. res = platform.platform()
  859. if isinstance(res, bytes):
  860. res = res.decode(preferredencoding())
  861. assert isinstance(res, compat_str)
  862. return res
  863. def _windows_write_string(s, out):
  864. """ Returns True if the string was written using special methods,
  865. False if it has yet to be written out."""
  866. # Adapted from http://stackoverflow.com/a/3259271/35070
  867. import ctypes
  868. import ctypes.wintypes
  869. WIN_OUTPUT_IDS = {
  870. 1: -11,
  871. 2: -12,
  872. }
  873. try:
  874. fileno = out.fileno()
  875. except AttributeError:
  876. # If the output stream doesn't have a fileno, it's virtual
  877. return False
  878. except io.UnsupportedOperation:
  879. # Some strange Windows pseudo files?
  880. return False
  881. if fileno not in WIN_OUTPUT_IDS:
  882. return False
  883. GetStdHandle = ctypes.WINFUNCTYPE(
  884. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  885. (b'GetStdHandle', ctypes.windll.kernel32))
  886. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  887. WriteConsoleW = ctypes.WINFUNCTYPE(
  888. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  889. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  890. ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
  891. written = ctypes.wintypes.DWORD(0)
  892. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
  893. FILE_TYPE_CHAR = 0x0002
  894. FILE_TYPE_REMOTE = 0x8000
  895. GetConsoleMode = ctypes.WINFUNCTYPE(
  896. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  897. ctypes.POINTER(ctypes.wintypes.DWORD))(
  898. (b'GetConsoleMode', ctypes.windll.kernel32))
  899. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  900. def not_a_console(handle):
  901. if handle == INVALID_HANDLE_VALUE or handle is None:
  902. return True
  903. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  904. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  905. if not_a_console(h):
  906. return False
  907. def next_nonbmp_pos(s):
  908. try:
  909. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  910. except StopIteration:
  911. return len(s)
  912. while s:
  913. count = min(next_nonbmp_pos(s), 1024)
  914. ret = WriteConsoleW(
  915. h, s, count if count else 2, ctypes.byref(written), None)
  916. if ret == 0:
  917. raise OSError('Failed to write string')
  918. if not count: # We just wrote a non-BMP character
  919. assert written.value == 2
  920. s = s[1:]
  921. else:
  922. assert written.value > 0
  923. s = s[written.value:]
  924. return True
  925. def write_string(s, out=None, encoding=None):
  926. if out is None:
  927. out = sys.stderr
  928. assert type(s) == compat_str
  929. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  930. if _windows_write_string(s, out):
  931. return
  932. if ('b' in getattr(out, 'mode', '') or
  933. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  934. byt = s.encode(encoding or preferredencoding(), 'ignore')
  935. out.write(byt)
  936. elif hasattr(out, 'buffer'):
  937. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  938. byt = s.encode(enc, 'ignore')
  939. out.buffer.write(byt)
  940. else:
  941. out.write(s)
  942. out.flush()
  943. def bytes_to_intlist(bs):
  944. if not bs:
  945. return []
  946. if isinstance(bs[0], int): # Python 3
  947. return list(bs)
  948. else:
  949. return [ord(c) for c in bs]
  950. def intlist_to_bytes(xs):
  951. if not xs:
  952. return b''
  953. return struct_pack('%dB' % len(xs), *xs)
  954. # Cross-platform file locking
  955. if sys.platform == 'win32':
  956. import ctypes.wintypes
  957. import msvcrt
  958. class OVERLAPPED(ctypes.Structure):
  959. _fields_ = [
  960. ('Internal', ctypes.wintypes.LPVOID),
  961. ('InternalHigh', ctypes.wintypes.LPVOID),
  962. ('Offset', ctypes.wintypes.DWORD),
  963. ('OffsetHigh', ctypes.wintypes.DWORD),
  964. ('hEvent', ctypes.wintypes.HANDLE),
  965. ]
  966. kernel32 = ctypes.windll.kernel32
  967. LockFileEx = kernel32.LockFileEx
  968. LockFileEx.argtypes = [
  969. ctypes.wintypes.HANDLE, # hFile
  970. ctypes.wintypes.DWORD, # dwFlags
  971. ctypes.wintypes.DWORD, # dwReserved
  972. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  973. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  974. ctypes.POINTER(OVERLAPPED) # Overlapped
  975. ]
  976. LockFileEx.restype = ctypes.wintypes.BOOL
  977. UnlockFileEx = kernel32.UnlockFileEx
  978. UnlockFileEx.argtypes = [
  979. ctypes.wintypes.HANDLE, # hFile
  980. ctypes.wintypes.DWORD, # dwReserved
  981. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  982. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  983. ctypes.POINTER(OVERLAPPED) # Overlapped
  984. ]
  985. UnlockFileEx.restype = ctypes.wintypes.BOOL
  986. whole_low = 0xffffffff
  987. whole_high = 0x7fffffff
  988. def _lock_file(f, exclusive):
  989. overlapped = OVERLAPPED()
  990. overlapped.Offset = 0
  991. overlapped.OffsetHigh = 0
  992. overlapped.hEvent = 0
  993. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  994. handle = msvcrt.get_osfhandle(f.fileno())
  995. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  996. whole_low, whole_high, f._lock_file_overlapped_p):
  997. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  998. def _unlock_file(f):
  999. assert f._lock_file_overlapped_p
  1000. handle = msvcrt.get_osfhandle(f.fileno())
  1001. if not UnlockFileEx(handle, 0,
  1002. whole_low, whole_high, f._lock_file_overlapped_p):
  1003. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1004. else:
  1005. import fcntl
  1006. def _lock_file(f, exclusive):
  1007. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1008. def _unlock_file(f):
  1009. fcntl.flock(f, fcntl.LOCK_UN)
  1010. class locked_file(object):
  1011. def __init__(self, filename, mode, encoding=None):
  1012. assert mode in ['r', 'a', 'w']
  1013. self.f = io.open(filename, mode, encoding=encoding)
  1014. self.mode = mode
  1015. def __enter__(self):
  1016. exclusive = self.mode != 'r'
  1017. try:
  1018. _lock_file(self.f, exclusive)
  1019. except IOError:
  1020. self.f.close()
  1021. raise
  1022. return self
  1023. def __exit__(self, etype, value, traceback):
  1024. try:
  1025. _unlock_file(self.f)
  1026. finally:
  1027. self.f.close()
  1028. def __iter__(self):
  1029. return iter(self.f)
  1030. def write(self, *args):
  1031. return self.f.write(*args)
  1032. def read(self, *args):
  1033. return self.f.read(*args)
  1034. def get_filesystem_encoding():
  1035. encoding = sys.getfilesystemencoding()
  1036. return encoding if encoding is not None else 'utf-8'
  1037. def shell_quote(args):
  1038. quoted_args = []
  1039. encoding = get_filesystem_encoding()
  1040. for a in args:
  1041. if isinstance(a, bytes):
  1042. # We may get a filename encoded with 'encodeFilename'
  1043. a = a.decode(encoding)
  1044. quoted_args.append(pipes.quote(a))
  1045. return ' '.join(quoted_args)
  1046. def smuggle_url(url, data):
  1047. """ Pass additional data in a URL for internal use. """
  1048. sdata = compat_urllib_parse.urlencode(
  1049. {'__youtubedl_smuggle': json.dumps(data)})
  1050. return url + '#' + sdata
  1051. def unsmuggle_url(smug_url, default=None):
  1052. if '#__youtubedl_smuggle' not in smug_url:
  1053. return smug_url, default
  1054. url, _, sdata = smug_url.rpartition('#')
  1055. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1056. data = json.loads(jsond)
  1057. return url, data
  1058. def format_bytes(bytes):
  1059. if bytes is None:
  1060. return 'N/A'
  1061. if type(bytes) is str:
  1062. bytes = float(bytes)
  1063. if bytes == 0.0:
  1064. exponent = 0
  1065. else:
  1066. exponent = int(math.log(bytes, 1024.0))
  1067. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1068. converted = float(bytes) / float(1024 ** exponent)
  1069. return '%.2f%s' % (converted, suffix)
  1070. def parse_filesize(s):
  1071. if s is None:
  1072. return None
  1073. # The lower-case forms are of course incorrect and unofficial,
  1074. # but we support those too
  1075. _UNIT_TABLE = {
  1076. 'B': 1,
  1077. 'b': 1,
  1078. 'KiB': 1024,
  1079. 'KB': 1000,
  1080. 'kB': 1024,
  1081. 'Kb': 1000,
  1082. 'MiB': 1024 ** 2,
  1083. 'MB': 1000 ** 2,
  1084. 'mB': 1024 ** 2,
  1085. 'Mb': 1000 ** 2,
  1086. 'GiB': 1024 ** 3,
  1087. 'GB': 1000 ** 3,
  1088. 'gB': 1024 ** 3,
  1089. 'Gb': 1000 ** 3,
  1090. 'TiB': 1024 ** 4,
  1091. 'TB': 1000 ** 4,
  1092. 'tB': 1024 ** 4,
  1093. 'Tb': 1000 ** 4,
  1094. 'PiB': 1024 ** 5,
  1095. 'PB': 1000 ** 5,
  1096. 'pB': 1024 ** 5,
  1097. 'Pb': 1000 ** 5,
  1098. 'EiB': 1024 ** 6,
  1099. 'EB': 1000 ** 6,
  1100. 'eB': 1024 ** 6,
  1101. 'Eb': 1000 ** 6,
  1102. 'ZiB': 1024 ** 7,
  1103. 'ZB': 1000 ** 7,
  1104. 'zB': 1024 ** 7,
  1105. 'Zb': 1000 ** 7,
  1106. 'YiB': 1024 ** 8,
  1107. 'YB': 1000 ** 8,
  1108. 'yB': 1024 ** 8,
  1109. 'Yb': 1000 ** 8,
  1110. }
  1111. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  1112. m = re.match(
  1113. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  1114. if not m:
  1115. return None
  1116. num_str = m.group('num').replace(',', '.')
  1117. mult = _UNIT_TABLE[m.group('unit')]
  1118. return int(float(num_str) * mult)
  1119. def month_by_name(name):
  1120. """ Return the number of a month by (locale-independently) English name """
  1121. try:
  1122. return ENGLISH_MONTH_NAMES.index(name) + 1
  1123. except ValueError:
  1124. return None
  1125. def month_by_abbreviation(abbrev):
  1126. """ Return the number of a month by (locale-independently) English
  1127. abbreviations """
  1128. try:
  1129. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1130. except ValueError:
  1131. return None
  1132. def fix_xml_ampersands(xml_str):
  1133. """Replace all the '&' by '&amp;' in XML"""
  1134. return re.sub(
  1135. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1136. '&amp;',
  1137. xml_str)
  1138. def setproctitle(title):
  1139. assert isinstance(title, compat_str)
  1140. try:
  1141. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1142. except OSError:
  1143. return
  1144. title_bytes = title.encode('utf-8')
  1145. buf = ctypes.create_string_buffer(len(title_bytes))
  1146. buf.value = title_bytes
  1147. try:
  1148. libc.prctl(15, buf, 0, 0, 0)
  1149. except AttributeError:
  1150. return # Strange libc, just skip this
  1151. def remove_start(s, start):
  1152. if s.startswith(start):
  1153. return s[len(start):]
  1154. return s
  1155. def remove_end(s, end):
  1156. if s.endswith(end):
  1157. return s[:-len(end)]
  1158. return s
  1159. def remove_quotes(s):
  1160. if s is None or len(s) < 2:
  1161. return s
  1162. for quote in ('"', "'", ):
  1163. if s[0] == quote and s[-1] == quote:
  1164. return s[1:-1]
  1165. return s
  1166. def url_basename(url):
  1167. path = compat_urlparse.urlparse(url).path
  1168. return path.strip('/').split('/')[-1]
  1169. class HEADRequest(compat_urllib_request.Request):
  1170. def get_method(self):
  1171. return 'HEAD'
  1172. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1173. if get_attr:
  1174. if v is not None:
  1175. v = getattr(v, get_attr, None)
  1176. if v == '':
  1177. v = None
  1178. if v is None:
  1179. return default
  1180. try:
  1181. return int(v) * invscale // scale
  1182. except ValueError:
  1183. return default
  1184. def str_or_none(v, default=None):
  1185. return default if v is None else compat_str(v)
  1186. def str_to_int(int_str):
  1187. """ A more relaxed version of int_or_none """
  1188. if int_str is None:
  1189. return None
  1190. int_str = re.sub(r'[,\.\+]', '', int_str)
  1191. return int(int_str)
  1192. def float_or_none(v, scale=1, invscale=1, default=None):
  1193. if v is None:
  1194. return default
  1195. try:
  1196. return float(v) * invscale / scale
  1197. except ValueError:
  1198. return default
  1199. def parse_duration(s):
  1200. if not isinstance(s, compat_basestring):
  1201. return None
  1202. s = s.strip()
  1203. m = re.match(
  1204. r'''(?ix)(?:P?T)?
  1205. (?:
  1206. (?P<only_mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*|
  1207. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1208. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?\.?|minutes?)\s*|
  1209. (?:
  1210. (?:
  1211. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1212. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1213. )?
  1214. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1215. )?
  1216. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1217. )$''', s)
  1218. if not m:
  1219. return None
  1220. res = 0
  1221. if m.group('only_mins'):
  1222. return float_or_none(m.group('only_mins'), invscale=60)
  1223. if m.group('only_hours'):
  1224. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1225. if m.group('secs'):
  1226. res += int(m.group('secs'))
  1227. if m.group('mins_reversed'):
  1228. res += int(m.group('mins_reversed')) * 60
  1229. if m.group('mins'):
  1230. res += int(m.group('mins')) * 60
  1231. if m.group('hours'):
  1232. res += int(m.group('hours')) * 60 * 60
  1233. if m.group('hours_reversed'):
  1234. res += int(m.group('hours_reversed')) * 60 * 60
  1235. if m.group('days'):
  1236. res += int(m.group('days')) * 24 * 60 * 60
  1237. if m.group('ms'):
  1238. res += float(m.group('ms'))
  1239. return res
  1240. def prepend_extension(filename, ext, expected_real_ext=None):
  1241. name, real_ext = os.path.splitext(filename)
  1242. return (
  1243. '{0}.{1}{2}'.format(name, ext, real_ext)
  1244. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1245. else '{0}.{1}'.format(filename, ext))
  1246. def replace_extension(filename, ext, expected_real_ext=None):
  1247. name, real_ext = os.path.splitext(filename)
  1248. return '{0}.{1}'.format(
  1249. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1250. ext)
  1251. def check_executable(exe, args=[]):
  1252. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1253. args can be a list of arguments for a short output (like -version) """
  1254. try:
  1255. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1256. except OSError:
  1257. return False
  1258. return exe
  1259. def get_exe_version(exe, args=['--version'],
  1260. version_re=None, unrecognized='present'):
  1261. """ Returns the version of the specified executable,
  1262. or False if the executable is not present """
  1263. try:
  1264. out, _ = subprocess.Popen(
  1265. [encodeArgument(exe)] + args,
  1266. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1267. except OSError:
  1268. return False
  1269. if isinstance(out, bytes): # Python 2.x
  1270. out = out.decode('ascii', 'ignore')
  1271. return detect_exe_version(out, version_re, unrecognized)
  1272. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1273. assert isinstance(output, compat_str)
  1274. if version_re is None:
  1275. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1276. m = re.search(version_re, output)
  1277. if m:
  1278. return m.group(1)
  1279. else:
  1280. return unrecognized
  1281. class PagedList(object):
  1282. def __len__(self):
  1283. # This is only useful for tests
  1284. return len(self.getslice())
  1285. class OnDemandPagedList(PagedList):
  1286. def __init__(self, pagefunc, pagesize, use_cache=False):
  1287. self._pagefunc = pagefunc
  1288. self._pagesize = pagesize
  1289. self._use_cache = use_cache
  1290. if use_cache:
  1291. self._cache = {}
  1292. def getslice(self, start=0, end=None):
  1293. res = []
  1294. for pagenum in itertools.count(start // self._pagesize):
  1295. firstid = pagenum * self._pagesize
  1296. nextfirstid = pagenum * self._pagesize + self._pagesize
  1297. if start >= nextfirstid:
  1298. continue
  1299. page_results = None
  1300. if self._use_cache:
  1301. page_results = self._cache.get(pagenum)
  1302. if page_results is None:
  1303. page_results = list(self._pagefunc(pagenum))
  1304. if self._use_cache:
  1305. self._cache[pagenum] = page_results
  1306. startv = (
  1307. start % self._pagesize
  1308. if firstid <= start < nextfirstid
  1309. else 0)
  1310. endv = (
  1311. ((end - 1) % self._pagesize) + 1
  1312. if (end is not None and firstid <= end <= nextfirstid)
  1313. else None)
  1314. if startv != 0 or endv is not None:
  1315. page_results = page_results[startv:endv]
  1316. res.extend(page_results)
  1317. # A little optimization - if current page is not "full", ie. does
  1318. # not contain page_size videos then we can assume that this page
  1319. # is the last one - there are no more ids on further pages -
  1320. # i.e. no need to query again.
  1321. if len(page_results) + startv < self._pagesize:
  1322. break
  1323. # If we got the whole page, but the next page is not interesting,
  1324. # break out early as well
  1325. if end == nextfirstid:
  1326. break
  1327. return res
  1328. class InAdvancePagedList(PagedList):
  1329. def __init__(self, pagefunc, pagecount, pagesize):
  1330. self._pagefunc = pagefunc
  1331. self._pagecount = pagecount
  1332. self._pagesize = pagesize
  1333. def getslice(self, start=0, end=None):
  1334. res = []
  1335. start_page = start // self._pagesize
  1336. end_page = (
  1337. self._pagecount if end is None else (end // self._pagesize + 1))
  1338. skip_elems = start - start_page * self._pagesize
  1339. only_more = None if end is None else end - start
  1340. for pagenum in range(start_page, end_page):
  1341. page = list(self._pagefunc(pagenum))
  1342. if skip_elems:
  1343. page = page[skip_elems:]
  1344. skip_elems = None
  1345. if only_more is not None:
  1346. if len(page) < only_more:
  1347. only_more -= len(page)
  1348. else:
  1349. page = page[:only_more]
  1350. res.extend(page)
  1351. break
  1352. res.extend(page)
  1353. return res
  1354. def uppercase_escape(s):
  1355. unicode_escape = codecs.getdecoder('unicode_escape')
  1356. return re.sub(
  1357. r'\\U[0-9a-fA-F]{8}',
  1358. lambda m: unicode_escape(m.group(0))[0],
  1359. s)
  1360. def lowercase_escape(s):
  1361. unicode_escape = codecs.getdecoder('unicode_escape')
  1362. return re.sub(
  1363. r'\\u[0-9a-fA-F]{4}',
  1364. lambda m: unicode_escape(m.group(0))[0],
  1365. s)
  1366. def escape_rfc3986(s):
  1367. """Escape non-ASCII characters as suggested by RFC 3986"""
  1368. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1369. s = s.encode('utf-8')
  1370. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1371. def escape_url(url):
  1372. """Escape URL as suggested by RFC 3986"""
  1373. url_parsed = compat_urllib_parse_urlparse(url)
  1374. return url_parsed._replace(
  1375. path=escape_rfc3986(url_parsed.path),
  1376. params=escape_rfc3986(url_parsed.params),
  1377. query=escape_rfc3986(url_parsed.query),
  1378. fragment=escape_rfc3986(url_parsed.fragment)
  1379. ).geturl()
  1380. try:
  1381. struct.pack('!I', 0)
  1382. except TypeError:
  1383. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1384. def struct_pack(spec, *args):
  1385. if isinstance(spec, compat_str):
  1386. spec = spec.encode('ascii')
  1387. return struct.pack(spec, *args)
  1388. def struct_unpack(spec, *args):
  1389. if isinstance(spec, compat_str):
  1390. spec = spec.encode('ascii')
  1391. return struct.unpack(spec, *args)
  1392. else:
  1393. struct_pack = struct.pack
  1394. struct_unpack = struct.unpack
  1395. def read_batch_urls(batch_fd):
  1396. def fixup(url):
  1397. if not isinstance(url, compat_str):
  1398. url = url.decode('utf-8', 'replace')
  1399. BOM_UTF8 = '\xef\xbb\xbf'
  1400. if url.startswith(BOM_UTF8):
  1401. url = url[len(BOM_UTF8):]
  1402. url = url.strip()
  1403. if url.startswith(('#', ';', ']')):
  1404. return False
  1405. return url
  1406. with contextlib.closing(batch_fd) as fd:
  1407. return [url for url in map(fixup, fd) if url]
  1408. def urlencode_postdata(*args, **kargs):
  1409. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1410. def update_url_query(url, query):
  1411. parsed_url = compat_urlparse.urlparse(url)
  1412. qs = compat_parse_qs(parsed_url.query)
  1413. qs.update(query)
  1414. return compat_urlparse.urlunparse(parsed_url._replace(
  1415. query=compat_urllib_parse.urlencode(qs, True)))
  1416. def encode_dict(d, encoding='utf-8'):
  1417. def encode(v):
  1418. return v.encode(encoding) if isinstance(v, compat_basestring) else v
  1419. return dict((encode(k), encode(v)) for k, v in d.items())
  1420. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1421. if isinstance(key_or_keys, (list, tuple)):
  1422. for key in key_or_keys:
  1423. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1424. continue
  1425. return d[key]
  1426. return default
  1427. return d.get(key_or_keys, default)
  1428. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1429. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1430. US_RATINGS = {
  1431. 'G': 0,
  1432. 'PG': 10,
  1433. 'PG-13': 13,
  1434. 'R': 16,
  1435. 'NC': 18,
  1436. }
  1437. def parse_age_limit(s):
  1438. if s is None:
  1439. return None
  1440. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1441. return int(m.group('age')) if m else US_RATINGS.get(s)
  1442. def strip_jsonp(code):
  1443. return re.sub(
  1444. r'(?s)^[a-zA-Z0-9_.]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1445. def js_to_json(code):
  1446. def fix_kv(m):
  1447. v = m.group(0)
  1448. if v in ('true', 'false', 'null'):
  1449. return v
  1450. if v.startswith('"'):
  1451. v = re.sub(r"\\'", "'", v[1:-1])
  1452. elif v.startswith("'"):
  1453. v = v[1:-1]
  1454. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1455. '\\\\': '\\\\',
  1456. "\\'": "'",
  1457. '"': '\\"',
  1458. }[m.group(0)], v)
  1459. return '"%s"' % v
  1460. res = re.sub(r'''(?x)
  1461. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1462. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1463. [a-zA-Z_][.a-zA-Z_0-9]*
  1464. ''', fix_kv, code)
  1465. res = re.sub(r',(\s*[\]}])', lambda m: m.group(1), res)
  1466. return res
  1467. def qualities(quality_ids):
  1468. """ Get a numeric quality value out of a list of possible values """
  1469. def q(qid):
  1470. try:
  1471. return quality_ids.index(qid)
  1472. except ValueError:
  1473. return -1
  1474. return q
  1475. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1476. def limit_length(s, length):
  1477. """ Add ellipses to overly long strings """
  1478. if s is None:
  1479. return None
  1480. ELLIPSES = '...'
  1481. if len(s) > length:
  1482. return s[:length - len(ELLIPSES)] + ELLIPSES
  1483. return s
  1484. def version_tuple(v):
  1485. return tuple(int(e) for e in re.split(r'[-.]', v))
  1486. def is_outdated_version(version, limit, assume_new=True):
  1487. if not version:
  1488. return not assume_new
  1489. try:
  1490. return version_tuple(version) < version_tuple(limit)
  1491. except ValueError:
  1492. return not assume_new
  1493. def ytdl_is_updateable():
  1494. """ Returns if youtube-dl can be updated with -U """
  1495. from zipimport import zipimporter
  1496. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1497. def args_to_str(args):
  1498. # Get a short string representation for a subprocess command
  1499. return ' '.join(shlex_quote(a) for a in args)
  1500. def error_to_compat_str(err):
  1501. err_str = str(err)
  1502. # On python 2 error byte string must be decoded with proper
  1503. # encoding rather than ascii
  1504. if sys.version_info[0] < 3:
  1505. err_str = err_str.decode(preferredencoding())
  1506. return err_str
  1507. def mimetype2ext(mt):
  1508. ext = {
  1509. 'audio/mp4': 'm4a',
  1510. }.get(mt)
  1511. if ext is not None:
  1512. return ext
  1513. _, _, res = mt.rpartition('/')
  1514. return {
  1515. '3gpp': '3gp',
  1516. 'smptett+xml': 'tt',
  1517. 'srt': 'srt',
  1518. 'ttaf+xml': 'dfxp',
  1519. 'ttml+xml': 'ttml',
  1520. 'vtt': 'vtt',
  1521. 'x-flv': 'flv',
  1522. 'x-mp4-fragmented': 'mp4',
  1523. 'x-ms-wmv': 'wmv',
  1524. }.get(res, res)
  1525. def urlhandle_detect_ext(url_handle):
  1526. try:
  1527. url_handle.headers
  1528. getheader = lambda h: url_handle.headers[h]
  1529. except AttributeError: # Python < 3
  1530. getheader = url_handle.info().getheader
  1531. cd = getheader('Content-Disposition')
  1532. if cd:
  1533. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1534. if m:
  1535. e = determine_ext(m.group('filename'), default_ext=None)
  1536. if e:
  1537. return e
  1538. return mimetype2ext(getheader('Content-Type'))
  1539. def encode_data_uri(data, mime_type):
  1540. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  1541. def age_restricted(content_limit, age_limit):
  1542. """ Returns True iff the content should be blocked """
  1543. if age_limit is None: # No limit set
  1544. return False
  1545. if content_limit is None:
  1546. return False # Content available for everyone
  1547. return age_limit < content_limit
  1548. def is_html(first_bytes):
  1549. """ Detect whether a file contains HTML by examining its first bytes. """
  1550. BOMS = [
  1551. (b'\xef\xbb\xbf', 'utf-8'),
  1552. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1553. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1554. (b'\xff\xfe', 'utf-16-le'),
  1555. (b'\xfe\xff', 'utf-16-be'),
  1556. ]
  1557. for bom, enc in BOMS:
  1558. if first_bytes.startswith(bom):
  1559. s = first_bytes[len(bom):].decode(enc, 'replace')
  1560. break
  1561. else:
  1562. s = first_bytes.decode('utf-8', 'replace')
  1563. return re.match(r'^\s*<', s)
  1564. def determine_protocol(info_dict):
  1565. protocol = info_dict.get('protocol')
  1566. if protocol is not None:
  1567. return protocol
  1568. url = info_dict['url']
  1569. if url.startswith('rtmp'):
  1570. return 'rtmp'
  1571. elif url.startswith('mms'):
  1572. return 'mms'
  1573. elif url.startswith('rtsp'):
  1574. return 'rtsp'
  1575. ext = determine_ext(url)
  1576. if ext == 'm3u8':
  1577. return 'm3u8'
  1578. elif ext == 'f4m':
  1579. return 'f4m'
  1580. return compat_urllib_parse_urlparse(url).scheme
  1581. def render_table(header_row, data):
  1582. """ Render a list of rows, each as a list of values """
  1583. table = [header_row] + data
  1584. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1585. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1586. return '\n'.join(format_str % tuple(row) for row in table)
  1587. def _match_one(filter_part, dct):
  1588. COMPARISON_OPERATORS = {
  1589. '<': operator.lt,
  1590. '<=': operator.le,
  1591. '>': operator.gt,
  1592. '>=': operator.ge,
  1593. '=': operator.eq,
  1594. '!=': operator.ne,
  1595. }
  1596. operator_rex = re.compile(r'''(?x)\s*
  1597. (?P<key>[a-z_]+)
  1598. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1599. (?:
  1600. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1601. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1602. )
  1603. \s*$
  1604. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1605. m = operator_rex.search(filter_part)
  1606. if m:
  1607. op = COMPARISON_OPERATORS[m.group('op')]
  1608. if m.group('strval') is not None:
  1609. if m.group('op') not in ('=', '!='):
  1610. raise ValueError(
  1611. 'Operator %s does not support string values!' % m.group('op'))
  1612. comparison_value = m.group('strval')
  1613. else:
  1614. try:
  1615. comparison_value = int(m.group('intval'))
  1616. except ValueError:
  1617. comparison_value = parse_filesize(m.group('intval'))
  1618. if comparison_value is None:
  1619. comparison_value = parse_filesize(m.group('intval') + 'B')
  1620. if comparison_value is None:
  1621. raise ValueError(
  1622. 'Invalid integer value %r in filter part %r' % (
  1623. m.group('intval'), filter_part))
  1624. actual_value = dct.get(m.group('key'))
  1625. if actual_value is None:
  1626. return m.group('none_inclusive')
  1627. return op(actual_value, comparison_value)
  1628. UNARY_OPERATORS = {
  1629. '': lambda v: v is not None,
  1630. '!': lambda v: v is None,
  1631. }
  1632. operator_rex = re.compile(r'''(?x)\s*
  1633. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1634. \s*$
  1635. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1636. m = operator_rex.search(filter_part)
  1637. if m:
  1638. op = UNARY_OPERATORS[m.group('op')]
  1639. actual_value = dct.get(m.group('key'))
  1640. return op(actual_value)
  1641. raise ValueError('Invalid filter part %r' % filter_part)
  1642. def match_str(filter_str, dct):
  1643. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1644. return all(
  1645. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1646. def match_filter_func(filter_str):
  1647. def _match_func(info_dict):
  1648. if match_str(filter_str, info_dict):
  1649. return None
  1650. else:
  1651. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1652. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1653. return _match_func
  1654. def parse_dfxp_time_expr(time_expr):
  1655. if not time_expr:
  1656. return
  1657. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  1658. if mobj:
  1659. return float(mobj.group('time_offset'))
  1660. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  1661. if mobj:
  1662. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  1663. def srt_subtitles_timecode(seconds):
  1664. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  1665. def dfxp2srt(dfxp_data):
  1666. _x = functools.partial(xpath_with_ns, ns_map={
  1667. 'ttml': 'http://www.w3.org/ns/ttml',
  1668. 'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
  1669. })
  1670. class TTMLPElementParser(object):
  1671. out = ''
  1672. def start(self, tag, attrib):
  1673. if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
  1674. self.out += '\n'
  1675. def end(self, tag):
  1676. pass
  1677. def data(self, data):
  1678. self.out += data
  1679. def close(self):
  1680. return self.out.strip()
  1681. def parse_node(node):
  1682. target = TTMLPElementParser()
  1683. parser = xml.etree.ElementTree.XMLParser(target=target)
  1684. parser.feed(xml.etree.ElementTree.tostring(node))
  1685. return parser.close()
  1686. dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
  1687. out = []
  1688. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall('.//p')
  1689. if not paras:
  1690. raise ValueError('Invalid dfxp/TTML subtitle')
  1691. for para, index in zip(paras, itertools.count(1)):
  1692. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  1693. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  1694. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  1695. if begin_time is None:
  1696. continue
  1697. if not end_time:
  1698. if not dur:
  1699. continue
  1700. end_time = begin_time + dur
  1701. out.append('%d\n%s --> %s\n%s\n\n' % (
  1702. index,
  1703. srt_subtitles_timecode(begin_time),
  1704. srt_subtitles_timecode(end_time),
  1705. parse_node(para)))
  1706. return ''.join(out)
  1707. def cli_option(params, command_option, param):
  1708. param = params.get(param)
  1709. return [command_option, param] if param is not None else []
  1710. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  1711. param = params.get(param)
  1712. assert isinstance(param, bool)
  1713. if separator:
  1714. return [command_option + separator + (true_value if param else false_value)]
  1715. return [command_option, true_value if param else false_value]
  1716. def cli_valueless_option(params, command_option, param, expected_value=True):
  1717. param = params.get(param)
  1718. return [command_option] if param == expected_value else []
  1719. def cli_configuration_args(params, param, default=[]):
  1720. ex_args = params.get(param)
  1721. if ex_args is None:
  1722. return default
  1723. assert isinstance(ex_args, list)
  1724. return ex_args
  1725. class ISO639Utils(object):
  1726. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  1727. _lang_map = {
  1728. 'aa': 'aar',
  1729. 'ab': 'abk',
  1730. 'ae': 'ave',
  1731. 'af': 'afr',
  1732. 'ak': 'aka',
  1733. 'am': 'amh',
  1734. 'an': 'arg',
  1735. 'ar': 'ara',
  1736. 'as': 'asm',
  1737. 'av': 'ava',
  1738. 'ay': 'aym',
  1739. 'az': 'aze',
  1740. 'ba': 'bak',
  1741. 'be': 'bel',
  1742. 'bg': 'bul',
  1743. 'bh': 'bih',
  1744. 'bi': 'bis',
  1745. 'bm': 'bam',
  1746. 'bn': 'ben',
  1747. 'bo': 'bod',
  1748. 'br': 'bre',
  1749. 'bs': 'bos',
  1750. 'ca': 'cat',
  1751. 'ce': 'che',
  1752. 'ch': 'cha',
  1753. 'co': 'cos',
  1754. 'cr': 'cre',
  1755. 'cs': 'ces',
  1756. 'cu': 'chu',
  1757. 'cv': 'chv',
  1758. 'cy': 'cym',
  1759. 'da': 'dan',
  1760. 'de': 'deu',
  1761. 'dv': 'div',
  1762. 'dz': 'dzo',
  1763. 'ee': 'ewe',
  1764. 'el': 'ell',
  1765. 'en': 'eng',
  1766. 'eo': 'epo',
  1767. 'es': 'spa',
  1768. 'et': 'est',
  1769. 'eu': 'eus',
  1770. 'fa': 'fas',
  1771. 'ff': 'ful',
  1772. 'fi': 'fin',
  1773. 'fj': 'fij',
  1774. 'fo': 'fao',
  1775. 'fr': 'fra',
  1776. 'fy': 'fry',
  1777. 'ga': 'gle',
  1778. 'gd': 'gla',
  1779. 'gl': 'glg',
  1780. 'gn': 'grn',
  1781. 'gu': 'guj',
  1782. 'gv': 'glv',
  1783. 'ha': 'hau',
  1784. 'he': 'heb',
  1785. 'hi': 'hin',
  1786. 'ho': 'hmo',
  1787. 'hr': 'hrv',
  1788. 'ht': 'hat',
  1789. 'hu': 'hun',
  1790. 'hy': 'hye',
  1791. 'hz': 'her',
  1792. 'ia': 'ina',
  1793. 'id': 'ind',
  1794. 'ie': 'ile',
  1795. 'ig': 'ibo',
  1796. 'ii': 'iii',
  1797. 'ik': 'ipk',
  1798. 'io': 'ido',
  1799. 'is': 'isl',
  1800. 'it': 'ita',
  1801. 'iu': 'iku',
  1802. 'ja': 'jpn',
  1803. 'jv': 'jav',
  1804. 'ka': 'kat',
  1805. 'kg': 'kon',
  1806. 'ki': 'kik',
  1807. 'kj': 'kua',
  1808. 'kk': 'kaz',
  1809. 'kl': 'kal',
  1810. 'km': 'khm',
  1811. 'kn': 'kan',
  1812. 'ko': 'kor',
  1813. 'kr': 'kau',
  1814. 'ks': 'kas',
  1815. 'ku': 'kur',
  1816. 'kv': 'kom',
  1817. 'kw': 'cor',
  1818. 'ky': 'kir',
  1819. 'la': 'lat',
  1820. 'lb': 'ltz',
  1821. 'lg': 'lug',
  1822. 'li': 'lim',
  1823. 'ln': 'lin',
  1824. 'lo': 'lao',
  1825. 'lt': 'lit',
  1826. 'lu': 'lub',
  1827. 'lv': 'lav',
  1828. 'mg': 'mlg',
  1829. 'mh': 'mah',
  1830. 'mi': 'mri',
  1831. 'mk': 'mkd',
  1832. 'ml': 'mal',
  1833. 'mn': 'mon',
  1834. 'mr': 'mar',
  1835. 'ms': 'msa',
  1836. 'mt': 'mlt',
  1837. 'my': 'mya',
  1838. 'na': 'nau',
  1839. 'nb': 'nob',
  1840. 'nd': 'nde',
  1841. 'ne': 'nep',
  1842. 'ng': 'ndo',
  1843. 'nl': 'nld',
  1844. 'nn': 'nno',
  1845. 'no': 'nor',
  1846. 'nr': 'nbl',
  1847. 'nv': 'nav',
  1848. 'ny': 'nya',
  1849. 'oc': 'oci',
  1850. 'oj': 'oji',
  1851. 'om': 'orm',
  1852. 'or': 'ori',
  1853. 'os': 'oss',
  1854. 'pa': 'pan',
  1855. 'pi': 'pli',
  1856. 'pl': 'pol',
  1857. 'ps': 'pus',
  1858. 'pt': 'por',
  1859. 'qu': 'que',
  1860. 'rm': 'roh',
  1861. 'rn': 'run',
  1862. 'ro': 'ron',
  1863. 'ru': 'rus',
  1864. 'rw': 'kin',
  1865. 'sa': 'san',
  1866. 'sc': 'srd',
  1867. 'sd': 'snd',
  1868. 'se': 'sme',
  1869. 'sg': 'sag',
  1870. 'si': 'sin',
  1871. 'sk': 'slk',
  1872. 'sl': 'slv',
  1873. 'sm': 'smo',
  1874. 'sn': 'sna',
  1875. 'so': 'som',
  1876. 'sq': 'sqi',
  1877. 'sr': 'srp',
  1878. 'ss': 'ssw',
  1879. 'st': 'sot',
  1880. 'su': 'sun',
  1881. 'sv': 'swe',
  1882. 'sw': 'swa',
  1883. 'ta': 'tam',
  1884. 'te': 'tel',
  1885. 'tg': 'tgk',
  1886. 'th': 'tha',
  1887. 'ti': 'tir',
  1888. 'tk': 'tuk',
  1889. 'tl': 'tgl',
  1890. 'tn': 'tsn',
  1891. 'to': 'ton',
  1892. 'tr': 'tur',
  1893. 'ts': 'tso',
  1894. 'tt': 'tat',
  1895. 'tw': 'twi',
  1896. 'ty': 'tah',
  1897. 'ug': 'uig',
  1898. 'uk': 'ukr',
  1899. 'ur': 'urd',
  1900. 'uz': 'uzb',
  1901. 've': 'ven',
  1902. 'vi': 'vie',
  1903. 'vo': 'vol',
  1904. 'wa': 'wln',
  1905. 'wo': 'wol',
  1906. 'xh': 'xho',
  1907. 'yi': 'yid',
  1908. 'yo': 'yor',
  1909. 'za': 'zha',
  1910. 'zh': 'zho',
  1911. 'zu': 'zul',
  1912. }
  1913. @classmethod
  1914. def short2long(cls, code):
  1915. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  1916. return cls._lang_map.get(code[:2])
  1917. @classmethod
  1918. def long2short(cls, code):
  1919. """Convert language code from ISO 639-2/T to ISO 639-1"""
  1920. for short_name, long_name in cls._lang_map.items():
  1921. if long_name == code:
  1922. return short_name
  1923. class ISO3166Utils(object):
  1924. # From http://data.okfn.org/data/core/country-list
  1925. _country_map = {
  1926. 'AF': 'Afghanistan',
  1927. 'AX': 'Åland Islands',
  1928. 'AL': 'Albania',
  1929. 'DZ': 'Algeria',
  1930. 'AS': 'American Samoa',
  1931. 'AD': 'Andorra',
  1932. 'AO': 'Angola',
  1933. 'AI': 'Anguilla',
  1934. 'AQ': 'Antarctica',
  1935. 'AG': 'Antigua and Barbuda',
  1936. 'AR': 'Argentina',
  1937. 'AM': 'Armenia',
  1938. 'AW': 'Aruba',
  1939. 'AU': 'Australia',
  1940. 'AT': 'Austria',
  1941. 'AZ': 'Azerbaijan',
  1942. 'BS': 'Bahamas',
  1943. 'BH': 'Bahrain',
  1944. 'BD': 'Bangladesh',
  1945. 'BB': 'Barbados',
  1946. 'BY': 'Belarus',
  1947. 'BE': 'Belgium',
  1948. 'BZ': 'Belize',
  1949. 'BJ': 'Benin',
  1950. 'BM': 'Bermuda',
  1951. 'BT': 'Bhutan',
  1952. 'BO': 'Bolivia, Plurinational State of',
  1953. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  1954. 'BA': 'Bosnia and Herzegovina',
  1955. 'BW': 'Botswana',
  1956. 'BV': 'Bouvet Island',
  1957. 'BR': 'Brazil',
  1958. 'IO': 'British Indian Ocean Territory',
  1959. 'BN': 'Brunei Darussalam',
  1960. 'BG': 'Bulgaria',
  1961. 'BF': 'Burkina Faso',
  1962. 'BI': 'Burundi',
  1963. 'KH': 'Cambodia',
  1964. 'CM': 'Cameroon',
  1965. 'CA': 'Canada',
  1966. 'CV': 'Cape Verde',
  1967. 'KY': 'Cayman Islands',
  1968. 'CF': 'Central African Republic',
  1969. 'TD': 'Chad',
  1970. 'CL': 'Chile',
  1971. 'CN': 'China',
  1972. 'CX': 'Christmas Island',
  1973. 'CC': 'Cocos (Keeling) Islands',
  1974. 'CO': 'Colombia',
  1975. 'KM': 'Comoros',
  1976. 'CG': 'Congo',
  1977. 'CD': 'Congo, the Democratic Republic of the',
  1978. 'CK': 'Cook Islands',
  1979. 'CR': 'Costa Rica',
  1980. 'CI': 'Côte d\'Ivoire',
  1981. 'HR': 'Croatia',
  1982. 'CU': 'Cuba',
  1983. 'CW': 'Curaçao',
  1984. 'CY': 'Cyprus',
  1985. 'CZ': 'Czech Republic',
  1986. 'DK': 'Denmark',
  1987. 'DJ': 'Djibouti',
  1988. 'DM': 'Dominica',
  1989. 'DO': 'Dominican Republic',
  1990. 'EC': 'Ecuador',
  1991. 'EG': 'Egypt',
  1992. 'SV': 'El Salvador',
  1993. 'GQ': 'Equatorial Guinea',
  1994. 'ER': 'Eritrea',
  1995. 'EE': 'Estonia',
  1996. 'ET': 'Ethiopia',
  1997. 'FK': 'Falkland Islands (Malvinas)',
  1998. 'FO': 'Faroe Islands',
  1999. 'FJ': 'Fiji',
  2000. 'FI': 'Finland',
  2001. 'FR': 'France',
  2002. 'GF': 'French Guiana',
  2003. 'PF': 'French Polynesia',
  2004. 'TF': 'French Southern Territories',
  2005. 'GA': 'Gabon',
  2006. 'GM': 'Gambia',
  2007. 'GE': 'Georgia',
  2008. 'DE': 'Germany',
  2009. 'GH': 'Ghana',
  2010. 'GI': 'Gibraltar',
  2011. 'GR': 'Greece',
  2012. 'GL': 'Greenland',
  2013. 'GD': 'Grenada',
  2014. 'GP': 'Guadeloupe',
  2015. 'GU': 'Guam',
  2016. 'GT': 'Guatemala',
  2017. 'GG': 'Guernsey',
  2018. 'GN': 'Guinea',
  2019. 'GW': 'Guinea-Bissau',
  2020. 'GY': 'Guyana',
  2021. 'HT': 'Haiti',
  2022. 'HM': 'Heard Island and McDonald Islands',
  2023. 'VA': 'Holy See (Vatican City State)',
  2024. 'HN': 'Honduras',
  2025. 'HK': 'Hong Kong',
  2026. 'HU': 'Hungary',
  2027. 'IS': 'Iceland',
  2028. 'IN': 'India',
  2029. 'ID': 'Indonesia',
  2030. 'IR': 'Iran, Islamic Republic of',
  2031. 'IQ': 'Iraq',
  2032. 'IE': 'Ireland',
  2033. 'IM': 'Isle of Man',
  2034. 'IL': 'Israel',
  2035. 'IT': 'Italy',
  2036. 'JM': 'Jamaica',
  2037. 'JP': 'Japan',
  2038. 'JE': 'Jersey',
  2039. 'JO': 'Jordan',
  2040. 'KZ': 'Kazakhstan',
  2041. 'KE': 'Kenya',
  2042. 'KI': 'Kiribati',
  2043. 'KP': 'Korea, Democratic People\'s Republic of',
  2044. 'KR': 'Korea, Republic of',
  2045. 'KW': 'Kuwait',
  2046. 'KG': 'Kyrgyzstan',
  2047. 'LA': 'Lao People\'s Democratic Republic',
  2048. 'LV': 'Latvia',
  2049. 'LB': 'Lebanon',
  2050. 'LS': 'Lesotho',
  2051. 'LR': 'Liberia',
  2052. 'LY': 'Libya',
  2053. 'LI': 'Liechtenstein',
  2054. 'LT': 'Lithuania',
  2055. 'LU': 'Luxembourg',
  2056. 'MO': 'Macao',
  2057. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2058. 'MG': 'Madagascar',
  2059. 'MW': 'Malawi',
  2060. 'MY': 'Malaysia',
  2061. 'MV': 'Maldives',
  2062. 'ML': 'Mali',
  2063. 'MT': 'Malta',
  2064. 'MH': 'Marshall Islands',
  2065. 'MQ': 'Martinique',
  2066. 'MR': 'Mauritania',
  2067. 'MU': 'Mauritius',
  2068. 'YT': 'Mayotte',
  2069. 'MX': 'Mexico',
  2070. 'FM': 'Micronesia, Federated States of',
  2071. 'MD': 'Moldova, Republic of',
  2072. 'MC': 'Monaco',
  2073. 'MN': 'Mongolia',
  2074. 'ME': 'Montenegro',
  2075. 'MS': 'Montserrat',
  2076. 'MA': 'Morocco',
  2077. 'MZ': 'Mozambique',
  2078. 'MM': 'Myanmar',
  2079. 'NA': 'Namibia',
  2080. 'NR': 'Nauru',
  2081. 'NP': 'Nepal',
  2082. 'NL': 'Netherlands',
  2083. 'NC': 'New Caledonia',
  2084. 'NZ': 'New Zealand',
  2085. 'NI': 'Nicaragua',
  2086. 'NE': 'Niger',
  2087. 'NG': 'Nigeria',
  2088. 'NU': 'Niue',
  2089. 'NF': 'Norfolk Island',
  2090. 'MP': 'Northern Mariana Islands',
  2091. 'NO': 'Norway',
  2092. 'OM': 'Oman',
  2093. 'PK': 'Pakistan',
  2094. 'PW': 'Palau',
  2095. 'PS': 'Palestine, State of',
  2096. 'PA': 'Panama',
  2097. 'PG': 'Papua New Guinea',
  2098. 'PY': 'Paraguay',
  2099. 'PE': 'Peru',
  2100. 'PH': 'Philippines',
  2101. 'PN': 'Pitcairn',
  2102. 'PL': 'Poland',
  2103. 'PT': 'Portugal',
  2104. 'PR': 'Puerto Rico',
  2105. 'QA': 'Qatar',
  2106. 'RE': 'Réunion',
  2107. 'RO': 'Romania',
  2108. 'RU': 'Russian Federation',
  2109. 'RW': 'Rwanda',
  2110. 'BL': 'Saint Barthélemy',
  2111. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2112. 'KN': 'Saint Kitts and Nevis',
  2113. 'LC': 'Saint Lucia',
  2114. 'MF': 'Saint Martin (French part)',
  2115. 'PM': 'Saint Pierre and Miquelon',
  2116. 'VC': 'Saint Vincent and the Grenadines',
  2117. 'WS': 'Samoa',
  2118. 'SM': 'San Marino',
  2119. 'ST': 'Sao Tome and Principe',
  2120. 'SA': 'Saudi Arabia',
  2121. 'SN': 'Senegal',
  2122. 'RS': 'Serbia',
  2123. 'SC': 'Seychelles',
  2124. 'SL': 'Sierra Leone',
  2125. 'SG': 'Singapore',
  2126. 'SX': 'Sint Maarten (Dutch part)',
  2127. 'SK': 'Slovakia',
  2128. 'SI': 'Slovenia',
  2129. 'SB': 'Solomon Islands',
  2130. 'SO': 'Somalia',
  2131. 'ZA': 'South Africa',
  2132. 'GS': 'South Georgia and the South Sandwich Islands',
  2133. 'SS': 'South Sudan',
  2134. 'ES': 'Spain',
  2135. 'LK': 'Sri Lanka',
  2136. 'SD': 'Sudan',
  2137. 'SR': 'Suriname',
  2138. 'SJ': 'Svalbard and Jan Mayen',
  2139. 'SZ': 'Swaziland',
  2140. 'SE': 'Sweden',
  2141. 'CH': 'Switzerland',
  2142. 'SY': 'Syrian Arab Republic',
  2143. 'TW': 'Taiwan, Province of China',
  2144. 'TJ': 'Tajikistan',
  2145. 'TZ': 'Tanzania, United Republic of',
  2146. 'TH': 'Thailand',
  2147. 'TL': 'Timor-Leste',
  2148. 'TG': 'Togo',
  2149. 'TK': 'Tokelau',
  2150. 'TO': 'Tonga',
  2151. 'TT': 'Trinidad and Tobago',
  2152. 'TN': 'Tunisia',
  2153. 'TR': 'Turkey',
  2154. 'TM': 'Turkmenistan',
  2155. 'TC': 'Turks and Caicos Islands',
  2156. 'TV': 'Tuvalu',
  2157. 'UG': 'Uganda',
  2158. 'UA': 'Ukraine',
  2159. 'AE': 'United Arab Emirates',
  2160. 'GB': 'United Kingdom',
  2161. 'US': 'United States',
  2162. 'UM': 'United States Minor Outlying Islands',
  2163. 'UY': 'Uruguay',
  2164. 'UZ': 'Uzbekistan',
  2165. 'VU': 'Vanuatu',
  2166. 'VE': 'Venezuela, Bolivarian Republic of',
  2167. 'VN': 'Viet Nam',
  2168. 'VG': 'Virgin Islands, British',
  2169. 'VI': 'Virgin Islands, U.S.',
  2170. 'WF': 'Wallis and Futuna',
  2171. 'EH': 'Western Sahara',
  2172. 'YE': 'Yemen',
  2173. 'ZM': 'Zambia',
  2174. 'ZW': 'Zimbabwe',
  2175. }
  2176. @classmethod
  2177. def short2full(cls, code):
  2178. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2179. return cls._country_map.get(code.upper())
  2180. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  2181. def __init__(self, proxies=None):
  2182. # Set default handlers
  2183. for type in ('http', 'https'):
  2184. setattr(self, '%s_open' % type,
  2185. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  2186. meth(r, proxy, type))
  2187. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  2188. def proxy_open(self, req, proxy, type):
  2189. req_proxy = req.headers.get('Ytdl-request-proxy')
  2190. if req_proxy is not None:
  2191. proxy = req_proxy
  2192. del req.headers['Ytdl-request-proxy']
  2193. if proxy == '__noproxy__':
  2194. return None # No Proxy
  2195. return compat_urllib_request.ProxyHandler.proxy_open(
  2196. self, req, proxy, type)
  2197. def ohdave_rsa_encrypt(data, exponent, modulus):
  2198. '''
  2199. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  2200. Input:
  2201. data: data to encrypt, bytes-like object
  2202. exponent, modulus: parameter e and N of RSA algorithm, both integer
  2203. Output: hex string of encrypted data
  2204. Limitation: supports one block encryption only
  2205. '''
  2206. payload = int(binascii.hexlify(data[::-1]), 16)
  2207. encrypted = pow(payload, exponent, modulus)
  2208. return '%x' % encrypted
  2209. def encode_base_n(num, n, table=None):
  2210. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2211. if not table:
  2212. table = FULL_TABLE[:n]
  2213. if n > len(table):
  2214. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  2215. if num == 0:
  2216. return table[0]
  2217. ret = ''
  2218. while num:
  2219. ret = table[num % n] + ret
  2220. num = num // n
  2221. return ret
  2222. def decode_packed_codes(code):
  2223. mobj = re.search(
  2224. r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
  2225. code)
  2226. obfucasted_code, base, count, symbols = mobj.groups()
  2227. base = int(base)
  2228. count = int(count)
  2229. symbols = symbols.split('|')
  2230. symbol_table = {}
  2231. while count:
  2232. count -= 1
  2233. base_n_count = encode_base_n(count, base)
  2234. symbol_table[base_n_count] = symbols[count] or base_n_count
  2235. return re.sub(
  2236. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  2237. obfucasted_code)