utils.py 84 KB

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