You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5612 lines
160 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
[utils] Remove Content-encoding from headers after decompression With cn_verification_proxy, our http_response() is called twice, one from PerRequestProxyHandler.proxy_open() and another from normal YoutubeDL.urlopen(). As a result, for proxies honoring Accept-Encoding, the following bug occurs: $ youtube-dl -vs --cn-verification-proxy https://secure.uku.im:993 "test:letv" [debug] System config: [] [debug] User config: [] [debug] Command-line args: ['-vs', '--cn-verification-proxy', 'https://secure.uku.im:993', 'test:letv'] [debug] Encodings: locale UTF-8, fs utf-8, out UTF-8, pref UTF-8 [debug] youtube-dl version 2015.12.23 [debug] Git HEAD: 97f18fa [debug] Python version 3.5.1 - Linux-4.3.3-1-ARCH-x86_64-with-arch-Arch-Linux [debug] exe versions: ffmpeg 2.8.4, ffprobe 2.8.4, rtmpdump 2.4 [debug] Proxy map: {} [TestURL] Test URL: http://www.letv.com/ptv/vplay/22005890.html [Letv] 22005890: Downloading webpage [Letv] 22005890: Downloading playJson data ERROR: Unable to download JSON metadata: Not a gzipped file (b'{"') (caused by OSError('Not a gzipped file (b\'{"\')',)); please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/extractor/common.py", line 330, in _request_webpage return self._downloader.urlopen(url_or_request) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/YoutubeDL.py", line 1886, in urlopen return self._opener.open(req, timeout=self._socket_timeout) File "/usr/lib/python3.5/urllib/request.py", line 471, in open response = meth(req, response) File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 773, in http_response raise original_ioerror File "/home/yen/Executables/Multimedia/youtube-dl/youtube_dl/utils.py", line 761, in http_response uncompressed = io.BytesIO(gz.read()) File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 409, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic)
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  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 email.header
  13. import errno
  14. import functools
  15. import gzip
  16. import io
  17. import itertools
  18. import json
  19. import locale
  20. import math
  21. import operator
  22. import os
  23. import platform
  24. import random
  25. import re
  26. import socket
  27. import ssl
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_HTMLParseError,
  36. compat_HTMLParser,
  37. compat_basestring,
  38. compat_chr,
  39. compat_cookiejar,
  40. compat_ctypes_WINFUNCTYPE,
  41. compat_etree_fromstring,
  42. compat_expanduser,
  43. compat_html_entities,
  44. compat_html_entities_html5,
  45. compat_http_client,
  46. compat_kwargs,
  47. compat_os_name,
  48. compat_parse_qs,
  49. compat_shlex_quote,
  50. compat_str,
  51. compat_struct_pack,
  52. compat_struct_unpack,
  53. compat_urllib_error,
  54. compat_urllib_parse,
  55. compat_urllib_parse_urlencode,
  56. compat_urllib_parse_urlparse,
  57. compat_urllib_parse_unquote_plus,
  58. compat_urllib_request,
  59. compat_urlparse,
  60. compat_xpath,
  61. )
  62. from .socks import (
  63. ProxyType,
  64. sockssocket,
  65. )
  66. def register_socks_protocols():
  67. # "Register" SOCKS protocols
  68. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  69. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  70. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  71. if scheme not in compat_urlparse.uses_netloc:
  72. compat_urlparse.uses_netloc.append(scheme)
  73. # This is not clearly defined otherwise
  74. compiled_regex_type = type(re.compile(''))
  75. def random_user_agent():
  76. _USER_AGENT_TPL = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
  77. _CHROME_VERSIONS = (
  78. '74.0.3729.129',
  79. '76.0.3780.3',
  80. '76.0.3780.2',
  81. '74.0.3729.128',
  82. '76.0.3780.1',
  83. '76.0.3780.0',
  84. '75.0.3770.15',
  85. '74.0.3729.127',
  86. '74.0.3729.126',
  87. '76.0.3779.1',
  88. '76.0.3779.0',
  89. '75.0.3770.14',
  90. '74.0.3729.125',
  91. '76.0.3778.1',
  92. '76.0.3778.0',
  93. '75.0.3770.13',
  94. '74.0.3729.124',
  95. '74.0.3729.123',
  96. '73.0.3683.121',
  97. '76.0.3777.1',
  98. '76.0.3777.0',
  99. '75.0.3770.12',
  100. '74.0.3729.122',
  101. '76.0.3776.4',
  102. '75.0.3770.11',
  103. '74.0.3729.121',
  104. '76.0.3776.3',
  105. '76.0.3776.2',
  106. '73.0.3683.120',
  107. '74.0.3729.120',
  108. '74.0.3729.119',
  109. '74.0.3729.118',
  110. '76.0.3776.1',
  111. '76.0.3776.0',
  112. '76.0.3775.5',
  113. '75.0.3770.10',
  114. '74.0.3729.117',
  115. '76.0.3775.4',
  116. '76.0.3775.3',
  117. '74.0.3729.116',
  118. '75.0.3770.9',
  119. '76.0.3775.2',
  120. '76.0.3775.1',
  121. '76.0.3775.0',
  122. '75.0.3770.8',
  123. '74.0.3729.115',
  124. '74.0.3729.114',
  125. '76.0.3774.1',
  126. '76.0.3774.0',
  127. '75.0.3770.7',
  128. '74.0.3729.113',
  129. '74.0.3729.112',
  130. '74.0.3729.111',
  131. '76.0.3773.1',
  132. '76.0.3773.0',
  133. '75.0.3770.6',
  134. '74.0.3729.110',
  135. '74.0.3729.109',
  136. '76.0.3772.1',
  137. '76.0.3772.0',
  138. '75.0.3770.5',
  139. '74.0.3729.108',
  140. '74.0.3729.107',
  141. '76.0.3771.1',
  142. '76.0.3771.0',
  143. '75.0.3770.4',
  144. '74.0.3729.106',
  145. '74.0.3729.105',
  146. '75.0.3770.3',
  147. '74.0.3729.104',
  148. '74.0.3729.103',
  149. '74.0.3729.102',
  150. '75.0.3770.2',
  151. '74.0.3729.101',
  152. '75.0.3770.1',
  153. '75.0.3770.0',
  154. '74.0.3729.100',
  155. '75.0.3769.5',
  156. '75.0.3769.4',
  157. '74.0.3729.99',
  158. '75.0.3769.3',
  159. '75.0.3769.2',
  160. '75.0.3768.6',
  161. '74.0.3729.98',
  162. '75.0.3769.1',
  163. '75.0.3769.0',
  164. '74.0.3729.97',
  165. '73.0.3683.119',
  166. '73.0.3683.118',
  167. '74.0.3729.96',
  168. '75.0.3768.5',
  169. '75.0.3768.4',
  170. '75.0.3768.3',
  171. '75.0.3768.2',
  172. '74.0.3729.95',
  173. '74.0.3729.94',
  174. '75.0.3768.1',
  175. '75.0.3768.0',
  176. '74.0.3729.93',
  177. '74.0.3729.92',
  178. '73.0.3683.117',
  179. '74.0.3729.91',
  180. '75.0.3766.3',
  181. '74.0.3729.90',
  182. '75.0.3767.2',
  183. '75.0.3767.1',
  184. '75.0.3767.0',
  185. '74.0.3729.89',
  186. '73.0.3683.116',
  187. '75.0.3766.2',
  188. '74.0.3729.88',
  189. '75.0.3766.1',
  190. '75.0.3766.0',
  191. '74.0.3729.87',
  192. '73.0.3683.115',
  193. '74.0.3729.86',
  194. '75.0.3765.1',
  195. '75.0.3765.0',
  196. '74.0.3729.85',
  197. '73.0.3683.114',
  198. '74.0.3729.84',
  199. '75.0.3764.1',
  200. '75.0.3764.0',
  201. '74.0.3729.83',
  202. '73.0.3683.113',
  203. '75.0.3763.2',
  204. '75.0.3761.4',
  205. '74.0.3729.82',
  206. '75.0.3763.1',
  207. '75.0.3763.0',
  208. '74.0.3729.81',
  209. '73.0.3683.112',
  210. '75.0.3762.1',
  211. '75.0.3762.0',
  212. '74.0.3729.80',
  213. '75.0.3761.3',
  214. '74.0.3729.79',
  215. '73.0.3683.111',
  216. '75.0.3761.2',
  217. '74.0.3729.78',
  218. '74.0.3729.77',
  219. '75.0.3761.1',
  220. '75.0.3761.0',
  221. '73.0.3683.110',
  222. '74.0.3729.76',
  223. '74.0.3729.75',
  224. '75.0.3760.0',
  225. '74.0.3729.74',
  226. '75.0.3759.8',
  227. '75.0.3759.7',
  228. '75.0.3759.6',
  229. '74.0.3729.73',
  230. '75.0.3759.5',
  231. '74.0.3729.72',
  232. '73.0.3683.109',
  233. '75.0.3759.4',
  234. '75.0.3759.3',
  235. '74.0.3729.71',
  236. '75.0.3759.2',
  237. '74.0.3729.70',
  238. '73.0.3683.108',
  239. '74.0.3729.69',
  240. '75.0.3759.1',
  241. '75.0.3759.0',
  242. '74.0.3729.68',
  243. '73.0.3683.107',
  244. '74.0.3729.67',
  245. '75.0.3758.1',
  246. '75.0.3758.0',
  247. '74.0.3729.66',
  248. '73.0.3683.106',
  249. '74.0.3729.65',
  250. '75.0.3757.1',
  251. '75.0.3757.0',
  252. '74.0.3729.64',
  253. '73.0.3683.105',
  254. '74.0.3729.63',
  255. '75.0.3756.1',
  256. '75.0.3756.0',
  257. '74.0.3729.62',
  258. '73.0.3683.104',
  259. '75.0.3755.3',
  260. '75.0.3755.2',
  261. '73.0.3683.103',
  262. '75.0.3755.1',
  263. '75.0.3755.0',
  264. '74.0.3729.61',
  265. '73.0.3683.102',
  266. '74.0.3729.60',
  267. '75.0.3754.2',
  268. '74.0.3729.59',
  269. '75.0.3753.4',
  270. '74.0.3729.58',
  271. '75.0.3754.1',
  272. '75.0.3754.0',
  273. '74.0.3729.57',
  274. '73.0.3683.101',
  275. '75.0.3753.3',
  276. '75.0.3752.2',
  277. '75.0.3753.2',
  278. '74.0.3729.56',
  279. '75.0.3753.1',
  280. '75.0.3753.0',
  281. '74.0.3729.55',
  282. '73.0.3683.100',
  283. '74.0.3729.54',
  284. '75.0.3752.1',
  285. '75.0.3752.0',
  286. '74.0.3729.53',
  287. '73.0.3683.99',
  288. '74.0.3729.52',
  289. '75.0.3751.1',
  290. '75.0.3751.0',
  291. '74.0.3729.51',
  292. '73.0.3683.98',
  293. '74.0.3729.50',
  294. '75.0.3750.0',
  295. '74.0.3729.49',
  296. '74.0.3729.48',
  297. '74.0.3729.47',
  298. '75.0.3749.3',
  299. '74.0.3729.46',
  300. '73.0.3683.97',
  301. '75.0.3749.2',
  302. '74.0.3729.45',
  303. '75.0.3749.1',
  304. '75.0.3749.0',
  305. '74.0.3729.44',
  306. '73.0.3683.96',
  307. '74.0.3729.43',
  308. '74.0.3729.42',
  309. '75.0.3748.1',
  310. '75.0.3748.0',
  311. '74.0.3729.41',
  312. '75.0.3747.1',
  313. '73.0.3683.95',
  314. '75.0.3746.4',
  315. '74.0.3729.40',
  316. '74.0.3729.39',
  317. '75.0.3747.0',
  318. '75.0.3746.3',
  319. '75.0.3746.2',
  320. '74.0.3729.38',
  321. '75.0.3746.1',
  322. '75.0.3746.0',
  323. '74.0.3729.37',
  324. '73.0.3683.94',
  325. '75.0.3745.5',
  326. '75.0.3745.4',
  327. '75.0.3745.3',
  328. '75.0.3745.2',
  329. '74.0.3729.36',
  330. '75.0.3745.1',
  331. '75.0.3745.0',
  332. '75.0.3744.2',
  333. '74.0.3729.35',
  334. '73.0.3683.93',
  335. '74.0.3729.34',
  336. '75.0.3744.1',
  337. '75.0.3744.0',
  338. '74.0.3729.33',
  339. '73.0.3683.92',
  340. '74.0.3729.32',
  341. '74.0.3729.31',
  342. '73.0.3683.91',
  343. '75.0.3741.2',
  344. '75.0.3740.5',
  345. '74.0.3729.30',
  346. '75.0.3741.1',
  347. '75.0.3741.0',
  348. '74.0.3729.29',
  349. '75.0.3740.4',
  350. '73.0.3683.90',
  351. '74.0.3729.28',
  352. '75.0.3740.3',
  353. '73.0.3683.89',
  354. '75.0.3740.2',
  355. '74.0.3729.27',
  356. '75.0.3740.1',
  357. '75.0.3740.0',
  358. '74.0.3729.26',
  359. '73.0.3683.88',
  360. '73.0.3683.87',
  361. '74.0.3729.25',
  362. '75.0.3739.1',
  363. '75.0.3739.0',
  364. '73.0.3683.86',
  365. '74.0.3729.24',
  366. '73.0.3683.85',
  367. '75.0.3738.4',
  368. '75.0.3738.3',
  369. '75.0.3738.2',
  370. '75.0.3738.1',
  371. '75.0.3738.0',
  372. '74.0.3729.23',
  373. '73.0.3683.84',
  374. '74.0.3729.22',
  375. '74.0.3729.21',
  376. '75.0.3737.1',
  377. '75.0.3737.0',
  378. '74.0.3729.20',
  379. '73.0.3683.83',
  380. '74.0.3729.19',
  381. '75.0.3736.1',
  382. '75.0.3736.0',
  383. '74.0.3729.18',
  384. '73.0.3683.82',
  385. '74.0.3729.17',
  386. '75.0.3735.1',
  387. '75.0.3735.0',
  388. '74.0.3729.16',
  389. '73.0.3683.81',
  390. '75.0.3734.1',
  391. '75.0.3734.0',
  392. '74.0.3729.15',
  393. '73.0.3683.80',
  394. '74.0.3729.14',
  395. '75.0.3733.1',
  396. '75.0.3733.0',
  397. '75.0.3732.1',
  398. '74.0.3729.13',
  399. '74.0.3729.12',
  400. '73.0.3683.79',
  401. '74.0.3729.11',
  402. '75.0.3732.0',
  403. '74.0.3729.10',
  404. '73.0.3683.78',
  405. '74.0.3729.9',
  406. '74.0.3729.8',
  407. '74.0.3729.7',
  408. '75.0.3731.3',
  409. '75.0.3731.2',
  410. '75.0.3731.0',
  411. '74.0.3729.6',
  412. '73.0.3683.77',
  413. '73.0.3683.76',
  414. '75.0.3730.5',
  415. '75.0.3730.4',
  416. '73.0.3683.75',
  417. '74.0.3729.5',
  418. '73.0.3683.74',
  419. '75.0.3730.3',
  420. '75.0.3730.2',
  421. '74.0.3729.4',
  422. '73.0.3683.73',
  423. '73.0.3683.72',
  424. '75.0.3730.1',
  425. '75.0.3730.0',
  426. '74.0.3729.3',
  427. '73.0.3683.71',
  428. '74.0.3729.2',
  429. '73.0.3683.70',
  430. '74.0.3729.1',
  431. '74.0.3729.0',
  432. '74.0.3726.4',
  433. '73.0.3683.69',
  434. '74.0.3726.3',
  435. '74.0.3728.0',
  436. '74.0.3726.2',
  437. '73.0.3683.68',
  438. '74.0.3726.1',
  439. '74.0.3726.0',
  440. '74.0.3725.4',
  441. '73.0.3683.67',
  442. '73.0.3683.66',
  443. '74.0.3725.3',
  444. '74.0.3725.2',
  445. '74.0.3725.1',
  446. '74.0.3724.8',
  447. '74.0.3725.0',
  448. '73.0.3683.65',
  449. '74.0.3724.7',
  450. '74.0.3724.6',
  451. '74.0.3724.5',
  452. '74.0.3724.4',
  453. '74.0.3724.3',
  454. '74.0.3724.2',
  455. '74.0.3724.1',
  456. '74.0.3724.0',
  457. '73.0.3683.64',
  458. '74.0.3723.1',
  459. '74.0.3723.0',
  460. '73.0.3683.63',
  461. '74.0.3722.1',
  462. '74.0.3722.0',
  463. '73.0.3683.62',
  464. '74.0.3718.9',
  465. '74.0.3702.3',
  466. '74.0.3721.3',
  467. '74.0.3721.2',
  468. '74.0.3721.1',
  469. '74.0.3721.0',
  470. '74.0.3720.6',
  471. '73.0.3683.61',
  472. '72.0.3626.122',
  473. '73.0.3683.60',
  474. '74.0.3720.5',
  475. '72.0.3626.121',
  476. '74.0.3718.8',
  477. '74.0.3720.4',
  478. '74.0.3720.3',
  479. '74.0.3718.7',
  480. '74.0.3720.2',
  481. '74.0.3720.1',
  482. '74.0.3720.0',
  483. '74.0.3718.6',
  484. '74.0.3719.5',
  485. '73.0.3683.59',
  486. '74.0.3718.5',
  487. '74.0.3718.4',
  488. '74.0.3719.4',
  489. '74.0.3719.3',
  490. '74.0.3719.2',
  491. '74.0.3719.1',
  492. '73.0.3683.58',
  493. '74.0.3719.0',
  494. '73.0.3683.57',
  495. '73.0.3683.56',
  496. '74.0.3718.3',
  497. '73.0.3683.55',
  498. '74.0.3718.2',
  499. '74.0.3718.1',
  500. '74.0.3718.0',
  501. '73.0.3683.54',
  502. '74.0.3717.2',
  503. '73.0.3683.53',
  504. '74.0.3717.1',
  505. '74.0.3717.0',
  506. '73.0.3683.52',
  507. '74.0.3716.1',
  508. '74.0.3716.0',
  509. '73.0.3683.51',
  510. '74.0.3715.1',
  511. '74.0.3715.0',
  512. '73.0.3683.50',
  513. '74.0.3711.2',
  514. '74.0.3714.2',
  515. '74.0.3713.3',
  516. '74.0.3714.1',
  517. '74.0.3714.0',
  518. '73.0.3683.49',
  519. '74.0.3713.1',
  520. '74.0.3713.0',
  521. '72.0.3626.120',
  522. '73.0.3683.48',
  523. '74.0.3712.2',
  524. '74.0.3712.1',
  525. '74.0.3712.0',
  526. '73.0.3683.47',
  527. '72.0.3626.119',
  528. '73.0.3683.46',
  529. '74.0.3710.2',
  530. '72.0.3626.118',
  531. '74.0.3711.1',
  532. '74.0.3711.0',
  533. '73.0.3683.45',
  534. '72.0.3626.117',
  535. '74.0.3710.1',
  536. '74.0.3710.0',
  537. '73.0.3683.44',
  538. '72.0.3626.116',
  539. '74.0.3709.1',
  540. '74.0.3709.0',
  541. '74.0.3704.9',
  542. '73.0.3683.43',
  543. '72.0.3626.115',
  544. '74.0.3704.8',
  545. '74.0.3704.7',
  546. '74.0.3708.0',
  547. '74.0.3706.7',
  548. '74.0.3704.6',
  549. '73.0.3683.42',
  550. '72.0.3626.114',
  551. '74.0.3706.6',
  552. '72.0.3626.113',
  553. '74.0.3704.5',
  554. '74.0.3706.5',
  555. '74.0.3706.4',
  556. '74.0.3706.3',
  557. '74.0.3706.2',
  558. '74.0.3706.1',
  559. '74.0.3706.0',
  560. '73.0.3683.41',
  561. '72.0.3626.112',
  562. '74.0.3705.1',
  563. '74.0.3705.0',
  564. '73.0.3683.40',
  565. '72.0.3626.111',
  566. '73.0.3683.39',
  567. '74.0.3704.4',
  568. '73.0.3683.38',
  569. '74.0.3704.3',
  570. '74.0.3704.2',
  571. '74.0.3704.1',
  572. '74.0.3704.0',
  573. '73.0.3683.37',
  574. '72.0.3626.110',
  575. '72.0.3626.109',
  576. '74.0.3703.3',
  577. '74.0.3703.2',
  578. '73.0.3683.36',
  579. '74.0.3703.1',
  580. '74.0.3703.0',
  581. '73.0.3683.35',
  582. '72.0.3626.108',
  583. '74.0.3702.2',
  584. '74.0.3699.3',
  585. '74.0.3702.1',
  586. '74.0.3702.0',
  587. '73.0.3683.34',
  588. '72.0.3626.107',
  589. '73.0.3683.33',
  590. '74.0.3701.1',
  591. '74.0.3701.0',
  592. '73.0.3683.32',
  593. '73.0.3683.31',
  594. '72.0.3626.105',
  595. '74.0.3700.1',
  596. '74.0.3700.0',
  597. '73.0.3683.29',
  598. '72.0.3626.103',
  599. '74.0.3699.2',
  600. '74.0.3699.1',
  601. '74.0.3699.0',
  602. '73.0.3683.28',
  603. '72.0.3626.102',
  604. '73.0.3683.27',
  605. '73.0.3683.26',
  606. '74.0.3698.0',
  607. '74.0.3696.2',
  608. '72.0.3626.101',
  609. '73.0.3683.25',
  610. '74.0.3696.1',
  611. '74.0.3696.0',
  612. '74.0.3694.8',
  613. '72.0.3626.100',
  614. '74.0.3694.7',
  615. '74.0.3694.6',
  616. '74.0.3694.5',
  617. '74.0.3694.4',
  618. '72.0.3626.99',
  619. '72.0.3626.98',
  620. '74.0.3694.3',
  621. '73.0.3683.24',
  622. '72.0.3626.97',
  623. '72.0.3626.96',
  624. '72.0.3626.95',
  625. '73.0.3683.23',
  626. '72.0.3626.94',
  627. '73.0.3683.22',
  628. '73.0.3683.21',
  629. '72.0.3626.93',
  630. '74.0.3694.2',
  631. '72.0.3626.92',
  632. '74.0.3694.1',
  633. '74.0.3694.0',
  634. '74.0.3693.6',
  635. '73.0.3683.20',
  636. '72.0.3626.91',
  637. '74.0.3693.5',
  638. '74.0.3693.4',
  639. '74.0.3693.3',
  640. '74.0.3693.2',
  641. '73.0.3683.19',
  642. '74.0.3693.1',
  643. '74.0.3693.0',
  644. '73.0.3683.18',
  645. '72.0.3626.90',
  646. '74.0.3692.1',
  647. '74.0.3692.0',
  648. '73.0.3683.17',
  649. '72.0.3626.89',
  650. '74.0.3687.3',
  651. '74.0.3691.1',
  652. '74.0.3691.0',
  653. '73.0.3683.16',
  654. '72.0.3626.88',
  655. '72.0.3626.87',
  656. '73.0.3683.15',
  657. '74.0.3690.1',
  658. '74.0.3690.0',
  659. '73.0.3683.14',
  660. '72.0.3626.86',
  661. '73.0.3683.13',
  662. '73.0.3683.12',
  663. '74.0.3689.1',
  664. '74.0.3689.0',
  665. '73.0.3683.11',
  666. '72.0.3626.85',
  667. '73.0.3683.10',
  668. '72.0.3626.84',
  669. '73.0.3683.9',
  670. '74.0.3688.1',
  671. '74.0.3688.0',
  672. '73.0.3683.8',
  673. '72.0.3626.83',
  674. '74.0.3687.2',
  675. '74.0.3687.1',
  676. '74.0.3687.0',
  677. '73.0.3683.7',
  678. '72.0.3626.82',
  679. '74.0.3686.4',
  680. '72.0.3626.81',
  681. '74.0.3686.3',
  682. '74.0.3686.2',
  683. '74.0.3686.1',
  684. '74.0.3686.0',
  685. '73.0.3683.6',
  686. '72.0.3626.80',
  687. '74.0.3685.1',
  688. '74.0.3685.0',
  689. '73.0.3683.5',
  690. '72.0.3626.79',
  691. '74.0.3684.1',
  692. '74.0.3684.0',
  693. '73.0.3683.4',
  694. '72.0.3626.78',
  695. '72.0.3626.77',
  696. '73.0.3683.3',
  697. '73.0.3683.2',
  698. '72.0.3626.76',
  699. '73.0.3683.1',
  700. '73.0.3683.0',
  701. '72.0.3626.75',
  702. '71.0.3578.141',
  703. '73.0.3682.1',
  704. '73.0.3682.0',
  705. '72.0.3626.74',
  706. '71.0.3578.140',
  707. '73.0.3681.4',
  708. '73.0.3681.3',
  709. '73.0.3681.2',
  710. '73.0.3681.1',
  711. '73.0.3681.0',
  712. '72.0.3626.73',
  713. '71.0.3578.139',
  714. '72.0.3626.72',
  715. '72.0.3626.71',
  716. '73.0.3680.1',
  717. '73.0.3680.0',
  718. '72.0.3626.70',
  719. '71.0.3578.138',
  720. '73.0.3678.2',
  721. '73.0.3679.1',
  722. '73.0.3679.0',
  723. '72.0.3626.69',
  724. '71.0.3578.137',
  725. '73.0.3678.1',
  726. '73.0.3678.0',
  727. '71.0.3578.136',
  728. '73.0.3677.1',
  729. '73.0.3677.0',
  730. '72.0.3626.68',
  731. '72.0.3626.67',
  732. '71.0.3578.135',
  733. '73.0.3676.1',
  734. '73.0.3676.0',
  735. '73.0.3674.2',
  736. '72.0.3626.66',
  737. '71.0.3578.134',
  738. '73.0.3674.1',
  739. '73.0.3674.0',
  740. '72.0.3626.65',
  741. '71.0.3578.133',
  742. '73.0.3673.2',
  743. '73.0.3673.1',
  744. '73.0.3673.0',
  745. '72.0.3626.64',
  746. '71.0.3578.132',
  747. '72.0.3626.63',
  748. '72.0.3626.62',
  749. '72.0.3626.61',
  750. '72.0.3626.60',
  751. '73.0.3672.1',
  752. '73.0.3672.0',
  753. '72.0.3626.59',
  754. '71.0.3578.131',
  755. '73.0.3671.3',
  756. '73.0.3671.2',
  757. '73.0.3671.1',
  758. '73.0.3671.0',
  759. '72.0.3626.58',
  760. '71.0.3578.130',
  761. '73.0.3670.1',
  762. '73.0.3670.0',
  763. '72.0.3626.57',
  764. '71.0.3578.129',
  765. '73.0.3669.1',
  766. '73.0.3669.0',
  767. '72.0.3626.56',
  768. '71.0.3578.128',
  769. '73.0.3668.2',
  770. '73.0.3668.1',
  771. '73.0.3668.0',
  772. '72.0.3626.55',
  773. '71.0.3578.127',
  774. '73.0.3667.2',
  775. '73.0.3667.1',
  776. '73.0.3667.0',
  777. '72.0.3626.54',
  778. '71.0.3578.126',
  779. '73.0.3666.1',
  780. '73.0.3666.0',
  781. '72.0.3626.53',
  782. '71.0.3578.125',
  783. '73.0.3665.4',
  784. '73.0.3665.3',
  785. '72.0.3626.52',
  786. '73.0.3665.2',
  787. '73.0.3664.4',
  788. '73.0.3665.1',
  789. '73.0.3665.0',
  790. '72.0.3626.51',
  791. '71.0.3578.124',
  792. '72.0.3626.50',
  793. '73.0.3664.3',
  794. '73.0.3664.2',
  795. '73.0.3664.1',
  796. '73.0.3664.0',
  797. '73.0.3663.2',
  798. '72.0.3626.49',
  799. '71.0.3578.123',
  800. '73.0.3663.1',
  801. '73.0.3663.0',
  802. '72.0.3626.48',
  803. '71.0.3578.122',
  804. '73.0.3662.1',
  805. '73.0.3662.0',
  806. '72.0.3626.47',
  807. '71.0.3578.121',
  808. '73.0.3661.1',
  809. '72.0.3626.46',
  810. '73.0.3661.0',
  811. '72.0.3626.45',
  812. '71.0.3578.120',
  813. '73.0.3660.2',
  814. '73.0.3660.1',
  815. '73.0.3660.0',
  816. '72.0.3626.44',
  817. '71.0.3578.119',
  818. '73.0.3659.1',
  819. '73.0.3659.0',
  820. '72.0.3626.43',
  821. '71.0.3578.118',
  822. '73.0.3658.1',
  823. '73.0.3658.0',
  824. '72.0.3626.42',
  825. '71.0.3578.117',
  826. '73.0.3657.1',
  827. '73.0.3657.0',
  828. '72.0.3626.41',
  829. '71.0.3578.116',
  830. '73.0.3656.1',
  831. '73.0.3656.0',
  832. '72.0.3626.40',
  833. '71.0.3578.115',
  834. '73.0.3655.1',
  835. '73.0.3655.0',
  836. '72.0.3626.39',
  837. '71.0.3578.114',
  838. '73.0.3654.1',
  839. '73.0.3654.0',
  840. '72.0.3626.38',
  841. '71.0.3578.113',
  842. '73.0.3653.1',
  843. '73.0.3653.0',
  844. '72.0.3626.37',
  845. '71.0.3578.112',
  846. '73.0.3652.1',
  847. '73.0.3652.0',
  848. '72.0.3626.36',
  849. '71.0.3578.111',
  850. '73.0.3651.1',
  851. '73.0.3651.0',
  852. '72.0.3626.35',
  853. '71.0.3578.110',
  854. '73.0.3650.1',
  855. '73.0.3650.0',
  856. '72.0.3626.34',
  857. '71.0.3578.109',
  858. '73.0.3649.1',
  859. '73.0.3649.0',
  860. '72.0.3626.33',
  861. '71.0.3578.108',
  862. '73.0.3648.2',
  863. '73.0.3648.1',
  864. '73.0.3648.0',
  865. '72.0.3626.32',
  866. '71.0.3578.107',
  867. '73.0.3647.2',
  868. '73.0.3647.1',
  869. '73.0.3647.0',
  870. '72.0.3626.31',
  871. '71.0.3578.106',
  872. '73.0.3635.3',
  873. '73.0.3646.2',
  874. '73.0.3646.1',
  875. '73.0.3646.0',
  876. '72.0.3626.30',
  877. '71.0.3578.105',
  878. '72.0.3626.29',
  879. '73.0.3645.2',
  880. '73.0.3645.1',
  881. '73.0.3645.0',
  882. '72.0.3626.28',
  883. '71.0.3578.104',
  884. '72.0.3626.27',
  885. '72.0.3626.26',
  886. '72.0.3626.25',
  887. '72.0.3626.24',
  888. '73.0.3644.0',
  889. '73.0.3643.2',
  890. '72.0.3626.23',
  891. '71.0.3578.103',
  892. '73.0.3643.1',
  893. '73.0.3643.0',
  894. '72.0.3626.22',
  895. '71.0.3578.102',
  896. '73.0.3642.1',
  897. '73.0.3642.0',
  898. '72.0.3626.21',
  899. '71.0.3578.101',
  900. '73.0.3641.1',
  901. '73.0.3641.0',
  902. '72.0.3626.20',
  903. '71.0.3578.100',
  904. '72.0.3626.19',
  905. '73.0.3640.1',
  906. '73.0.3640.0',
  907. '72.0.3626.18',
  908. '73.0.3639.1',
  909. '71.0.3578.99',
  910. '73.0.3639.0',
  911. '72.0.3626.17',
  912. '73.0.3638.2',
  913. '72.0.3626.16',
  914. '73.0.3638.1',
  915. '73.0.3638.0',
  916. '72.0.3626.15',
  917. '71.0.3578.98',
  918. '73.0.3635.2',
  919. '71.0.3578.97',
  920. '73.0.3637.1',
  921. '73.0.3637.0',
  922. '72.0.3626.14',
  923. '71.0.3578.96',
  924. '71.0.3578.95',
  925. '72.0.3626.13',
  926. '71.0.3578.94',
  927. '73.0.3636.2',
  928. '71.0.3578.93',
  929. '73.0.3636.1',
  930. '73.0.3636.0',
  931. '72.0.3626.12',
  932. '71.0.3578.92',
  933. '73.0.3635.1',
  934. '73.0.3635.0',
  935. '72.0.3626.11',
  936. '71.0.3578.91',
  937. '73.0.3634.2',
  938. '73.0.3634.1',
  939. '73.0.3634.0',
  940. '72.0.3626.10',
  941. '71.0.3578.90',
  942. '71.0.3578.89',
  943. '73.0.3633.2',
  944. '73.0.3633.1',
  945. '73.0.3633.0',
  946. '72.0.3610.4',
  947. '72.0.3626.9',
  948. '71.0.3578.88',
  949. '73.0.3632.5',
  950. '73.0.3632.4',
  951. '73.0.3632.3',
  952. '73.0.3632.2',
  953. '73.0.3632.1',
  954. '73.0.3632.0',
  955. '72.0.3626.8',
  956. '71.0.3578.87',
  957. '73.0.3631.2',
  958. '73.0.3631.1',
  959. '73.0.3631.0',
  960. '72.0.3626.7',
  961. '71.0.3578.86',
  962. '72.0.3626.6',
  963. '73.0.3630.1',
  964. '73.0.3630.0',
  965. '72.0.3626.5',
  966. '71.0.3578.85',
  967. '72.0.3626.4',
  968. '73.0.3628.3',
  969. '73.0.3628.2',
  970. '73.0.3629.1',
  971. '73.0.3629.0',
  972. '72.0.3626.3',
  973. '71.0.3578.84',
  974. '73.0.3628.1',
  975. '73.0.3628.0',
  976. '71.0.3578.83',
  977. '73.0.3627.1',
  978. '73.0.3627.0',
  979. '72.0.3626.2',
  980. '71.0.3578.82',
  981. '71.0.3578.81',
  982. '71.0.3578.80',
  983. '72.0.3626.1',
  984. '72.0.3626.0',
  985. '71.0.3578.79',
  986. '70.0.3538.124',
  987. '71.0.3578.78',
  988. '72.0.3623.4',
  989. '72.0.3625.2',
  990. '72.0.3625.1',
  991. '72.0.3625.0',
  992. '71.0.3578.77',
  993. '70.0.3538.123',
  994. '72.0.3624.4',
  995. '72.0.3624.3',
  996. '72.0.3624.2',
  997. '71.0.3578.76',
  998. '72.0.3624.1',
  999. '72.0.3624.0',
  1000. '72.0.3623.3',
  1001. '71.0.3578.75',
  1002. '70.0.3538.122',
  1003. '71.0.3578.74',
  1004. '72.0.3623.2',
  1005. '72.0.3610.3',
  1006. '72.0.3623.1',
  1007. '72.0.3623.0',
  1008. '72.0.3622.3',
  1009. '72.0.3622.2',
  1010. '71.0.3578.73',
  1011. '70.0.3538.121',
  1012. '72.0.3622.1',
  1013. '72.0.3622.0',
  1014. '71.0.3578.72',
  1015. '70.0.3538.120',
  1016. '72.0.3621.1',
  1017. '72.0.3621.0',
  1018. '71.0.3578.71',
  1019. '70.0.3538.119',
  1020. '72.0.3620.1',
  1021. '72.0.3620.0',
  1022. '71.0.3578.70',
  1023. '70.0.3538.118',
  1024. '71.0.3578.69',
  1025. '72.0.3619.1',
  1026. '72.0.3619.0',
  1027. '71.0.3578.68',
  1028. '70.0.3538.117',
  1029. '71.0.3578.67',
  1030. '72.0.3618.1',
  1031. '72.0.3618.0',
  1032. '71.0.3578.66',
  1033. '70.0.3538.116',
  1034. '72.0.3617.1',
  1035. '72.0.3617.0',
  1036. '71.0.3578.65',
  1037. '70.0.3538.115',
  1038. '72.0.3602.3',
  1039. '71.0.3578.64',
  1040. '72.0.3616.1',
  1041. '72.0.3616.0',
  1042. '71.0.3578.63',
  1043. '70.0.3538.114',
  1044. '71.0.3578.62',
  1045. '72.0.3615.1',
  1046. '72.0.3615.0',
  1047. '71.0.3578.61',
  1048. '70.0.3538.113',
  1049. '72.0.3614.1',
  1050. '72.0.3614.0',
  1051. '71.0.3578.60',
  1052. '70.0.3538.112',
  1053. '72.0.3613.1',
  1054. '72.0.3613.0',
  1055. '71.0.3578.59',
  1056. '70.0.3538.111',
  1057. '72.0.3612.2',
  1058. '72.0.3612.1',
  1059. '72.0.3612.0',
  1060. '70.0.3538.110',
  1061. '71.0.3578.58',
  1062. '70.0.3538.109',
  1063. '72.0.3611.2',
  1064. '72.0.3611.1',
  1065. '72.0.3611.0',
  1066. '71.0.3578.57',
  1067. '70.0.3538.108',
  1068. '72.0.3610.2',
  1069. '71.0.3578.56',
  1070. '71.0.3578.55',
  1071. '72.0.3610.1',
  1072. '72.0.3610.0',
  1073. '71.0.3578.54',
  1074. '70.0.3538.107',
  1075. '71.0.3578.53',
  1076. '72.0.3609.3',
  1077. '71.0.3578.52',
  1078. '72.0.3609.2',
  1079. '71.0.3578.51',
  1080. '72.0.3608.5',
  1081. '72.0.3609.1',
  1082. '72.0.3609.0',
  1083. '71.0.3578.50',
  1084. '70.0.3538.106',
  1085. '72.0.3608.4',
  1086. '72.0.3608.3',
  1087. '72.0.3608.2',
  1088. '71.0.3578.49',
  1089. '72.0.3608.1',
  1090. '72.0.3608.0',
  1091. '70.0.3538.105',
  1092. '71.0.3578.48',
  1093. '72.0.3607.1',
  1094. '72.0.3607.0',
  1095. '71.0.3578.47',
  1096. '70.0.3538.104',
  1097. '72.0.3606.2',
  1098. '72.0.3606.1',
  1099. '72.0.3606.0',
  1100. '71.0.3578.46',
  1101. '70.0.3538.103',
  1102. '70.0.3538.102',
  1103. '72.0.3605.3',
  1104. '72.0.3605.2',
  1105. '72.0.3605.1',
  1106. '72.0.3605.0',
  1107. '71.0.3578.45',
  1108. '70.0.3538.101',
  1109. '71.0.3578.44',
  1110. '71.0.3578.43',
  1111. '70.0.3538.100',
  1112. '70.0.3538.99',
  1113. '71.0.3578.42',
  1114. '72.0.3604.1',
  1115. '72.0.3604.0',
  1116. '71.0.3578.41',
  1117. '70.0.3538.98',
  1118. '71.0.3578.40',
  1119. '72.0.3603.2',
  1120. '72.0.3603.1',
  1121. '72.0.3603.0',
  1122. '71.0.3578.39',
  1123. '70.0.3538.97',
  1124. '72.0.3602.2',
  1125. '71.0.3578.38',
  1126. '71.0.3578.37',
  1127. '72.0.3602.1',
  1128. '72.0.3602.0',
  1129. '71.0.3578.36',
  1130. '70.0.3538.96',
  1131. '72.0.3601.1',
  1132. '72.0.3601.0',
  1133. '71.0.3578.35',
  1134. '70.0.3538.95',
  1135. '72.0.3600.1',
  1136. '72.0.3600.0',
  1137. '71.0.3578.34',
  1138. '70.0.3538.94',
  1139. '72.0.3599.3',
  1140. '72.0.3599.2',
  1141. '72.0.3599.1',
  1142. '72.0.3599.0',
  1143. '71.0.3578.33',
  1144. '70.0.3538.93',
  1145. '72.0.3598.1',
  1146. '72.0.3598.0',
  1147. '71.0.3578.32',
  1148. '70.0.3538.87',
  1149. '72.0.3597.1',
  1150. '72.0.3597.0',
  1151. '72.0.3596.2',
  1152. '71.0.3578.31',
  1153. '70.0.3538.86',
  1154. '71.0.3578.30',
  1155. '71.0.3578.29',
  1156. '72.0.3596.1',
  1157. '72.0.3596.0',
  1158. '71.0.3578.28',
  1159. '70.0.3538.85',
  1160. '72.0.3595.2',
  1161. '72.0.3591.3',
  1162. '72.0.3595.1',
  1163. '72.0.3595.0',
  1164. '71.0.3578.27',
  1165. '70.0.3538.84',
  1166. '72.0.3594.1',
  1167. '72.0.3594.0',
  1168. '71.0.3578.26',
  1169. '70.0.3538.83',
  1170. '72.0.3593.2',
  1171. '72.0.3593.1',
  1172. '72.0.3593.0',
  1173. '71.0.3578.25',
  1174. '70.0.3538.82',
  1175. '72.0.3589.3',
  1176. '72.0.3592.2',
  1177. '72.0.3592.1',
  1178. '72.0.3592.0',
  1179. '71.0.3578.24',
  1180. '72.0.3589.2',
  1181. '70.0.3538.81',
  1182. '70.0.3538.80',
  1183. '72.0.3591.2',
  1184. '72.0.3591.1',
  1185. '72.0.3591.0',
  1186. '71.0.3578.23',
  1187. '70.0.3538.79',
  1188. '71.0.3578.22',
  1189. '72.0.3590.1',
  1190. '72.0.3590.0',
  1191. '71.0.3578.21',
  1192. '70.0.3538.78',
  1193. '70.0.3538.77',
  1194. '72.0.3589.1',
  1195. '72.0.3589.0',
  1196. '71.0.3578.20',
  1197. '70.0.3538.76',
  1198. '71.0.3578.19',
  1199. '70.0.3538.75',
  1200. '72.0.3588.1',
  1201. '72.0.3588.0',
  1202. '71.0.3578.18',
  1203. '70.0.3538.74',
  1204. '72.0.3586.2',
  1205. '72.0.3587.0',
  1206. '71.0.3578.17',
  1207. '70.0.3538.73',
  1208. '72.0.3586.1',
  1209. '72.0.3586.0',
  1210. '71.0.3578.16',
  1211. '70.0.3538.72',
  1212. '72.0.3585.1',
  1213. '72.0.3585.0',
  1214. '71.0.3578.15',
  1215. '70.0.3538.71',
  1216. '71.0.3578.14',
  1217. '72.0.3584.1',
  1218. '72.0.3584.0',
  1219. '71.0.3578.13',
  1220. '70.0.3538.70',
  1221. '72.0.3583.2',
  1222. '71.0.3578.12',
  1223. '72.0.3583.1',
  1224. '72.0.3583.0',
  1225. '71.0.3578.11',
  1226. '70.0.3538.69',
  1227. '71.0.3578.10',
  1228. '72.0.3582.0',
  1229. '72.0.3581.4',
  1230. '71.0.3578.9',
  1231. '70.0.3538.67',
  1232. '72.0.3581.3',
  1233. '72.0.3581.2',
  1234. '72.0.3581.1',
  1235. '72.0.3581.0',
  1236. '71.0.3578.8',
  1237. '70.0.3538.66',
  1238. '72.0.3580.1',
  1239. '72.0.3580.0',
  1240. '71.0.3578.7',
  1241. '70.0.3538.65',
  1242. '71.0.3578.6',
  1243. '72.0.3579.1',
  1244. '72.0.3579.0',
  1245. '71.0.3578.5',
  1246. '70.0.3538.64',
  1247. '71.0.3578.4',
  1248. '71.0.3578.3',
  1249. '71.0.3578.2',
  1250. '71.0.3578.1',
  1251. '71.0.3578.0',
  1252. '70.0.3538.63',
  1253. '69.0.3497.128',
  1254. '70.0.3538.62',
  1255. '70.0.3538.61',
  1256. '70.0.3538.60',
  1257. '70.0.3538.59',
  1258. '71.0.3577.1',
  1259. '71.0.3577.0',
  1260. '70.0.3538.58',
  1261. '69.0.3497.127',
  1262. '71.0.3576.2',
  1263. '71.0.3576.1',
  1264. '71.0.3576.0',
  1265. '70.0.3538.57',
  1266. '70.0.3538.56',
  1267. '71.0.3575.2',
  1268. '70.0.3538.55',
  1269. '69.0.3497.126',
  1270. '70.0.3538.54',
  1271. '71.0.3575.1',
  1272. '71.0.3575.0',
  1273. '71.0.3574.1',
  1274. '71.0.3574.0',
  1275. '70.0.3538.53',
  1276. '69.0.3497.125',
  1277. '70.0.3538.52',
  1278. '71.0.3573.1',
  1279. '71.0.3573.0',
  1280. '70.0.3538.51',
  1281. '69.0.3497.124',
  1282. '71.0.3572.1',
  1283. '71.0.3572.0',
  1284. '70.0.3538.50',
  1285. '69.0.3497.123',
  1286. '71.0.3571.2',
  1287. '70.0.3538.49',
  1288. '69.0.3497.122',
  1289. '71.0.3571.1',
  1290. '71.0.3571.0',
  1291. '70.0.3538.48',
  1292. '69.0.3497.121',
  1293. '71.0.3570.1',
  1294. '71.0.3570.0',
  1295. '70.0.3538.47',
  1296. '69.0.3497.120',
  1297. '71.0.3568.2',
  1298. '71.0.3569.1',
  1299. '71.0.3569.0',
  1300. '70.0.3538.46',
  1301. '69.0.3497.119',
  1302. '70.0.3538.45',
  1303. '71.0.3568.1',
  1304. '71.0.3568.0',
  1305. '70.0.3538.44',
  1306. '69.0.3497.118',
  1307. '70.0.3538.43',
  1308. '70.0.3538.42',
  1309. '71.0.3567.1',
  1310. '71.0.3567.0',
  1311. '70.0.3538.41',
  1312. '69.0.3497.117',
  1313. '71.0.3566.1',
  1314. '71.0.3566.0',
  1315. '70.0.3538.40',
  1316. '69.0.3497.116',
  1317. '71.0.3565.1',
  1318. '71.0.3565.0',
  1319. '70.0.3538.39',
  1320. '69.0.3497.115',
  1321. '71.0.3564.1',
  1322. '71.0.3564.0',
  1323. '70.0.3538.38',
  1324. '69.0.3497.114',
  1325. '71.0.3563.0',
  1326. '71.0.3562.2',
  1327. '70.0.3538.37',
  1328. '69.0.3497.113',
  1329. '70.0.3538.36',
  1330. '70.0.3538.35',
  1331. '71.0.3562.1',
  1332. '71.0.3562.0',
  1333. '70.0.3538.34',
  1334. '69.0.3497.112',
  1335. '70.0.3538.33',
  1336. '71.0.3561.1',
  1337. '71.0.3561.0',
  1338. '70.0.3538.32',
  1339. '69.0.3497.111',
  1340. '71.0.3559.6',
  1341. '71.0.3560.1',
  1342. '71.0.3560.0',
  1343. '71.0.3559.5',
  1344. '71.0.3559.4',
  1345. '70.0.3538.31',
  1346. '69.0.3497.110',
  1347. '71.0.3559.3',
  1348. '70.0.3538.30',
  1349. '69.0.3497.109',
  1350. '71.0.3559.2',
  1351. '71.0.3559.1',
  1352. '71.0.3559.0',
  1353. '70.0.3538.29',
  1354. '69.0.3497.108',
  1355. '71.0.3558.2',
  1356. '71.0.3558.1',
  1357. '71.0.3558.0',
  1358. '70.0.3538.28',
  1359. '69.0.3497.107',
  1360. '71.0.3557.2',
  1361. '71.0.3557.1',
  1362. '71.0.3557.0',
  1363. '70.0.3538.27',
  1364. '69.0.3497.106',
  1365. '71.0.3554.4',
  1366. '70.0.3538.26',
  1367. '71.0.3556.1',
  1368. '71.0.3556.0',
  1369. '70.0.3538.25',
  1370. '71.0.3554.3',
  1371. '69.0.3497.105',
  1372. '71.0.3554.2',
  1373. '70.0.3538.24',
  1374. '69.0.3497.104',
  1375. '71.0.3555.2',
  1376. '70.0.3538.23',
  1377. '71.0.3555.1',
  1378. '71.0.3555.0',
  1379. '70.0.3538.22',
  1380. '69.0.3497.103',
  1381. '71.0.3554.1',
  1382. '71.0.3554.0',
  1383. '70.0.3538.21',
  1384. '69.0.3497.102',
  1385. '71.0.3553.3',
  1386. '70.0.3538.20',
  1387. '69.0.3497.101',
  1388. '71.0.3553.2',
  1389. '69.0.3497.100',
  1390. '71.0.3553.1',
  1391. '71.0.3553.0',
  1392. '70.0.3538.19',
  1393. '69.0.3497.99',
  1394. '69.0.3497.98',
  1395. '69.0.3497.97',
  1396. '71.0.3552.6',
  1397. '71.0.3552.5',
  1398. '71.0.3552.4',
  1399. '71.0.3552.3',
  1400. '71.0.3552.2',
  1401. '71.0.3552.1',
  1402. '71.0.3552.0',
  1403. '70.0.3538.18',
  1404. '69.0.3497.96',
  1405. '71.0.3551.3',
  1406. '71.0.3551.2',
  1407. '71.0.3551.1',
  1408. '71.0.3551.0',
  1409. '70.0.3538.17',
  1410. '69.0.3497.95',
  1411. '71.0.3550.3',
  1412. '71.0.3550.2',
  1413. '71.0.3550.1',
  1414. '71.0.3550.0',
  1415. '70.0.3538.16',
  1416. '69.0.3497.94',
  1417. '71.0.3549.1',
  1418. '71.0.3549.0',
  1419. '70.0.3538.15',
  1420. '69.0.3497.93',
  1421. '69.0.3497.92',
  1422. '71.0.3548.1',
  1423. '71.0.3548.0',
  1424. '70.0.3538.14',
  1425. '69.0.3497.91',
  1426. '71.0.3547.1',
  1427. '71.0.3547.0',
  1428. '70.0.3538.13',
  1429. '69.0.3497.90',
  1430. '71.0.3546.2',
  1431. '69.0.3497.89',
  1432. '71.0.3546.1',
  1433. '71.0.3546.0',
  1434. '70.0.3538.12',
  1435. '69.0.3497.88',
  1436. '71.0.3545.4',
  1437. '71.0.3545.3',
  1438. '71.0.3545.2',
  1439. '71.0.3545.1',
  1440. '71.0.3545.0',
  1441. '70.0.3538.11',
  1442. '69.0.3497.87',
  1443. '71.0.3544.5',
  1444. '71.0.3544.4',
  1445. '71.0.3544.3',
  1446. '71.0.3544.2',
  1447. '71.0.3544.1',
  1448. '71.0.3544.0',
  1449. '69.0.3497.86',
  1450. '70.0.3538.10',
  1451. '69.0.3497.85',
  1452. '70.0.3538.9',
  1453. '69.0.3497.84',
  1454. '71.0.3543.4',
  1455. '70.0.3538.8',
  1456. '71.0.3543.3',
  1457. '71.0.3543.2',
  1458. '71.0.3543.1',
  1459. '71.0.3543.0',
  1460. '70.0.3538.7',
  1461. '69.0.3497.83',
  1462. '71.0.3542.2',
  1463. '71.0.3542.1',
  1464. '71.0.3542.0',
  1465. '70.0.3538.6',
  1466. '69.0.3497.82',
  1467. '69.0.3497.81',
  1468. '71.0.3541.1',
  1469. '71.0.3541.0',
  1470. '70.0.3538.5',
  1471. '69.0.3497.80',
  1472. '71.0.3540.1',
  1473. '71.0.3540.0',
  1474. '70.0.3538.4',
  1475. '69.0.3497.79',
  1476. '70.0.3538.3',
  1477. '71.0.3539.1',
  1478. '71.0.3539.0',
  1479. '69.0.3497.78',
  1480. '68.0.3440.134',
  1481. '69.0.3497.77',
  1482. '70.0.3538.2',
  1483. '70.0.3538.1',
  1484. '70.0.3538.0',
  1485. '69.0.3497.76',
  1486. '68.0.3440.133',
  1487. '69.0.3497.75',
  1488. '70.0.3537.2',
  1489. '70.0.3537.1',
  1490. '70.0.3537.0',
  1491. '69.0.3497.74',
  1492. '68.0.3440.132',
  1493. '70.0.3536.0',
  1494. '70.0.3535.5',
  1495. '70.0.3535.4',
  1496. '70.0.3535.3',
  1497. '69.0.3497.73',
  1498. '68.0.3440.131',
  1499. '70.0.3532.8',
  1500. '70.0.3532.7',
  1501. '69.0.3497.72',
  1502. '69.0.3497.71',
  1503. '70.0.3535.2',
  1504. '70.0.3535.1',
  1505. '70.0.3535.0',
  1506. '69.0.3497.70',
  1507. '68.0.3440.130',
  1508. '69.0.3497.69',
  1509. '68.0.3440.129',
  1510. '70.0.3534.4',
  1511. '70.0.3534.3',
  1512. '70.0.3534.2',
  1513. '70.0.3534.1',
  1514. '70.0.3534.0',
  1515. '69.0.3497.68',
  1516. '68.0.3440.128',
  1517. '70.0.3533.2',
  1518. '70.0.3533.1',
  1519. '70.0.3533.0',
  1520. '69.0.3497.67',
  1521. '68.0.3440.127',
  1522. '70.0.3532.6',
  1523. '70.0.3532.5',
  1524. '70.0.3532.4',
  1525. '69.0.3497.66',
  1526. '68.0.3440.126',
  1527. '70.0.3532.3',
  1528. '70.0.3532.2',
  1529. '70.0.3532.1',
  1530. '69.0.3497.60',
  1531. '69.0.3497.65',
  1532. '69.0.3497.64',
  1533. '70.0.3532.0',
  1534. '70.0.3531.0',
  1535. '70.0.3530.4',
  1536. '70.0.3530.3',
  1537. '70.0.3530.2',
  1538. '69.0.3497.58',
  1539. '68.0.3440.125',
  1540. '69.0.3497.57',
  1541. '69.0.3497.56',
  1542. '69.0.3497.55',
  1543. '69.0.3497.54',
  1544. '70.0.3530.1',
  1545. '70.0.3530.0',
  1546. '69.0.3497.53',
  1547. '68.0.3440.124',
  1548. '69.0.3497.52',
  1549. '70.0.3529.3',
  1550. '70.0.3529.2',
  1551. '70.0.3529.1',
  1552. '70.0.3529.0',
  1553. '69.0.3497.51',
  1554. '70.0.3528.4',
  1555. '68.0.3440.123',
  1556. '70.0.3528.3',
  1557. '70.0.3528.2',
  1558. '70.0.3528.1',
  1559. '70.0.3528.0',
  1560. '69.0.3497.50',
  1561. '68.0.3440.122',
  1562. '70.0.3527.1',
  1563. '70.0.3527.0',
  1564. '69.0.3497.49',
  1565. '68.0.3440.121',
  1566. '70.0.3526.1',
  1567. '70.0.3526.0',
  1568. '68.0.3440.120',
  1569. '69.0.3497.48',
  1570. '69.0.3497.47',
  1571. '68.0.3440.119',
  1572. '68.0.3440.118',
  1573. '70.0.3525.5',
  1574. '70.0.3525.4',
  1575. '70.0.3525.3',
  1576. '68.0.3440.117',
  1577. '69.0.3497.46',
  1578. '70.0.3525.2',
  1579. '70.0.3525.1',
  1580. '70.0.3525.0',
  1581. '69.0.3497.45',
  1582. '68.0.3440.116',
  1583. '70.0.3524.4',
  1584. '70.0.3524.3',
  1585. '69.0.3497.44',
  1586. '70.0.3524.2',
  1587. '70.0.3524.1',
  1588. '70.0.3524.0',
  1589. '70.0.3523.2',
  1590. '69.0.3497.43',
  1591. '68.0.3440.115',
  1592. '70.0.3505.9',
  1593. '69.0.3497.42',
  1594. '70.0.3505.8',
  1595. '70.0.3523.1',
  1596. '70.0.3523.0',
  1597. '69.0.3497.41',
  1598. '68.0.3440.114',
  1599. '70.0.3505.7',
  1600. '69.0.3497.40',
  1601. '70.0.3522.1',
  1602. '70.0.3522.0',
  1603. '70.0.3521.2',
  1604. '69.0.3497.39',
  1605. '68.0.3440.113',
  1606. '70.0.3505.6',
  1607. '70.0.3521.1',
  1608. '70.0.3521.0',
  1609. '69.0.3497.38',
  1610. '68.0.3440.112',
  1611. '70.0.3520.1',
  1612. '70.0.3520.0',
  1613. '69.0.3497.37',
  1614. '68.0.3440.111',
  1615. '70.0.3519.3',
  1616. '70.0.3519.2',
  1617. '70.0.3519.1',
  1618. '70.0.3519.0',
  1619. '69.0.3497.36',
  1620. '68.0.3440.110',
  1621. '70.0.3518.1',
  1622. '70.0.3518.0',
  1623. '69.0.3497.35',
  1624. '69.0.3497.34',
  1625. '68.0.3440.109',
  1626. '70.0.3517.1',
  1627. '70.0.3517.0',
  1628. '69.0.3497.33',
  1629. '68.0.3440.108',
  1630. '69.0.3497.32',
  1631. '70.0.3516.3',
  1632. '70.0.3516.2',
  1633. '70.0.3516.1',
  1634. '70.0.3516.0',
  1635. '69.0.3497.31',
  1636. '68.0.3440.107',
  1637. '70.0.3515.4',
  1638. '68.0.3440.106',
  1639. '70.0.3515.3',
  1640. '70.0.3515.2',
  1641. '70.0.3515.1',
  1642. '70.0.3515.0',
  1643. '69.0.3497.30',
  1644. '68.0.3440.105',
  1645. '68.0.3440.104',
  1646. '70.0.3514.2',
  1647. '70.0.3514.1',
  1648. '70.0.3514.0',
  1649. '69.0.3497.29',
  1650. '68.0.3440.103',
  1651. '70.0.3513.1',
  1652. '70.0.3513.0',
  1653. '69.0.3497.28',
  1654. )
  1655. return _USER_AGENT_TPL % random.choice(_CHROME_VERSIONS)
  1656. std_headers = {
  1657. 'User-Agent': random_user_agent(),
  1658. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  1659. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  1660. 'Accept-Encoding': 'gzip, deflate',
  1661. 'Accept-Language': 'en-us,en;q=0.5',
  1662. }
  1663. USER_AGENTS = {
  1664. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  1665. }
  1666. NO_DEFAULT = object()
  1667. ENGLISH_MONTH_NAMES = [
  1668. 'January', 'February', 'March', 'April', 'May', 'June',
  1669. 'July', 'August', 'September', 'October', 'November', 'December']
  1670. MONTH_NAMES = {
  1671. 'en': ENGLISH_MONTH_NAMES,
  1672. 'fr': [
  1673. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  1674. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  1675. }
  1676. KNOWN_EXTENSIONS = (
  1677. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  1678. 'flv', 'f4v', 'f4a', 'f4b',
  1679. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  1680. 'mkv', 'mka', 'mk3d',
  1681. 'avi', 'divx',
  1682. 'mov',
  1683. 'asf', 'wmv', 'wma',
  1684. '3gp', '3g2',
  1685. 'mp3',
  1686. 'flac',
  1687. 'ape',
  1688. 'wav',
  1689. 'f4f', 'f4m', 'm3u8', 'smil')
  1690. # needed for sanitizing filenames in restricted mode
  1691. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  1692. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
  1693. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
  1694. DATE_FORMATS = (
  1695. '%d %B %Y',
  1696. '%d %b %Y',
  1697. '%B %d %Y',
  1698. '%B %dst %Y',
  1699. '%B %dnd %Y',
  1700. '%B %drd %Y',
  1701. '%B %dth %Y',
  1702. '%b %d %Y',
  1703. '%b %dst %Y',
  1704. '%b %dnd %Y',
  1705. '%b %drd %Y',
  1706. '%b %dth %Y',
  1707. '%b %dst %Y %I:%M',
  1708. '%b %dnd %Y %I:%M',
  1709. '%b %drd %Y %I:%M',
  1710. '%b %dth %Y %I:%M',
  1711. '%Y %m %d',
  1712. '%Y-%m-%d',
  1713. '%Y/%m/%d',
  1714. '%Y/%m/%d %H:%M',
  1715. '%Y/%m/%d %H:%M:%S',
  1716. '%Y-%m-%d %H:%M',
  1717. '%Y-%m-%d %H:%M:%S',
  1718. '%Y-%m-%d %H:%M:%S.%f',
  1719. '%d.%m.%Y %H:%M',
  1720. '%d.%m.%Y %H.%M',
  1721. '%Y-%m-%dT%H:%M:%SZ',
  1722. '%Y-%m-%dT%H:%M:%S.%fZ',
  1723. '%Y-%m-%dT%H:%M:%S.%f0Z',
  1724. '%Y-%m-%dT%H:%M:%S',
  1725. '%Y-%m-%dT%H:%M:%S.%f',
  1726. '%Y-%m-%dT%H:%M',
  1727. '%b %d %Y at %H:%M',
  1728. '%b %d %Y at %H:%M:%S',
  1729. '%B %d %Y at %H:%M',
  1730. '%B %d %Y at %H:%M:%S',
  1731. )
  1732. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  1733. DATE_FORMATS_DAY_FIRST.extend([
  1734. '%d-%m-%Y',
  1735. '%d.%m.%Y',
  1736. '%d.%m.%y',
  1737. '%d/%m/%Y',
  1738. '%d/%m/%y',
  1739. '%d/%m/%Y %H:%M:%S',
  1740. ])
  1741. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  1742. DATE_FORMATS_MONTH_FIRST.extend([
  1743. '%m-%d-%Y',
  1744. '%m.%d.%Y',
  1745. '%m/%d/%Y',
  1746. '%m/%d/%y',
  1747. '%m/%d/%Y %H:%M:%S',
  1748. ])
  1749. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  1750. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  1751. def preferredencoding():
  1752. """Get preferred encoding.
  1753. Returns the best encoding scheme for the system, based on
  1754. locale.getpreferredencoding() and some further tweaks.
  1755. """
  1756. try:
  1757. pref = locale.getpreferredencoding()
  1758. 'TEST'.encode(pref)
  1759. except Exception:
  1760. pref = 'UTF-8'
  1761. return pref
  1762. def write_json_file(obj, fn):
  1763. """ Encode obj as JSON and write it to fn, atomically if possible """
  1764. fn = encodeFilename(fn)
  1765. if sys.version_info < (3, 0) and sys.platform != 'win32':
  1766. encoding = get_filesystem_encoding()
  1767. # os.path.basename returns a bytes object, but NamedTemporaryFile
  1768. # will fail if the filename contains non ascii characters unless we
  1769. # use a unicode object
  1770. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  1771. # the same for os.path.dirname
  1772. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  1773. else:
  1774. path_basename = os.path.basename
  1775. path_dirname = os.path.dirname
  1776. args = {
  1777. 'suffix': '.tmp',
  1778. 'prefix': path_basename(fn) + '.',
  1779. 'dir': path_dirname(fn),
  1780. 'delete': False,
  1781. }
  1782. # In Python 2.x, json.dump expects a bytestream.
  1783. # In Python 3.x, it writes to a character stream
  1784. if sys.version_info < (3, 0):
  1785. args['mode'] = 'wb'
  1786. else:
  1787. args.update({
  1788. 'mode': 'w',
  1789. 'encoding': 'utf-8',
  1790. })
  1791. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  1792. try:
  1793. with tf:
  1794. json.dump(obj, tf)
  1795. if sys.platform == 'win32':
  1796. # Need to remove existing file on Windows, else os.rename raises
  1797. # WindowsError or FileExistsError.
  1798. try:
  1799. os.unlink(fn)
  1800. except OSError:
  1801. pass
  1802. os.rename(tf.name, fn)
  1803. except Exception:
  1804. try:
  1805. os.remove(tf.name)
  1806. except OSError:
  1807. pass
  1808. raise
  1809. if sys.version_info >= (2, 7):
  1810. def find_xpath_attr(node, xpath, key, val=None):
  1811. """ Find the xpath xpath[@key=val] """
  1812. assert re.match(r'^[a-zA-Z_-]+$', key)
  1813. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  1814. return node.find(expr)
  1815. else:
  1816. def find_xpath_attr(node, xpath, key, val=None):
  1817. for f in node.findall(compat_xpath(xpath)):
  1818. if key not in f.attrib:
  1819. continue
  1820. if val is None or f.attrib.get(key) == val:
  1821. return f
  1822. return None
  1823. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  1824. # the namespace parameter
  1825. def xpath_with_ns(path, ns_map):
  1826. components = [c.split(':') for c in path.split('/')]
  1827. replaced = []
  1828. for c in components:
  1829. if len(c) == 1:
  1830. replaced.append(c[0])
  1831. else:
  1832. ns, tag = c
  1833. replaced.append('{%s}%s' % (ns_map[ns], tag))
  1834. return '/'.join(replaced)
  1835. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1836. def _find_xpath(xpath):
  1837. return node.find(compat_xpath(xpath))
  1838. if isinstance(xpath, (str, compat_str)):
  1839. n = _find_xpath(xpath)
  1840. else:
  1841. for xp in xpath:
  1842. n = _find_xpath(xp)
  1843. if n is not None:
  1844. break
  1845. if n is None:
  1846. if default is not NO_DEFAULT:
  1847. return default
  1848. elif fatal:
  1849. name = xpath if name is None else name
  1850. raise ExtractorError('Could not find XML element %s' % name)
  1851. else:
  1852. return None
  1853. return n
  1854. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1855. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  1856. if n is None or n == default:
  1857. return n
  1858. if n.text is None:
  1859. if default is not NO_DEFAULT:
  1860. return default
  1861. elif fatal:
  1862. name = xpath if name is None else name
  1863. raise ExtractorError('Could not find XML element\'s text %s' % name)
  1864. else:
  1865. return None
  1866. return n.text
  1867. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  1868. n = find_xpath_attr(node, xpath, key)
  1869. if n is None:
  1870. if default is not NO_DEFAULT:
  1871. return default
  1872. elif fatal:
  1873. name = '%s[@%s]' % (xpath, key) if name is None else name
  1874. raise ExtractorError('Could not find XML attribute %s' % name)
  1875. else:
  1876. return None
  1877. return n.attrib[key]
  1878. def get_element_by_id(id, html):
  1879. """Return the content of the tag with the specified ID in the passed HTML document"""
  1880. return get_element_by_attribute('id', id, html)
  1881. def get_element_by_class(class_name, html):
  1882. """Return the content of the first tag with the specified class in the passed HTML document"""
  1883. retval = get_elements_by_class(class_name, html)
  1884. return retval[0] if retval else None
  1885. def get_element_by_attribute(attribute, value, html, escape_value=True):
  1886. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  1887. return retval[0] if retval else None
  1888. def get_elements_by_class(class_name, html):
  1889. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  1890. return get_elements_by_attribute(
  1891. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  1892. html, escape_value=False)
  1893. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  1894. """Return the content of the tag with the specified attribute in the passed HTML document"""
  1895. value = re.escape(value) if escape_value else value
  1896. retlist = []
  1897. for m in re.finditer(r'''(?xs)
  1898. <([a-zA-Z0-9:._-]+)
  1899. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1900. \s+%s=['"]?%s['"]?
  1901. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1902. \s*>
  1903. (?P<content>.*?)
  1904. </\1>
  1905. ''' % (re.escape(attribute), value), html):
  1906. res = m.group('content')
  1907. if res.startswith('"') or res.startswith("'"):
  1908. res = res[1:-1]
  1909. retlist.append(unescapeHTML(res))
  1910. return retlist
  1911. class HTMLAttributeParser(compat_HTMLParser):
  1912. """Trivial HTML parser to gather the attributes for a single element"""
  1913. def __init__(self):
  1914. self.attrs = {}
  1915. compat_HTMLParser.__init__(self)
  1916. def handle_starttag(self, tag, attrs):
  1917. self.attrs = dict(attrs)
  1918. def extract_attributes(html_element):
  1919. """Given a string for an HTML element such as
  1920. <el
  1921. a="foo" B="bar" c="&98;az" d=boz
  1922. empty= noval entity="&amp;"
  1923. sq='"' dq="'"
  1924. >
  1925. Decode and return a dictionary of attributes.
  1926. {
  1927. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  1928. 'empty': '', 'noval': None, 'entity': '&',
  1929. 'sq': '"', 'dq': '\''
  1930. }.
  1931. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  1932. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  1933. """
  1934. parser = HTMLAttributeParser()
  1935. try:
  1936. parser.feed(html_element)
  1937. parser.close()
  1938. # Older Python may throw HTMLParseError in case of malformed HTML
  1939. except compat_HTMLParseError:
  1940. pass
  1941. return parser.attrs
  1942. def clean_html(html):
  1943. """Clean an HTML snippet into a readable string"""
  1944. if html is None: # Convenience for sanitizing descriptions etc.
  1945. return html
  1946. # Newline vs <br />
  1947. html = html.replace('\n', ' ')
  1948. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  1949. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  1950. # Strip html tags
  1951. html = re.sub('<.*?>', '', html)
  1952. # Replace html entities
  1953. html = unescapeHTML(html)
  1954. return html.strip()
  1955. def sanitize_open(filename, open_mode):
  1956. """Try to open the given filename, and slightly tweak it if this fails.
  1957. Attempts to open the given filename. If this fails, it tries to change
  1958. the filename slightly, step by step, until it's either able to open it
  1959. or it fails and raises a final exception, like the standard open()
  1960. function.
  1961. It returns the tuple (stream, definitive_file_name).
  1962. """
  1963. try:
  1964. if filename == '-':
  1965. if sys.platform == 'win32':
  1966. import msvcrt
  1967. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  1968. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  1969. stream = open(encodeFilename(filename), open_mode)
  1970. return (stream, filename)
  1971. except (IOError, OSError) as err:
  1972. if err.errno in (errno.EACCES,):
  1973. raise
  1974. # In case of error, try to remove win32 forbidden chars
  1975. alt_filename = sanitize_path(filename)
  1976. if alt_filename == filename:
  1977. raise
  1978. else:
  1979. # An exception here should be caught in the caller
  1980. stream = open(encodeFilename(alt_filename), open_mode)
  1981. return (stream, alt_filename)
  1982. def timeconvert(timestr):
  1983. """Convert RFC 2822 defined time string into system timestamp"""
  1984. timestamp = None
  1985. timetuple = email.utils.parsedate_tz(timestr)
  1986. if timetuple is not None:
  1987. timestamp = email.utils.mktime_tz(timetuple)
  1988. return timestamp
  1989. def sanitize_filename(s, restricted=False, is_id=False):
  1990. """Sanitizes a string so it could be used as part of a filename.
  1991. If restricted is set, use a stricter subset of allowed characters.
  1992. Set is_id if this is not an arbitrary string, but an ID that should be kept
  1993. if possible.
  1994. """
  1995. def replace_insane(char):
  1996. if restricted and char in ACCENT_CHARS:
  1997. return ACCENT_CHARS[char]
  1998. if char == '?' or ord(char) < 32 or ord(char) == 127:
  1999. return ''
  2000. elif char == '"':
  2001. return '' if restricted else '\''
  2002. elif char == ':':
  2003. return '_-' if restricted else ' -'
  2004. elif char in '\\/|*<>':
  2005. return '_'
  2006. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  2007. return '_'
  2008. if restricted and ord(char) > 127:
  2009. return '_'
  2010. return char
  2011. # Handle timestamps
  2012. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  2013. result = ''.join(map(replace_insane, s))
  2014. if not is_id:
  2015. while '__' in result:
  2016. result = result.replace('__', '_')
  2017. result = result.strip('_')
  2018. # Common case of "Foreign band name - English song title"
  2019. if restricted and result.startswith('-_'):
  2020. result = result[2:]
  2021. if result.startswith('-'):
  2022. result = '_' + result[len('-'):]
  2023. result = result.lstrip('.')
  2024. if not result:
  2025. result = '_'
  2026. return result
  2027. def sanitize_path(s):
  2028. """Sanitizes and normalizes path on Windows"""
  2029. if sys.platform != 'win32':
  2030. return s
  2031. drive_or_unc, _ = os.path.splitdrive(s)
  2032. if sys.version_info < (2, 7) and not drive_or_unc:
  2033. drive_or_unc, _ = os.path.splitunc(s)
  2034. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  2035. if drive_or_unc:
  2036. norm_path.pop(0)
  2037. sanitized_path = [
  2038. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  2039. for path_part in norm_path]
  2040. if drive_or_unc:
  2041. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  2042. return os.path.join(*sanitized_path)
  2043. def sanitize_url(url):
  2044. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  2045. # the number of unwanted failures due to missing protocol
  2046. if url.startswith('//'):
  2047. return 'http:%s' % url
  2048. # Fix some common typos seen so far
  2049. COMMON_TYPOS = (
  2050. # https://github.com/ytdl-org/youtube-dl/issues/15649
  2051. (r'^httpss://', r'https://'),
  2052. # https://bx1.be/lives/direct-tv/
  2053. (r'^rmtp([es]?)://', r'rtmp\1://'),
  2054. )
  2055. for mistake, fixup in COMMON_TYPOS:
  2056. if re.match(mistake, url):
  2057. return re.sub(mistake, fixup, url)
  2058. return url
  2059. def sanitized_Request(url, *args, **kwargs):
  2060. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  2061. def expand_path(s):
  2062. """Expand shell variables and ~"""
  2063. return os.path.expandvars(compat_expanduser(s))
  2064. def orderedSet(iterable):
  2065. """ Remove all duplicates from the input iterable """
  2066. res = []
  2067. for el in iterable:
  2068. if el not in res:
  2069. res.append(el)
  2070. return res
  2071. def _htmlentity_transform(entity_with_semicolon):
  2072. """Transforms an HTML entity to a character."""
  2073. entity = entity_with_semicolon[:-1]
  2074. # Known non-numeric HTML entity
  2075. if entity in compat_html_entities.name2codepoint:
  2076. return compat_chr(compat_html_entities.name2codepoint[entity])
  2077. # TODO: HTML5 allows entities without a semicolon. For example,
  2078. # '&Eacuteric' should be decoded as 'Éric'.
  2079. if entity_with_semicolon in compat_html_entities_html5:
  2080. return compat_html_entities_html5[entity_with_semicolon]
  2081. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  2082. if mobj is not None:
  2083. numstr = mobj.group(1)
  2084. if numstr.startswith('x'):
  2085. base = 16
  2086. numstr = '0%s' % numstr
  2087. else:
  2088. base = 10
  2089. # See https://github.com/ytdl-org/youtube-dl/issues/7518
  2090. try:
  2091. return compat_chr(int(numstr, base))
  2092. except ValueError:
  2093. pass
  2094. # Unknown entity in name, return its literal representation
  2095. return '&%s;' % entity
  2096. def unescapeHTML(s):
  2097. if s is None:
  2098. return None
  2099. assert type(s) == compat_str
  2100. return re.sub(
  2101. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  2102. def get_subprocess_encoding():
  2103. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2104. # For subprocess calls, encode with locale encoding
  2105. # Refer to http://stackoverflow.com/a/9951851/35070
  2106. encoding = preferredencoding()
  2107. else:
  2108. encoding = sys.getfilesystemencoding()
  2109. if encoding is None:
  2110. encoding = 'utf-8'
  2111. return encoding
  2112. def encodeFilename(s, for_subprocess=False):
  2113. """
  2114. @param s The name of the file
  2115. """
  2116. assert type(s) == compat_str
  2117. # Python 3 has a Unicode API
  2118. if sys.version_info >= (3, 0):
  2119. return s
  2120. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  2121. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  2122. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  2123. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2124. return s
  2125. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  2126. if sys.platform.startswith('java'):
  2127. return s
  2128. return s.encode(get_subprocess_encoding(), 'ignore')
  2129. def decodeFilename(b, for_subprocess=False):
  2130. if sys.version_info >= (3, 0):
  2131. return b
  2132. if not isinstance(b, bytes):
  2133. return b
  2134. return b.decode(get_subprocess_encoding(), 'ignore')
  2135. def encodeArgument(s):
  2136. if not isinstance(s, compat_str):
  2137. # Legacy code that uses byte strings
  2138. # Uncomment the following line after fixing all post processors
  2139. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  2140. s = s.decode('ascii')
  2141. return encodeFilename(s, True)
  2142. def decodeArgument(b):
  2143. return decodeFilename(b, True)
  2144. def decodeOption(optval):
  2145. if optval is None:
  2146. return optval
  2147. if isinstance(optval, bytes):
  2148. optval = optval.decode(preferredencoding())
  2149. assert isinstance(optval, compat_str)
  2150. return optval
  2151. def formatSeconds(secs):
  2152. if secs > 3600:
  2153. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  2154. elif secs > 60:
  2155. return '%d:%02d' % (secs // 60, secs % 60)
  2156. else:
  2157. return '%d' % secs
  2158. def make_HTTPS_handler(params, **kwargs):
  2159. opts_no_check_certificate = params.get('nocheckcertificate', False)
  2160. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  2161. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  2162. if opts_no_check_certificate:
  2163. context.check_hostname = False
  2164. context.verify_mode = ssl.CERT_NONE
  2165. try:
  2166. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2167. except TypeError:
  2168. # Python 2.7.8
  2169. # (create_default_context present but HTTPSHandler has no context=)
  2170. pass
  2171. if sys.version_info < (3, 2):
  2172. return YoutubeDLHTTPSHandler(params, **kwargs)
  2173. else: # Python < 3.4
  2174. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  2175. context.verify_mode = (ssl.CERT_NONE
  2176. if opts_no_check_certificate
  2177. else ssl.CERT_REQUIRED)
  2178. context.set_default_verify_paths()
  2179. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2180. def bug_reports_message():
  2181. if ytdl_is_updateable():
  2182. update_cmd = 'type youtube-dl -U to update'
  2183. else:
  2184. update_cmd = 'see https://yt-dl.org/update on how to update'
  2185. msg = '; please report this issue on https://yt-dl.org/bug .'
  2186. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  2187. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  2188. return msg
  2189. class YoutubeDLError(Exception):
  2190. """Base exception for YoutubeDL errors."""
  2191. pass
  2192. class ExtractorError(YoutubeDLError):
  2193. """Error during info extraction."""
  2194. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  2195. """ tb, if given, is the original traceback (so that it can be printed out).
  2196. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  2197. """
  2198. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  2199. expected = True
  2200. if video_id is not None:
  2201. msg = video_id + ': ' + msg
  2202. if cause:
  2203. msg += ' (caused by %r)' % cause
  2204. if not expected:
  2205. msg += bug_reports_message()
  2206. super(ExtractorError, self).__init__(msg)
  2207. self.traceback = tb
  2208. self.exc_info = sys.exc_info() # preserve original exception
  2209. self.cause = cause
  2210. self.video_id = video_id
  2211. def format_traceback(self):
  2212. if self.traceback is None:
  2213. return None
  2214. return ''.join(traceback.format_tb(self.traceback))
  2215. class UnsupportedError(ExtractorError):
  2216. def __init__(self, url):
  2217. super(UnsupportedError, self).__init__(
  2218. 'Unsupported URL: %s' % url, expected=True)
  2219. self.url = url
  2220. class RegexNotFoundError(ExtractorError):
  2221. """Error when a regex didn't match"""
  2222. pass
  2223. class GeoRestrictedError(ExtractorError):
  2224. """Geographic restriction Error exception.
  2225. This exception may be thrown when a video is not available from your
  2226. geographic location due to geographic restrictions imposed by a website.
  2227. """
  2228. def __init__(self, msg, countries=None):
  2229. super(GeoRestrictedError, self).__init__(msg, expected=True)
  2230. self.msg = msg
  2231. self.countries = countries
  2232. class DownloadError(YoutubeDLError):
  2233. """Download Error exception.
  2234. This exception may be thrown by FileDownloader objects if they are not
  2235. configured to continue on errors. They will contain the appropriate
  2236. error message.
  2237. """
  2238. def __init__(self, msg, exc_info=None):
  2239. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  2240. super(DownloadError, self).__init__(msg)
  2241. self.exc_info = exc_info
  2242. class SameFileError(YoutubeDLError):
  2243. """Same File exception.
  2244. This exception will be thrown by FileDownloader objects if they detect
  2245. multiple files would have to be downloaded to the same file on disk.
  2246. """
  2247. pass
  2248. class PostProcessingError(YoutubeDLError):
  2249. """Post Processing exception.
  2250. This exception may be raised by PostProcessor's .run() method to
  2251. indicate an error in the postprocessing task.
  2252. """
  2253. def __init__(self, msg):
  2254. super(PostProcessingError, self).__init__(msg)
  2255. self.msg = msg
  2256. class MaxDownloadsReached(YoutubeDLError):
  2257. """ --max-downloads limit has been reached. """
  2258. pass
  2259. class UnavailableVideoError(YoutubeDLError):
  2260. """Unavailable Format exception.
  2261. This exception will be thrown when a video is requested
  2262. in a format that is not available for that video.
  2263. """
  2264. pass
  2265. class ContentTooShortError(YoutubeDLError):
  2266. """Content Too Short exception.
  2267. This exception may be raised by FileDownloader objects when a file they
  2268. download is too small for what the server announced first, indicating
  2269. the connection was probably interrupted.
  2270. """
  2271. def __init__(self, downloaded, expected):
  2272. super(ContentTooShortError, self).__init__(
  2273. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  2274. )
  2275. # Both in bytes
  2276. self.downloaded = downloaded
  2277. self.expected = expected
  2278. class XAttrMetadataError(YoutubeDLError):
  2279. def __init__(self, code=None, msg='Unknown error'):
  2280. super(XAttrMetadataError, self).__init__(msg)
  2281. self.code = code
  2282. self.msg = msg
  2283. # Parsing code and msg
  2284. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  2285. or 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  2286. self.reason = 'NO_SPACE'
  2287. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  2288. self.reason = 'VALUE_TOO_LONG'
  2289. else:
  2290. self.reason = 'NOT_SUPPORTED'
  2291. class XAttrUnavailableError(YoutubeDLError):
  2292. pass
  2293. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  2294. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  2295. # expected HTTP responses to meet HTTP/1.0 or later (see also
  2296. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  2297. if sys.version_info < (3, 0):
  2298. kwargs['strict'] = True
  2299. hc = http_class(*args, **compat_kwargs(kwargs))
  2300. source_address = ydl_handler._params.get('source_address')
  2301. if source_address is not None:
  2302. # This is to workaround _create_connection() from socket where it will try all
  2303. # address data from getaddrinfo() including IPv6. This filters the result from
  2304. # getaddrinfo() based on the source_address value.
  2305. # This is based on the cpython socket.create_connection() function.
  2306. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  2307. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  2308. host, port = address
  2309. err = None
  2310. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  2311. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  2312. ip_addrs = [addr for addr in addrs if addr[0] == af]
  2313. if addrs and not ip_addrs:
  2314. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  2315. raise socket.error(
  2316. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  2317. % (ip_version, source_address[0]))
  2318. for res in ip_addrs:
  2319. af, socktype, proto, canonname, sa = res
  2320. sock = None
  2321. try:
  2322. sock = socket.socket(af, socktype, proto)
  2323. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  2324. sock.settimeout(timeout)
  2325. sock.bind(source_address)
  2326. sock.connect(sa)
  2327. err = None # Explicitly break reference cycle
  2328. return sock
  2329. except socket.error as _:
  2330. err = _
  2331. if sock is not None:
  2332. sock.close()
  2333. if err is not None:
  2334. raise err
  2335. else:
  2336. raise socket.error('getaddrinfo returns an empty list')
  2337. if hasattr(hc, '_create_connection'):
  2338. hc._create_connection = _create_connection
  2339. sa = (source_address, 0)
  2340. if hasattr(hc, 'source_address'): # Python 2.7+
  2341. hc.source_address = sa
  2342. else: # Python 2.6
  2343. def _hc_connect(self, *args, **kwargs):
  2344. sock = _create_connection(
  2345. (self.host, self.port), self.timeout, sa)
  2346. if is_https:
  2347. self.sock = ssl.wrap_socket(
  2348. sock, self.key_file, self.cert_file,
  2349. ssl_version=ssl.PROTOCOL_TLSv1)
  2350. else:
  2351. self.sock = sock
  2352. hc.connect = functools.partial(_hc_connect, hc)
  2353. return hc
  2354. def handle_youtubedl_headers(headers):
  2355. filtered_headers = headers
  2356. if 'Youtubedl-no-compression' in filtered_headers:
  2357. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  2358. del filtered_headers['Youtubedl-no-compression']
  2359. return filtered_headers
  2360. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  2361. """Handler for HTTP requests and responses.
  2362. This class, when installed with an OpenerDirector, automatically adds
  2363. the standard headers to every HTTP request and handles gzipped and
  2364. deflated responses from web servers. If compression is to be avoided in
  2365. a particular request, the original request in the program code only has
  2366. to include the HTTP header "Youtubedl-no-compression", which will be
  2367. removed before making the real request.
  2368. Part of this code was copied from:
  2369. http://techknack.net/python-urllib2-handlers/
  2370. Andrew Rowls, the author of that code, agreed to release it to the
  2371. public domain.
  2372. """
  2373. def __init__(self, params, *args, **kwargs):
  2374. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  2375. self._params = params
  2376. def http_open(self, req):
  2377. conn_class = compat_http_client.HTTPConnection
  2378. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2379. if socks_proxy:
  2380. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2381. del req.headers['Ytdl-socks-proxy']
  2382. return self.do_open(functools.partial(
  2383. _create_http_connection, self, conn_class, False),
  2384. req)
  2385. @staticmethod
  2386. def deflate(data):
  2387. try:
  2388. return zlib.decompress(data, -zlib.MAX_WBITS)
  2389. except zlib.error:
  2390. return zlib.decompress(data)
  2391. def http_request(self, req):
  2392. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  2393. # always respected by websites, some tend to give out URLs with non percent-encoded
  2394. # non-ASCII characters (see telemb.py, ard.py [#3412])
  2395. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  2396. # To work around aforementioned issue we will replace request's original URL with
  2397. # percent-encoded one
  2398. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  2399. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  2400. url = req.get_full_url()
  2401. url_escaped = escape_url(url)
  2402. # Substitute URL if any change after escaping
  2403. if url != url_escaped:
  2404. req = update_Request(req, url=url_escaped)
  2405. for h, v in std_headers.items():
  2406. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  2407. # The dict keys are capitalized because of this bug by urllib
  2408. if h.capitalize() not in req.headers:
  2409. req.add_header(h, v)
  2410. req.headers = handle_youtubedl_headers(req.headers)
  2411. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  2412. # Python 2.6 is brain-dead when it comes to fragments
  2413. req._Request__original = req._Request__original.partition('#')[0]
  2414. req._Request__r_type = req._Request__r_type.partition('#')[0]
  2415. return req
  2416. def http_response(self, req, resp):
  2417. old_resp = resp
  2418. # gzip
  2419. if resp.headers.get('Content-encoding', '') == 'gzip':
  2420. content = resp.read()
  2421. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  2422. try:
  2423. uncompressed = io.BytesIO(gz.read())
  2424. except IOError as original_ioerror:
  2425. # There may be junk add the end of the file
  2426. # See http://stackoverflow.com/q/4928560/35070 for details
  2427. for i in range(1, 1024):
  2428. try:
  2429. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  2430. uncompressed = io.BytesIO(gz.read())
  2431. except IOError:
  2432. continue
  2433. break
  2434. else:
  2435. raise original_ioerror
  2436. resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  2437. resp.msg = old_resp.msg
  2438. del resp.headers['Content-encoding']
  2439. # deflate
  2440. if resp.headers.get('Content-encoding', '') == 'deflate':
  2441. gz = io.BytesIO(self.deflate(resp.read()))
  2442. resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  2443. resp.msg = old_resp.msg
  2444. del resp.headers['Content-encoding']
  2445. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  2446. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  2447. if 300 <= resp.code < 400:
  2448. location = resp.headers.get('Location')
  2449. if location:
  2450. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  2451. if sys.version_info >= (3, 0):
  2452. location = location.encode('iso-8859-1').decode('utf-8')
  2453. else:
  2454. location = location.decode('utf-8')
  2455. location_escaped = escape_url(location)
  2456. if location != location_escaped:
  2457. del resp.headers['Location']
  2458. if sys.version_info < (3, 0):
  2459. location_escaped = location_escaped.encode('utf-8')
  2460. resp.headers['Location'] = location_escaped
  2461. return resp
  2462. https_request = http_request
  2463. https_response = http_response
  2464. def make_socks_conn_class(base_class, socks_proxy):
  2465. assert issubclass(base_class, (
  2466. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  2467. url_components = compat_urlparse.urlparse(socks_proxy)
  2468. if url_components.scheme.lower() == 'socks5':
  2469. socks_type = ProxyType.SOCKS5
  2470. elif url_components.scheme.lower() in ('socks', 'socks4'):
  2471. socks_type = ProxyType.SOCKS4
  2472. elif url_components.scheme.lower() == 'socks4a':
  2473. socks_type = ProxyType.SOCKS4A
  2474. def unquote_if_non_empty(s):
  2475. if not s:
  2476. return s
  2477. return compat_urllib_parse_unquote_plus(s)
  2478. proxy_args = (
  2479. socks_type,
  2480. url_components.hostname, url_components.port or 1080,
  2481. True, # Remote DNS
  2482. unquote_if_non_empty(url_components.username),
  2483. unquote_if_non_empty(url_components.password),
  2484. )
  2485. class SocksConnection(base_class):
  2486. def connect(self):
  2487. self.sock = sockssocket()
  2488. self.sock.setproxy(*proxy_args)
  2489. if type(self.timeout) in (int, float):
  2490. self.sock.settimeout(self.timeout)
  2491. self.sock.connect((self.host, self.port))
  2492. if isinstance(self, compat_http_client.HTTPSConnection):
  2493. if hasattr(self, '_context'): # Python > 2.6
  2494. self.sock = self._context.wrap_socket(
  2495. self.sock, server_hostname=self.host)
  2496. else:
  2497. self.sock = ssl.wrap_socket(self.sock)
  2498. return SocksConnection
  2499. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  2500. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  2501. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  2502. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  2503. self._params = params
  2504. def https_open(self, req):
  2505. kwargs = {}
  2506. conn_class = self._https_conn_class
  2507. if hasattr(self, '_context'): # python > 2.6
  2508. kwargs['context'] = self._context
  2509. if hasattr(self, '_check_hostname'): # python 3.x
  2510. kwargs['check_hostname'] = self._check_hostname
  2511. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2512. if socks_proxy:
  2513. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2514. del req.headers['Ytdl-socks-proxy']
  2515. return self.do_open(functools.partial(
  2516. _create_http_connection, self, conn_class, True),
  2517. req, **kwargs)
  2518. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  2519. _HTTPONLY_PREFIX = '#HttpOnly_'
  2520. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  2521. # Store session cookies with `expires` set to 0 instead of an empty
  2522. # string
  2523. for cookie in self:
  2524. if cookie.expires is None:
  2525. cookie.expires = 0
  2526. compat_cookiejar.MozillaCookieJar.save(self, filename, ignore_discard, ignore_expires)
  2527. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  2528. """Load cookies from a file."""
  2529. if filename is None:
  2530. if self.filename is not None:
  2531. filename = self.filename
  2532. else:
  2533. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2534. cf = io.StringIO()
  2535. with open(filename) as f:
  2536. for line in f:
  2537. if line.startswith(self._HTTPONLY_PREFIX):
  2538. line = line[len(self._HTTPONLY_PREFIX):]
  2539. cf.write(compat_str(line))
  2540. cf.seek(0)
  2541. self._really_load(cf, filename, ignore_discard, ignore_expires)
  2542. # Session cookies are denoted by either `expires` field set to
  2543. # an empty string or 0. MozillaCookieJar only recognizes the former
  2544. # (see [1]). So we need force the latter to be recognized as session
  2545. # cookies on our own.
  2546. # Session cookies may be important for cookies-based authentication,
  2547. # e.g. usually, when user does not check 'Remember me' check box while
  2548. # logging in on a site, some important cookies are stored as session
  2549. # cookies so that not recognizing them will result in failed login.
  2550. # 1. https://bugs.python.org/issue17164
  2551. for cookie in self:
  2552. # Treat `expires=0` cookies as session cookies
  2553. if cookie.expires == 0:
  2554. cookie.expires = None
  2555. cookie.discard = True
  2556. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  2557. def __init__(self, cookiejar=None):
  2558. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  2559. def http_response(self, request, response):
  2560. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  2561. # characters in Set-Cookie HTTP header of last response (see
  2562. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  2563. # In order to at least prevent crashing we will percent encode Set-Cookie
  2564. # header before HTTPCookieProcessor starts processing it.
  2565. # if sys.version_info < (3, 0) and response.headers:
  2566. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  2567. # set_cookie = response.headers.get(set_cookie_header)
  2568. # if set_cookie:
  2569. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  2570. # if set_cookie != set_cookie_escaped:
  2571. # del response.headers[set_cookie_header]
  2572. # response.headers[set_cookie_header] = set_cookie_escaped
  2573. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  2574. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  2575. https_response = http_response
  2576. def extract_timezone(date_str):
  2577. m = re.search(
  2578. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  2579. date_str)
  2580. if not m:
  2581. timezone = datetime.timedelta()
  2582. else:
  2583. date_str = date_str[:-len(m.group('tz'))]
  2584. if not m.group('sign'):
  2585. timezone = datetime.timedelta()
  2586. else:
  2587. sign = 1 if m.group('sign') == '+' else -1
  2588. timezone = datetime.timedelta(
  2589. hours=sign * int(m.group('hours')),
  2590. minutes=sign * int(m.group('minutes')))
  2591. return timezone, date_str
  2592. def parse_iso8601(date_str, delimiter='T', timezone=None):
  2593. """ Return a UNIX timestamp from the given date """
  2594. if date_str is None:
  2595. return None
  2596. date_str = re.sub(r'\.[0-9]+', '', date_str)
  2597. if timezone is None:
  2598. timezone, date_str = extract_timezone(date_str)
  2599. try:
  2600. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  2601. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  2602. return calendar.timegm(dt.timetuple())
  2603. except ValueError:
  2604. pass
  2605. def date_formats(day_first=True):
  2606. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  2607. def unified_strdate(date_str, day_first=True):
  2608. """Return a string with the date in the format YYYYMMDD"""
  2609. if date_str is None:
  2610. return None
  2611. upload_date = None
  2612. # Replace commas
  2613. date_str = date_str.replace(',', ' ')
  2614. # Remove AM/PM + timezone
  2615. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2616. _, date_str = extract_timezone(date_str)
  2617. for expression in date_formats(day_first):
  2618. try:
  2619. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  2620. except ValueError:
  2621. pass
  2622. if upload_date is None:
  2623. timetuple = email.utils.parsedate_tz(date_str)
  2624. if timetuple:
  2625. try:
  2626. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  2627. except ValueError:
  2628. pass
  2629. if upload_date is not None:
  2630. return compat_str(upload_date)
  2631. def unified_timestamp(date_str, day_first=True):
  2632. if date_str is None:
  2633. return None
  2634. date_str = re.sub(r'[,|]', '', date_str)
  2635. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  2636. timezone, date_str = extract_timezone(date_str)
  2637. # Remove AM/PM + timezone
  2638. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2639. # Remove unrecognized timezones from ISO 8601 alike timestamps
  2640. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2641. if m:
  2642. date_str = date_str[:-len(m.group('tz'))]
  2643. # Python only supports microseconds, so remove nanoseconds
  2644. m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
  2645. if m:
  2646. date_str = m.group(1)
  2647. for expression in date_formats(day_first):
  2648. try:
  2649. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  2650. return calendar.timegm(dt.timetuple())
  2651. except ValueError:
  2652. pass
  2653. timetuple = email.utils.parsedate_tz(date_str)
  2654. if timetuple:
  2655. return calendar.timegm(timetuple) + pm_delta * 3600
  2656. def determine_ext(url, default_ext='unknown_video'):
  2657. if url is None or '.' not in url:
  2658. return default_ext
  2659. guess = url.partition('?')[0].rpartition('.')[2]
  2660. if re.match(r'^[A-Za-z0-9]+$', guess):
  2661. return guess
  2662. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  2663. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  2664. return guess.rstrip('/')
  2665. else:
  2666. return default_ext
  2667. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  2668. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  2669. def date_from_str(date_str):
  2670. """
  2671. Return a datetime object from a string in the format YYYYMMDD or
  2672. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  2673. today = datetime.date.today()
  2674. if date_str in ('now', 'today'):
  2675. return today
  2676. if date_str == 'yesterday':
  2677. return today - datetime.timedelta(days=1)
  2678. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  2679. if match is not None:
  2680. sign = match.group('sign')
  2681. time = int(match.group('time'))
  2682. if sign == '-':
  2683. time = -time
  2684. unit = match.group('unit')
  2685. # A bad approximation?
  2686. if unit == 'month':
  2687. unit = 'day'
  2688. time *= 30
  2689. elif unit == 'year':
  2690. unit = 'day'
  2691. time *= 365
  2692. unit += 's'
  2693. delta = datetime.timedelta(**{unit: time})
  2694. return today + delta
  2695. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  2696. def hyphenate_date(date_str):
  2697. """
  2698. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  2699. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  2700. if match is not None:
  2701. return '-'.join(match.groups())
  2702. else:
  2703. return date_str
  2704. class DateRange(object):
  2705. """Represents a time interval between two dates"""
  2706. def __init__(self, start=None, end=None):
  2707. """start and end must be strings in the format accepted by date"""
  2708. if start is not None:
  2709. self.start = date_from_str(start)
  2710. else:
  2711. self.start = datetime.datetime.min.date()
  2712. if end is not None:
  2713. self.end = date_from_str(end)
  2714. else:
  2715. self.end = datetime.datetime.max.date()
  2716. if self.start > self.end:
  2717. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  2718. @classmethod
  2719. def day(cls, day):
  2720. """Returns a range that only contains the given day"""
  2721. return cls(day, day)
  2722. def __contains__(self, date):
  2723. """Check if the date is in the range"""
  2724. if not isinstance(date, datetime.date):
  2725. date = date_from_str(date)
  2726. return self.start <= date <= self.end
  2727. def __str__(self):
  2728. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  2729. def platform_name():
  2730. """ Returns the platform name as a compat_str """
  2731. res = platform.platform()
  2732. if isinstance(res, bytes):
  2733. res = res.decode(preferredencoding())
  2734. assert isinstance(res, compat_str)
  2735. return res
  2736. def _windows_write_string(s, out):
  2737. """ Returns True if the string was written using special methods,
  2738. False if it has yet to be written out."""
  2739. # Adapted from http://stackoverflow.com/a/3259271/35070
  2740. import ctypes
  2741. import ctypes.wintypes
  2742. WIN_OUTPUT_IDS = {
  2743. 1: -11,
  2744. 2: -12,
  2745. }
  2746. try:
  2747. fileno = out.fileno()
  2748. except AttributeError:
  2749. # If the output stream doesn't have a fileno, it's virtual
  2750. return False
  2751. except io.UnsupportedOperation:
  2752. # Some strange Windows pseudo files?
  2753. return False
  2754. if fileno not in WIN_OUTPUT_IDS:
  2755. return False
  2756. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  2757. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  2758. ('GetStdHandle', ctypes.windll.kernel32))
  2759. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  2760. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  2761. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  2762. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  2763. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  2764. written = ctypes.wintypes.DWORD(0)
  2765. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  2766. FILE_TYPE_CHAR = 0x0002
  2767. FILE_TYPE_REMOTE = 0x8000
  2768. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  2769. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  2770. ctypes.POINTER(ctypes.wintypes.DWORD))(
  2771. ('GetConsoleMode', ctypes.windll.kernel32))
  2772. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  2773. def not_a_console(handle):
  2774. if handle == INVALID_HANDLE_VALUE or handle is None:
  2775. return True
  2776. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  2777. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  2778. if not_a_console(h):
  2779. return False
  2780. def next_nonbmp_pos(s):
  2781. try:
  2782. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  2783. except StopIteration:
  2784. return len(s)
  2785. while s:
  2786. count = min(next_nonbmp_pos(s), 1024)
  2787. ret = WriteConsoleW(
  2788. h, s, count if count else 2, ctypes.byref(written), None)
  2789. if ret == 0:
  2790. raise OSError('Failed to write string')
  2791. if not count: # We just wrote a non-BMP character
  2792. assert written.value == 2
  2793. s = s[1:]
  2794. else:
  2795. assert written.value > 0
  2796. s = s[written.value:]
  2797. return True
  2798. def write_string(s, out=None, encoding=None):
  2799. if out is None:
  2800. out = sys.stderr
  2801. assert type(s) == compat_str
  2802. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  2803. if _windows_write_string(s, out):
  2804. return
  2805. if ('b' in getattr(out, 'mode', '')
  2806. or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  2807. byt = s.encode(encoding or preferredencoding(), 'ignore')
  2808. out.write(byt)
  2809. elif hasattr(out, 'buffer'):
  2810. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  2811. byt = s.encode(enc, 'ignore')
  2812. out.buffer.write(byt)
  2813. else:
  2814. out.write(s)
  2815. out.flush()
  2816. def bytes_to_intlist(bs):
  2817. if not bs:
  2818. return []
  2819. if isinstance(bs[0], int): # Python 3
  2820. return list(bs)
  2821. else:
  2822. return [ord(c) for c in bs]
  2823. def intlist_to_bytes(xs):
  2824. if not xs:
  2825. return b''
  2826. return compat_struct_pack('%dB' % len(xs), *xs)
  2827. # Cross-platform file locking
  2828. if sys.platform == 'win32':
  2829. import ctypes.wintypes
  2830. import msvcrt
  2831. class OVERLAPPED(ctypes.Structure):
  2832. _fields_ = [
  2833. ('Internal', ctypes.wintypes.LPVOID),
  2834. ('InternalHigh', ctypes.wintypes.LPVOID),
  2835. ('Offset', ctypes.wintypes.DWORD),
  2836. ('OffsetHigh', ctypes.wintypes.DWORD),
  2837. ('hEvent', ctypes.wintypes.HANDLE),
  2838. ]
  2839. kernel32 = ctypes.windll.kernel32
  2840. LockFileEx = kernel32.LockFileEx
  2841. LockFileEx.argtypes = [
  2842. ctypes.wintypes.HANDLE, # hFile
  2843. ctypes.wintypes.DWORD, # dwFlags
  2844. ctypes.wintypes.DWORD, # dwReserved
  2845. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2846. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2847. ctypes.POINTER(OVERLAPPED) # Overlapped
  2848. ]
  2849. LockFileEx.restype = ctypes.wintypes.BOOL
  2850. UnlockFileEx = kernel32.UnlockFileEx
  2851. UnlockFileEx.argtypes = [
  2852. ctypes.wintypes.HANDLE, # hFile
  2853. ctypes.wintypes.DWORD, # dwReserved
  2854. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2855. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2856. ctypes.POINTER(OVERLAPPED) # Overlapped
  2857. ]
  2858. UnlockFileEx.restype = ctypes.wintypes.BOOL
  2859. whole_low = 0xffffffff
  2860. whole_high = 0x7fffffff
  2861. def _lock_file(f, exclusive):
  2862. overlapped = OVERLAPPED()
  2863. overlapped.Offset = 0
  2864. overlapped.OffsetHigh = 0
  2865. overlapped.hEvent = 0
  2866. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  2867. handle = msvcrt.get_osfhandle(f.fileno())
  2868. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  2869. whole_low, whole_high, f._lock_file_overlapped_p):
  2870. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  2871. def _unlock_file(f):
  2872. assert f._lock_file_overlapped_p
  2873. handle = msvcrt.get_osfhandle(f.fileno())
  2874. if not UnlockFileEx(handle, 0,
  2875. whole_low, whole_high, f._lock_file_overlapped_p):
  2876. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  2877. else:
  2878. # Some platforms, such as Jython, is missing fcntl
  2879. try:
  2880. import fcntl
  2881. def _lock_file(f, exclusive):
  2882. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  2883. def _unlock_file(f):
  2884. fcntl.flock(f, fcntl.LOCK_UN)
  2885. except ImportError:
  2886. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  2887. def _lock_file(f, exclusive):
  2888. raise IOError(UNSUPPORTED_MSG)
  2889. def _unlock_file(f):
  2890. raise IOError(UNSUPPORTED_MSG)
  2891. class locked_file(object):
  2892. def __init__(self, filename, mode, encoding=None):
  2893. assert mode in ['r', 'a', 'w']
  2894. self.f = io.open(filename, mode, encoding=encoding)
  2895. self.mode = mode
  2896. def __enter__(self):
  2897. exclusive = self.mode != 'r'
  2898. try:
  2899. _lock_file(self.f, exclusive)
  2900. except IOError:
  2901. self.f.close()
  2902. raise
  2903. return self
  2904. def __exit__(self, etype, value, traceback):
  2905. try:
  2906. _unlock_file(self.f)
  2907. finally:
  2908. self.f.close()
  2909. def __iter__(self):
  2910. return iter(self.f)
  2911. def write(self, *args):
  2912. return self.f.write(*args)
  2913. def read(self, *args):
  2914. return self.f.read(*args)
  2915. def get_filesystem_encoding():
  2916. encoding = sys.getfilesystemencoding()
  2917. return encoding if encoding is not None else 'utf-8'
  2918. def shell_quote(args):
  2919. quoted_args = []
  2920. encoding = get_filesystem_encoding()
  2921. for a in args:
  2922. if isinstance(a, bytes):
  2923. # We may get a filename encoded with 'encodeFilename'
  2924. a = a.decode(encoding)
  2925. quoted_args.append(compat_shlex_quote(a))
  2926. return ' '.join(quoted_args)
  2927. def smuggle_url(url, data):
  2928. """ Pass additional data in a URL for internal use. """
  2929. url, idata = unsmuggle_url(url, {})
  2930. data.update(idata)
  2931. sdata = compat_urllib_parse_urlencode(
  2932. {'__youtubedl_smuggle': json.dumps(data)})
  2933. return url + '#' + sdata
  2934. def unsmuggle_url(smug_url, default=None):
  2935. if '#__youtubedl_smuggle' not in smug_url:
  2936. return smug_url, default
  2937. url, _, sdata = smug_url.rpartition('#')
  2938. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  2939. data = json.loads(jsond)
  2940. return url, data
  2941. def format_bytes(bytes):
  2942. if bytes is None:
  2943. return 'N/A'
  2944. if type(bytes) is str:
  2945. bytes = float(bytes)
  2946. if bytes == 0.0:
  2947. exponent = 0
  2948. else:
  2949. exponent = int(math.log(bytes, 1024.0))
  2950. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  2951. converted = float(bytes) / float(1024 ** exponent)
  2952. return '%.2f%s' % (converted, suffix)
  2953. def lookup_unit_table(unit_table, s):
  2954. units_re = '|'.join(re.escape(u) for u in unit_table)
  2955. m = re.match(
  2956. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  2957. if not m:
  2958. return None
  2959. num_str = m.group('num').replace(',', '.')
  2960. mult = unit_table[m.group('unit')]
  2961. return int(float(num_str) * mult)
  2962. def parse_filesize(s):
  2963. if s is None:
  2964. return None
  2965. # The lower-case forms are of course incorrect and unofficial,
  2966. # but we support those too
  2967. _UNIT_TABLE = {
  2968. 'B': 1,
  2969. 'b': 1,
  2970. 'bytes': 1,
  2971. 'KiB': 1024,
  2972. 'KB': 1000,
  2973. 'kB': 1024,
  2974. 'Kb': 1000,
  2975. 'kb': 1000,
  2976. 'kilobytes': 1000,
  2977. 'kibibytes': 1024,
  2978. 'MiB': 1024 ** 2,
  2979. 'MB': 1000 ** 2,
  2980. 'mB': 1024 ** 2,
  2981. 'Mb': 1000 ** 2,
  2982. 'mb': 1000 ** 2,
  2983. 'megabytes': 1000 ** 2,
  2984. 'mebibytes': 1024 ** 2,
  2985. 'GiB': 1024 ** 3,
  2986. 'GB': 1000 ** 3,
  2987. 'gB': 1024 ** 3,
  2988. 'Gb': 1000 ** 3,
  2989. 'gb': 1000 ** 3,
  2990. 'gigabytes': 1000 ** 3,
  2991. 'gibibytes': 1024 ** 3,
  2992. 'TiB': 1024 ** 4,
  2993. 'TB': 1000 ** 4,
  2994. 'tB': 1024 ** 4,
  2995. 'Tb': 1000 ** 4,
  2996. 'tb': 1000 ** 4,
  2997. 'terabytes': 1000 ** 4,
  2998. 'tebibytes': 1024 ** 4,
  2999. 'PiB': 1024 ** 5,
  3000. 'PB': 1000 ** 5,
  3001. 'pB': 1024 ** 5,
  3002. 'Pb': 1000 ** 5,
  3003. 'pb': 1000 ** 5,
  3004. 'petabytes': 1000 ** 5,
  3005. 'pebibytes': 1024 ** 5,
  3006. 'EiB': 1024 ** 6,
  3007. 'EB': 1000 ** 6,
  3008. 'eB': 1024 ** 6,
  3009. 'Eb': 1000 ** 6,
  3010. 'eb': 1000 ** 6,
  3011. 'exabytes': 1000 ** 6,
  3012. 'exbibytes': 1024 ** 6,
  3013. 'ZiB': 1024 ** 7,
  3014. 'ZB': 1000 ** 7,
  3015. 'zB': 1024 ** 7,
  3016. 'Zb': 1000 ** 7,
  3017. 'zb': 1000 ** 7,
  3018. 'zettabytes': 1000 ** 7,
  3019. 'zebibytes': 1024 ** 7,
  3020. 'YiB': 1024 ** 8,
  3021. 'YB': 1000 ** 8,
  3022. 'yB': 1024 ** 8,
  3023. 'Yb': 1000 ** 8,
  3024. 'yb': 1000 ** 8,
  3025. 'yottabytes': 1000 ** 8,
  3026. 'yobibytes': 1024 ** 8,
  3027. }
  3028. return lookup_unit_table(_UNIT_TABLE, s)
  3029. def parse_count(s):
  3030. if s is None:
  3031. return None
  3032. s = s.strip()
  3033. if re.match(r'^[\d,.]+$', s):
  3034. return str_to_int(s)
  3035. _UNIT_TABLE = {
  3036. 'k': 1000,
  3037. 'K': 1000,
  3038. 'm': 1000 ** 2,
  3039. 'M': 1000 ** 2,
  3040. 'kk': 1000 ** 2,
  3041. 'KK': 1000 ** 2,
  3042. }
  3043. return lookup_unit_table(_UNIT_TABLE, s)
  3044. def parse_resolution(s):
  3045. if s is None:
  3046. return {}
  3047. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  3048. if mobj:
  3049. return {
  3050. 'width': int(mobj.group('w')),
  3051. 'height': int(mobj.group('h')),
  3052. }
  3053. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  3054. if mobj:
  3055. return {'height': int(mobj.group(1))}
  3056. mobj = re.search(r'\b([48])[kK]\b', s)
  3057. if mobj:
  3058. return {'height': int(mobj.group(1)) * 540}
  3059. return {}
  3060. def parse_bitrate(s):
  3061. if not isinstance(s, compat_str):
  3062. return
  3063. mobj = re.search(r'\b(\d+)\s*kbps', s)
  3064. if mobj:
  3065. return int(mobj.group(1))
  3066. def month_by_name(name, lang='en'):
  3067. """ Return the number of a month by (locale-independently) English name """
  3068. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  3069. try:
  3070. return month_names.index(name) + 1
  3071. except ValueError:
  3072. return None
  3073. def month_by_abbreviation(abbrev):
  3074. """ Return the number of a month by (locale-independently) English
  3075. abbreviations """
  3076. try:
  3077. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  3078. except ValueError:
  3079. return None
  3080. def fix_xml_ampersands(xml_str):
  3081. """Replace all the '&' by '&amp;' in XML"""
  3082. return re.sub(
  3083. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  3084. '&amp;',
  3085. xml_str)
  3086. def setproctitle(title):
  3087. assert isinstance(title, compat_str)
  3088. # ctypes in Jython is not complete
  3089. # http://bugs.jython.org/issue2148
  3090. if sys.platform.startswith('java'):
  3091. return
  3092. try:
  3093. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  3094. except OSError:
  3095. return
  3096. except TypeError:
  3097. # LoadLibrary in Windows Python 2.7.13 only expects
  3098. # a bytestring, but since unicode_literals turns
  3099. # every string into a unicode string, it fails.
  3100. return
  3101. title_bytes = title.encode('utf-8')
  3102. buf = ctypes.create_string_buffer(len(title_bytes))
  3103. buf.value = title_bytes
  3104. try:
  3105. libc.prctl(15, buf, 0, 0, 0)
  3106. except AttributeError:
  3107. return # Strange libc, just skip this
  3108. def remove_start(s, start):
  3109. return s[len(start):] if s is not None and s.startswith(start) else s
  3110. def remove_end(s, end):
  3111. return s[:-len(end)] if s is not None and s.endswith(end) else s
  3112. def remove_quotes(s):
  3113. if s is None or len(s) < 2:
  3114. return s
  3115. for quote in ('"', "'", ):
  3116. if s[0] == quote and s[-1] == quote:
  3117. return s[1:-1]
  3118. return s
  3119. def url_basename(url):
  3120. path = compat_urlparse.urlparse(url).path
  3121. return path.strip('/').split('/')[-1]
  3122. def base_url(url):
  3123. return re.match(r'https?://[^?#&]+/', url).group()
  3124. def urljoin(base, path):
  3125. if isinstance(path, bytes):
  3126. path = path.decode('utf-8')
  3127. if not isinstance(path, compat_str) or not path:
  3128. return None
  3129. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  3130. return path
  3131. if isinstance(base, bytes):
  3132. base = base.decode('utf-8')
  3133. if not isinstance(base, compat_str) or not re.match(
  3134. r'^(?:https?:)?//', base):
  3135. return None
  3136. return compat_urlparse.urljoin(base, path)
  3137. class HEADRequest(compat_urllib_request.Request):
  3138. def get_method(self):
  3139. return 'HEAD'
  3140. class PUTRequest(compat_urllib_request.Request):
  3141. def get_method(self):
  3142. return 'PUT'
  3143. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  3144. if get_attr:
  3145. if v is not None:
  3146. v = getattr(v, get_attr, None)
  3147. if v == '':
  3148. v = None
  3149. if v is None:
  3150. return default
  3151. try:
  3152. return int(v) * invscale // scale
  3153. except (ValueError, TypeError):
  3154. return default
  3155. def str_or_none(v, default=None):
  3156. return default if v is None else compat_str(v)
  3157. def str_to_int(int_str):
  3158. """ A more relaxed version of int_or_none """
  3159. if int_str is None:
  3160. return None
  3161. int_str = re.sub(r'[,\.\+]', '', int_str)
  3162. return int(int_str)
  3163. def float_or_none(v, scale=1, invscale=1, default=None):
  3164. if v is None:
  3165. return default
  3166. try:
  3167. return float(v) * invscale / scale
  3168. except (ValueError, TypeError):
  3169. return default
  3170. def bool_or_none(v, default=None):
  3171. return v if isinstance(v, bool) else default
  3172. def strip_or_none(v, default=None):
  3173. return v.strip() if isinstance(v, compat_str) else default
  3174. def url_or_none(url):
  3175. if not url or not isinstance(url, compat_str):
  3176. return None
  3177. url = url.strip()
  3178. return url if re.match(r'^(?:[a-zA-Z][\da-zA-Z.+-]*:)?//', url) else None
  3179. def parse_duration(s):
  3180. if not isinstance(s, compat_basestring):
  3181. return None
  3182. s = s.strip()
  3183. days, hours, mins, secs, ms = [None] * 5
  3184. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s)
  3185. if m:
  3186. days, hours, mins, secs, ms = m.groups()
  3187. else:
  3188. m = re.match(
  3189. r'''(?ix)(?:P?
  3190. (?:
  3191. [0-9]+\s*y(?:ears?)?\s*
  3192. )?
  3193. (?:
  3194. [0-9]+\s*m(?:onths?)?\s*
  3195. )?
  3196. (?:
  3197. [0-9]+\s*w(?:eeks?)?\s*
  3198. )?
  3199. (?:
  3200. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  3201. )?
  3202. T)?
  3203. (?:
  3204. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  3205. )?
  3206. (?:
  3207. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  3208. )?
  3209. (?:
  3210. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  3211. )?Z?$''', s)
  3212. if m:
  3213. days, hours, mins, secs, ms = m.groups()
  3214. else:
  3215. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  3216. if m:
  3217. hours, mins = m.groups()
  3218. else:
  3219. return None
  3220. duration = 0
  3221. if secs:
  3222. duration += float(secs)
  3223. if mins:
  3224. duration += float(mins) * 60
  3225. if hours:
  3226. duration += float(hours) * 60 * 60
  3227. if days:
  3228. duration += float(days) * 24 * 60 * 60
  3229. if ms:
  3230. duration += float(ms)
  3231. return duration
  3232. def prepend_extension(filename, ext, expected_real_ext=None):
  3233. name, real_ext = os.path.splitext(filename)
  3234. return (
  3235. '{0}.{1}{2}'.format(name, ext, real_ext)
  3236. if not expected_real_ext or real_ext[1:] == expected_real_ext
  3237. else '{0}.{1}'.format(filename, ext))
  3238. def replace_extension(filename, ext, expected_real_ext=None):
  3239. name, real_ext = os.path.splitext(filename)
  3240. return '{0}.{1}'.format(
  3241. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  3242. ext)
  3243. def check_executable(exe, args=[]):
  3244. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  3245. args can be a list of arguments for a short output (like -version) """
  3246. try:
  3247. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  3248. except OSError:
  3249. return False
  3250. return exe
  3251. def get_exe_version(exe, args=['--version'],
  3252. version_re=None, unrecognized='present'):
  3253. """ Returns the version of the specified executable,
  3254. or False if the executable is not present """
  3255. try:
  3256. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  3257. # SIGTTOU if youtube-dl is run in the background.
  3258. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  3259. out, _ = subprocess.Popen(
  3260. [encodeArgument(exe)] + args,
  3261. stdin=subprocess.PIPE,
  3262. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  3263. except OSError:
  3264. return False
  3265. if isinstance(out, bytes): # Python 2.x
  3266. out = out.decode('ascii', 'ignore')
  3267. return detect_exe_version(out, version_re, unrecognized)
  3268. def detect_exe_version(output, version_re=None, unrecognized='present'):
  3269. assert isinstance(output, compat_str)
  3270. if version_re is None:
  3271. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  3272. m = re.search(version_re, output)
  3273. if m:
  3274. return m.group(1)
  3275. else:
  3276. return unrecognized
  3277. class PagedList(object):
  3278. def __len__(self):
  3279. # This is only useful for tests
  3280. return len(self.getslice())
  3281. class OnDemandPagedList(PagedList):
  3282. def __init__(self, pagefunc, pagesize, use_cache=True):
  3283. self._pagefunc = pagefunc
  3284. self._pagesize = pagesize
  3285. self._use_cache = use_cache
  3286. if use_cache:
  3287. self._cache = {}
  3288. def getslice(self, start=0, end=None):
  3289. res = []
  3290. for pagenum in itertools.count(start // self._pagesize):
  3291. firstid = pagenum * self._pagesize
  3292. nextfirstid = pagenum * self._pagesize + self._pagesize
  3293. if start >= nextfirstid:
  3294. continue
  3295. page_results = None
  3296. if self._use_cache:
  3297. page_results = self._cache.get(pagenum)
  3298. if page_results is None:
  3299. page_results = list(self._pagefunc(pagenum))
  3300. if self._use_cache:
  3301. self._cache[pagenum] = page_results
  3302. startv = (
  3303. start % self._pagesize
  3304. if firstid <= start < nextfirstid
  3305. else 0)
  3306. endv = (
  3307. ((end - 1) % self._pagesize) + 1
  3308. if (end is not None and firstid <= end <= nextfirstid)
  3309. else None)
  3310. if startv != 0 or endv is not None:
  3311. page_results = page_results[startv:endv]
  3312. res.extend(page_results)
  3313. # A little optimization - if current page is not "full", ie. does
  3314. # not contain page_size videos then we can assume that this page
  3315. # is the last one - there are no more ids on further pages -
  3316. # i.e. no need to query again.
  3317. if len(page_results) + startv < self._pagesize:
  3318. break
  3319. # If we got the whole page, but the next page is not interesting,
  3320. # break out early as well
  3321. if end == nextfirstid:
  3322. break
  3323. return res
  3324. class InAdvancePagedList(PagedList):
  3325. def __init__(self, pagefunc, pagecount, pagesize):
  3326. self._pagefunc = pagefunc
  3327. self._pagecount = pagecount
  3328. self._pagesize = pagesize
  3329. def getslice(self, start=0, end=None):
  3330. res = []
  3331. start_page = start // self._pagesize
  3332. end_page = (
  3333. self._pagecount if end is None else (end // self._pagesize + 1))
  3334. skip_elems = start - start_page * self._pagesize
  3335. only_more = None if end is None else end - start
  3336. for pagenum in range(start_page, end_page):
  3337. page = list(self._pagefunc(pagenum))
  3338. if skip_elems:
  3339. page = page[skip_elems:]
  3340. skip_elems = None
  3341. if only_more is not None:
  3342. if len(page) < only_more:
  3343. only_more -= len(page)
  3344. else:
  3345. page = page[:only_more]
  3346. res.extend(page)
  3347. break
  3348. res.extend(page)
  3349. return res
  3350. def uppercase_escape(s):
  3351. unicode_escape = codecs.getdecoder('unicode_escape')
  3352. return re.sub(
  3353. r'\\U[0-9a-fA-F]{8}',
  3354. lambda m: unicode_escape(m.group(0))[0],
  3355. s)
  3356. def lowercase_escape(s):
  3357. unicode_escape = codecs.getdecoder('unicode_escape')
  3358. return re.sub(
  3359. r'\\u[0-9a-fA-F]{4}',
  3360. lambda m: unicode_escape(m.group(0))[0],
  3361. s)
  3362. def escape_rfc3986(s):
  3363. """Escape non-ASCII characters as suggested by RFC 3986"""
  3364. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  3365. s = s.encode('utf-8')
  3366. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  3367. def escape_url(url):
  3368. """Escape URL as suggested by RFC 3986"""
  3369. url_parsed = compat_urllib_parse_urlparse(url)
  3370. return url_parsed._replace(
  3371. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  3372. path=escape_rfc3986(url_parsed.path),
  3373. params=escape_rfc3986(url_parsed.params),
  3374. query=escape_rfc3986(url_parsed.query),
  3375. fragment=escape_rfc3986(url_parsed.fragment)
  3376. ).geturl()
  3377. def read_batch_urls(batch_fd):
  3378. def fixup(url):
  3379. if not isinstance(url, compat_str):
  3380. url = url.decode('utf-8', 'replace')
  3381. BOM_UTF8 = '\xef\xbb\xbf'
  3382. if url.startswith(BOM_UTF8):
  3383. url = url[len(BOM_UTF8):]
  3384. url = url.strip()
  3385. if url.startswith(('#', ';', ']')):
  3386. return False
  3387. return url
  3388. with contextlib.closing(batch_fd) as fd:
  3389. return [url for url in map(fixup, fd) if url]
  3390. def urlencode_postdata(*args, **kargs):
  3391. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  3392. def update_url_query(url, query):
  3393. if not query:
  3394. return url
  3395. parsed_url = compat_urlparse.urlparse(url)
  3396. qs = compat_parse_qs(parsed_url.query)
  3397. qs.update(query)
  3398. return compat_urlparse.urlunparse(parsed_url._replace(
  3399. query=compat_urllib_parse_urlencode(qs, True)))
  3400. def update_Request(req, url=None, data=None, headers={}, query={}):
  3401. req_headers = req.headers.copy()
  3402. req_headers.update(headers)
  3403. req_data = data or req.data
  3404. req_url = update_url_query(url or req.get_full_url(), query)
  3405. req_get_method = req.get_method()
  3406. if req_get_method == 'HEAD':
  3407. req_type = HEADRequest
  3408. elif req_get_method == 'PUT':
  3409. req_type = PUTRequest
  3410. else:
  3411. req_type = compat_urllib_request.Request
  3412. new_req = req_type(
  3413. req_url, data=req_data, headers=req_headers,
  3414. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  3415. if hasattr(req, 'timeout'):
  3416. new_req.timeout = req.timeout
  3417. return new_req
  3418. def _multipart_encode_impl(data, boundary):
  3419. content_type = 'multipart/form-data; boundary=%s' % boundary
  3420. out = b''
  3421. for k, v in data.items():
  3422. out += b'--' + boundary.encode('ascii') + b'\r\n'
  3423. if isinstance(k, compat_str):
  3424. k = k.encode('utf-8')
  3425. if isinstance(v, compat_str):
  3426. v = v.encode('utf-8')
  3427. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  3428. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  3429. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  3430. if boundary.encode('ascii') in content:
  3431. raise ValueError('Boundary overlaps with data')
  3432. out += content
  3433. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  3434. return out, content_type
  3435. def multipart_encode(data, boundary=None):
  3436. '''
  3437. Encode a dict to RFC 7578-compliant form-data
  3438. data:
  3439. A dict where keys and values can be either Unicode or bytes-like
  3440. objects.
  3441. boundary:
  3442. If specified a Unicode object, it's used as the boundary. Otherwise
  3443. a random boundary is generated.
  3444. Reference: https://tools.ietf.org/html/rfc7578
  3445. '''
  3446. has_specified_boundary = boundary is not None
  3447. while True:
  3448. if boundary is None:
  3449. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  3450. try:
  3451. out, content_type = _multipart_encode_impl(data, boundary)
  3452. break
  3453. except ValueError:
  3454. if has_specified_boundary:
  3455. raise
  3456. boundary = None
  3457. return out, content_type
  3458. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  3459. if isinstance(key_or_keys, (list, tuple)):
  3460. for key in key_or_keys:
  3461. if key not in d or d[key] is None or skip_false_values and not d[key]:
  3462. continue
  3463. return d[key]
  3464. return default
  3465. return d.get(key_or_keys, default)
  3466. def try_get(src, getter, expected_type=None):
  3467. if not isinstance(getter, (list, tuple)):
  3468. getter = [getter]
  3469. for get in getter:
  3470. try:
  3471. v = get(src)
  3472. except (AttributeError, KeyError, TypeError, IndexError):
  3473. pass
  3474. else:
  3475. if expected_type is None or isinstance(v, expected_type):
  3476. return v
  3477. def merge_dicts(*dicts):
  3478. merged = {}
  3479. for a_dict in dicts:
  3480. for k, v in a_dict.items():
  3481. if v is None:
  3482. continue
  3483. if (k not in merged
  3484. or (isinstance(v, compat_str) and v
  3485. and isinstance(merged[k], compat_str)
  3486. and not merged[k])):
  3487. merged[k] = v
  3488. return merged
  3489. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  3490. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  3491. US_RATINGS = {
  3492. 'G': 0,
  3493. 'PG': 10,
  3494. 'PG-13': 13,
  3495. 'R': 16,
  3496. 'NC': 18,
  3497. }
  3498. TV_PARENTAL_GUIDELINES = {
  3499. 'TV-Y': 0,
  3500. 'TV-Y7': 7,
  3501. 'TV-G': 0,
  3502. 'TV-PG': 0,
  3503. 'TV-14': 14,
  3504. 'TV-MA': 17,
  3505. }
  3506. def parse_age_limit(s):
  3507. if type(s) == int:
  3508. return s if 0 <= s <= 21 else None
  3509. if not isinstance(s, compat_basestring):
  3510. return None
  3511. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  3512. if m:
  3513. return int(m.group('age'))
  3514. if s in US_RATINGS:
  3515. return US_RATINGS[s]
  3516. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  3517. if m:
  3518. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  3519. return None
  3520. def strip_jsonp(code):
  3521. return re.sub(
  3522. r'''(?sx)^
  3523. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  3524. (?:\s*&&\s*(?P=func_name))?
  3525. \s*\(\s*(?P<callback_data>.*)\);?
  3526. \s*?(?://[^\n]*)*$''',
  3527. r'\g<callback_data>', code)
  3528. def js_to_json(code):
  3529. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  3530. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  3531. INTEGER_TABLE = (
  3532. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  3533. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  3534. )
  3535. def fix_kv(m):
  3536. v = m.group(0)
  3537. if v in ('true', 'false', 'null'):
  3538. return v
  3539. elif v.startswith('/*') or v.startswith('//') or v == ',':
  3540. return ""
  3541. if v[0] in ("'", '"'):
  3542. v = re.sub(r'(?s)\\.|"', lambda m: {
  3543. '"': '\\"',
  3544. "\\'": "'",
  3545. '\\\n': '',
  3546. '\\x': '\\u00',
  3547. }.get(m.group(0), m.group(0)), v[1:-1])
  3548. for regex, base in INTEGER_TABLE:
  3549. im = re.match(regex, v)
  3550. if im:
  3551. i = int(im.group(1), base)
  3552. return '"%d":' % i if v.endswith(':') else '%d' % i
  3553. return '"%s"' % v
  3554. return re.sub(r'''(?sx)
  3555. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  3556. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  3557. {comment}|,(?={skip}[\]}}])|
  3558. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  3559. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  3560. [0-9]+(?={skip}:)
  3561. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  3562. def qualities(quality_ids):
  3563. """ Get a numeric quality value out of a list of possible values """
  3564. def q(qid):
  3565. try:
  3566. return quality_ids.index(qid)
  3567. except ValueError:
  3568. return -1
  3569. return q
  3570. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  3571. def limit_length(s, length):
  3572. """ Add ellipses to overly long strings """
  3573. if s is None:
  3574. return None
  3575. ELLIPSES = '...'
  3576. if len(s) > length:
  3577. return s[:length - len(ELLIPSES)] + ELLIPSES
  3578. return s
  3579. def version_tuple(v):
  3580. return tuple(int(e) for e in re.split(r'[-.]', v))
  3581. def is_outdated_version(version, limit, assume_new=True):
  3582. if not version:
  3583. return not assume_new
  3584. try:
  3585. return version_tuple(version) < version_tuple(limit)
  3586. except ValueError:
  3587. return not assume_new
  3588. def ytdl_is_updateable():
  3589. """ Returns if youtube-dl can be updated with -U """
  3590. from zipimport import zipimporter
  3591. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  3592. def args_to_str(args):
  3593. # Get a short string representation for a subprocess command
  3594. return ' '.join(compat_shlex_quote(a) for a in args)
  3595. def error_to_compat_str(err):
  3596. err_str = str(err)
  3597. # On python 2 error byte string must be decoded with proper
  3598. # encoding rather than ascii
  3599. if sys.version_info[0] < 3:
  3600. err_str = err_str.decode(preferredencoding())
  3601. return err_str
  3602. def mimetype2ext(mt):
  3603. if mt is None:
  3604. return None
  3605. ext = {
  3606. 'audio/mp4': 'm4a',
  3607. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  3608. # it's the most popular one
  3609. 'audio/mpeg': 'mp3',
  3610. }.get(mt)
  3611. if ext is not None:
  3612. return ext
  3613. _, _, res = mt.rpartition('/')
  3614. res = res.split(';')[0].strip().lower()
  3615. return {
  3616. '3gpp': '3gp',
  3617. 'smptett+xml': 'tt',
  3618. 'ttaf+xml': 'dfxp',
  3619. 'ttml+xml': 'ttml',
  3620. 'x-flv': 'flv',
  3621. 'x-mp4-fragmented': 'mp4',
  3622. 'x-ms-sami': 'sami',
  3623. 'x-ms-wmv': 'wmv',
  3624. 'mpegurl': 'm3u8',
  3625. 'x-mpegurl': 'm3u8',
  3626. 'vnd.apple.mpegurl': 'm3u8',
  3627. 'dash+xml': 'mpd',
  3628. 'f4m+xml': 'f4m',
  3629. 'hds+xml': 'f4m',
  3630. 'vnd.ms-sstr+xml': 'ism',
  3631. 'quicktime': 'mov',
  3632. 'mp2t': 'ts',
  3633. }.get(res, res)
  3634. def parse_codecs(codecs_str):
  3635. # http://tools.ietf.org/html/rfc6381
  3636. if not codecs_str:
  3637. return {}
  3638. splited_codecs = list(filter(None, map(
  3639. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  3640. vcodec, acodec = None, None
  3641. for full_codec in splited_codecs:
  3642. codec = full_codec.split('.')[0]
  3643. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'):
  3644. if not vcodec:
  3645. vcodec = full_codec
  3646. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  3647. if not acodec:
  3648. acodec = full_codec
  3649. else:
  3650. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  3651. if not vcodec and not acodec:
  3652. if len(splited_codecs) == 2:
  3653. return {
  3654. 'vcodec': splited_codecs[0],
  3655. 'acodec': splited_codecs[1],
  3656. }
  3657. else:
  3658. return {
  3659. 'vcodec': vcodec or 'none',
  3660. 'acodec': acodec or 'none',
  3661. }
  3662. return {}
  3663. def urlhandle_detect_ext(url_handle):
  3664. getheader = url_handle.headers.get
  3665. cd = getheader('Content-Disposition')
  3666. if cd:
  3667. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  3668. if m:
  3669. e = determine_ext(m.group('filename'), default_ext=None)
  3670. if e:
  3671. return e
  3672. return mimetype2ext(getheader('Content-Type'))
  3673. def encode_data_uri(data, mime_type):
  3674. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  3675. def age_restricted(content_limit, age_limit):
  3676. """ Returns True iff the content should be blocked """
  3677. if age_limit is None: # No limit set
  3678. return False
  3679. if content_limit is None:
  3680. return False # Content available for everyone
  3681. return age_limit < content_limit
  3682. def is_html(first_bytes):
  3683. """ Detect whether a file contains HTML by examining its first bytes. """
  3684. BOMS = [
  3685. (b'\xef\xbb\xbf', 'utf-8'),
  3686. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  3687. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  3688. (b'\xff\xfe', 'utf-16-le'),
  3689. (b'\xfe\xff', 'utf-16-be'),
  3690. ]
  3691. for bom, enc in BOMS:
  3692. if first_bytes.startswith(bom):
  3693. s = first_bytes[len(bom):].decode(enc, 'replace')
  3694. break
  3695. else:
  3696. s = first_bytes.decode('utf-8', 'replace')
  3697. return re.match(r'^\s*<', s)
  3698. def determine_protocol(info_dict):
  3699. protocol = info_dict.get('protocol')
  3700. if protocol is not None:
  3701. return protocol
  3702. url = info_dict['url']
  3703. if url.startswith('rtmp'):
  3704. return 'rtmp'
  3705. elif url.startswith('mms'):
  3706. return 'mms'
  3707. elif url.startswith('rtsp'):
  3708. return 'rtsp'
  3709. ext = determine_ext(url)
  3710. if ext == 'm3u8':
  3711. return 'm3u8'
  3712. elif ext == 'f4m':
  3713. return 'f4m'
  3714. return compat_urllib_parse_urlparse(url).scheme
  3715. def render_table(header_row, data):
  3716. """ Render a list of rows, each as a list of values """
  3717. table = [header_row] + data
  3718. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  3719. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  3720. return '\n'.join(format_str % tuple(row) for row in table)
  3721. def _match_one(filter_part, dct):
  3722. COMPARISON_OPERATORS = {
  3723. '<': operator.lt,
  3724. '<=': operator.le,
  3725. '>': operator.gt,
  3726. '>=': operator.ge,
  3727. '=': operator.eq,
  3728. '!=': operator.ne,
  3729. }
  3730. operator_rex = re.compile(r'''(?x)\s*
  3731. (?P<key>[a-z_]+)
  3732. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  3733. (?:
  3734. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  3735. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  3736. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  3737. )
  3738. \s*$
  3739. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  3740. m = operator_rex.search(filter_part)
  3741. if m:
  3742. op = COMPARISON_OPERATORS[m.group('op')]
  3743. actual_value = dct.get(m.group('key'))
  3744. if (m.group('quotedstrval') is not None
  3745. or m.group('strval') is not None
  3746. # If the original field is a string and matching comparisonvalue is
  3747. # a number we should respect the origin of the original field
  3748. # and process comparison value as a string (see
  3749. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  3750. or actual_value is not None and m.group('intval') is not None
  3751. and isinstance(actual_value, compat_str)):
  3752. if m.group('op') not in ('=', '!='):
  3753. raise ValueError(
  3754. 'Operator %s does not support string values!' % m.group('op'))
  3755. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  3756. quote = m.group('quote')
  3757. if quote is not None:
  3758. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  3759. else:
  3760. try:
  3761. comparison_value = int(m.group('intval'))
  3762. except ValueError:
  3763. comparison_value = parse_filesize(m.group('intval'))
  3764. if comparison_value is None:
  3765. comparison_value = parse_filesize(m.group('intval') + 'B')
  3766. if comparison_value is None:
  3767. raise ValueError(
  3768. 'Invalid integer value %r in filter part %r' % (
  3769. m.group('intval'), filter_part))
  3770. if actual_value is None:
  3771. return m.group('none_inclusive')
  3772. return op(actual_value, comparison_value)
  3773. UNARY_OPERATORS = {
  3774. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  3775. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  3776. }
  3777. operator_rex = re.compile(r'''(?x)\s*
  3778. (?P<op>%s)\s*(?P<key>[a-z_]+)
  3779. \s*$
  3780. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  3781. m = operator_rex.search(filter_part)
  3782. if m:
  3783. op = UNARY_OPERATORS[m.group('op')]
  3784. actual_value = dct.get(m.group('key'))
  3785. return op(actual_value)
  3786. raise ValueError('Invalid filter part %r' % filter_part)
  3787. def match_str(filter_str, dct):
  3788. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  3789. return all(
  3790. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  3791. def match_filter_func(filter_str):
  3792. def _match_func(info_dict):
  3793. if match_str(filter_str, info_dict):
  3794. return None
  3795. else:
  3796. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  3797. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  3798. return _match_func
  3799. def parse_dfxp_time_expr(time_expr):
  3800. if not time_expr:
  3801. return
  3802. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  3803. if mobj:
  3804. return float(mobj.group('time_offset'))
  3805. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  3806. if mobj:
  3807. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  3808. def srt_subtitles_timecode(seconds):
  3809. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  3810. def dfxp2srt(dfxp_data):
  3811. '''
  3812. @param dfxp_data A bytes-like object containing DFXP data
  3813. @returns A unicode object containing converted SRT data
  3814. '''
  3815. LEGACY_NAMESPACES = (
  3816. (b'http://www.w3.org/ns/ttml', [
  3817. b'http://www.w3.org/2004/11/ttaf1',
  3818. b'http://www.w3.org/2006/04/ttaf1',
  3819. b'http://www.w3.org/2006/10/ttaf1',
  3820. ]),
  3821. (b'http://www.w3.org/ns/ttml#styling', [
  3822. b'http://www.w3.org/ns/ttml#style',
  3823. ]),
  3824. )
  3825. SUPPORTED_STYLING = [
  3826. 'color',
  3827. 'fontFamily',
  3828. 'fontSize',
  3829. 'fontStyle',
  3830. 'fontWeight',
  3831. 'textDecoration'
  3832. ]
  3833. _x = functools.partial(xpath_with_ns, ns_map={
  3834. 'xml': 'http://www.w3.org/XML/1998/namespace',
  3835. 'ttml': 'http://www.w3.org/ns/ttml',
  3836. 'tts': 'http://www.w3.org/ns/ttml#styling',
  3837. })
  3838. styles = {}
  3839. default_style = {}
  3840. class TTMLPElementParser(object):
  3841. _out = ''
  3842. _unclosed_elements = []
  3843. _applied_styles = []
  3844. def start(self, tag, attrib):
  3845. if tag in (_x('ttml:br'), 'br'):
  3846. self._out += '\n'
  3847. else:
  3848. unclosed_elements = []
  3849. style = {}
  3850. element_style_id = attrib.get('style')
  3851. if default_style:
  3852. style.update(default_style)
  3853. if element_style_id:
  3854. style.update(styles.get(element_style_id, {}))
  3855. for prop in SUPPORTED_STYLING:
  3856. prop_val = attrib.get(_x('tts:' + prop))
  3857. if prop_val:
  3858. style[prop] = prop_val
  3859. if style:
  3860. font = ''
  3861. for k, v in sorted(style.items()):
  3862. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  3863. continue
  3864. if k == 'color':
  3865. font += ' color="%s"' % v
  3866. elif k == 'fontSize':
  3867. font += ' size="%s"' % v
  3868. elif k == 'fontFamily':
  3869. font += ' face="%s"' % v
  3870. elif k == 'fontWeight' and v == 'bold':
  3871. self._out += '<b>'
  3872. unclosed_elements.append('b')
  3873. elif k == 'fontStyle' and v == 'italic':
  3874. self._out += '<i>'
  3875. unclosed_elements.append('i')
  3876. elif k == 'textDecoration' and v == 'underline':
  3877. self._out += '<u>'
  3878. unclosed_elements.append('u')
  3879. if font:
  3880. self._out += '<font' + font + '>'
  3881. unclosed_elements.append('font')
  3882. applied_style = {}
  3883. if self._applied_styles:
  3884. applied_style.update(self._applied_styles[-1])
  3885. applied_style.update(style)
  3886. self._applied_styles.append(applied_style)
  3887. self._unclosed_elements.append(unclosed_elements)
  3888. def end(self, tag):
  3889. if tag not in (_x('ttml:br'), 'br'):
  3890. unclosed_elements = self._unclosed_elements.pop()
  3891. for element in reversed(unclosed_elements):
  3892. self._out += '</%s>' % element
  3893. if unclosed_elements and self._applied_styles:
  3894. self._applied_styles.pop()
  3895. def data(self, data):
  3896. self._out += data
  3897. def close(self):
  3898. return self._out.strip()
  3899. def parse_node(node):
  3900. target = TTMLPElementParser()
  3901. parser = xml.etree.ElementTree.XMLParser(target=target)
  3902. parser.feed(xml.etree.ElementTree.tostring(node))
  3903. return parser.close()
  3904. for k, v in LEGACY_NAMESPACES:
  3905. for ns in v:
  3906. dfxp_data = dfxp_data.replace(ns, k)
  3907. dfxp = compat_etree_fromstring(dfxp_data)
  3908. out = []
  3909. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  3910. if not paras:
  3911. raise ValueError('Invalid dfxp/TTML subtitle')
  3912. repeat = False
  3913. while True:
  3914. for style in dfxp.findall(_x('.//ttml:style')):
  3915. style_id = style.get('id') or style.get(_x('xml:id'))
  3916. if not style_id:
  3917. continue
  3918. parent_style_id = style.get('style')
  3919. if parent_style_id:
  3920. if parent_style_id not in styles:
  3921. repeat = True
  3922. continue
  3923. styles[style_id] = styles[parent_style_id].copy()
  3924. for prop in SUPPORTED_STYLING:
  3925. prop_val = style.get(_x('tts:' + prop))
  3926. if prop_val:
  3927. styles.setdefault(style_id, {})[prop] = prop_val
  3928. if repeat:
  3929. repeat = False
  3930. else:
  3931. break
  3932. for p in ('body', 'div'):
  3933. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  3934. if ele is None:
  3935. continue
  3936. style = styles.get(ele.get('style'))
  3937. if not style:
  3938. continue
  3939. default_style.update(style)
  3940. for para, index in zip(paras, itertools.count(1)):
  3941. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  3942. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  3943. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  3944. if begin_time is None:
  3945. continue
  3946. if not end_time:
  3947. if not dur:
  3948. continue
  3949. end_time = begin_time + dur
  3950. out.append('%d\n%s --> %s\n%s\n\n' % (
  3951. index,
  3952. srt_subtitles_timecode(begin_time),
  3953. srt_subtitles_timecode(end_time),
  3954. parse_node(para)))
  3955. return ''.join(out)
  3956. def cli_option(params, command_option, param):
  3957. param = params.get(param)
  3958. if param:
  3959. param = compat_str(param)
  3960. return [command_option, param] if param is not None else []
  3961. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  3962. param = params.get(param)
  3963. if param is None:
  3964. return []
  3965. assert isinstance(param, bool)
  3966. if separator:
  3967. return [command_option + separator + (true_value if param else false_value)]
  3968. return [command_option, true_value if param else false_value]
  3969. def cli_valueless_option(params, command_option, param, expected_value=True):
  3970. param = params.get(param)
  3971. return [command_option] if param == expected_value else []
  3972. def cli_configuration_args(params, param, default=[]):
  3973. ex_args = params.get(param)
  3974. if ex_args is None:
  3975. return default
  3976. assert isinstance(ex_args, list)
  3977. return ex_args
  3978. class ISO639Utils(object):
  3979. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  3980. _lang_map = {
  3981. 'aa': 'aar',
  3982. 'ab': 'abk',
  3983. 'ae': 'ave',
  3984. 'af': 'afr',
  3985. 'ak': 'aka',
  3986. 'am': 'amh',
  3987. 'an': 'arg',
  3988. 'ar': 'ara',
  3989. 'as': 'asm',
  3990. 'av': 'ava',
  3991. 'ay': 'aym',
  3992. 'az': 'aze',
  3993. 'ba': 'bak',
  3994. 'be': 'bel',
  3995. 'bg': 'bul',
  3996. 'bh': 'bih',
  3997. 'bi': 'bis',
  3998. 'bm': 'bam',
  3999. 'bn': 'ben',
  4000. 'bo': 'bod',
  4001. 'br': 'bre',
  4002. 'bs': 'bos',
  4003. 'ca': 'cat',
  4004. 'ce': 'che',
  4005. 'ch': 'cha',
  4006. 'co': 'cos',
  4007. 'cr': 'cre',
  4008. 'cs': 'ces',
  4009. 'cu': 'chu',
  4010. 'cv': 'chv',
  4011. 'cy': 'cym',
  4012. 'da': 'dan',
  4013. 'de': 'deu',
  4014. 'dv': 'div',
  4015. 'dz': 'dzo',
  4016. 'ee': 'ewe',
  4017. 'el': 'ell',
  4018. 'en': 'eng',
  4019. 'eo': 'epo',
  4020. 'es': 'spa',
  4021. 'et': 'est',
  4022. 'eu': 'eus',
  4023. 'fa': 'fas',
  4024. 'ff': 'ful',
  4025. 'fi': 'fin',
  4026. 'fj': 'fij',
  4027. 'fo': 'fao',
  4028. 'fr': 'fra',
  4029. 'fy': 'fry',
  4030. 'ga': 'gle',
  4031. 'gd': 'gla',
  4032. 'gl': 'glg',
  4033. 'gn': 'grn',
  4034. 'gu': 'guj',
  4035. 'gv': 'glv',
  4036. 'ha': 'hau',
  4037. 'he': 'heb',
  4038. 'iw': 'heb', # Replaced by he in 1989 revision
  4039. 'hi': 'hin',
  4040. 'ho': 'hmo',
  4041. 'hr': 'hrv',
  4042. 'ht': 'hat',
  4043. 'hu': 'hun',
  4044. 'hy': 'hye',
  4045. 'hz': 'her',
  4046. 'ia': 'ina',
  4047. 'id': 'ind',
  4048. 'in': 'ind', # Replaced by id in 1989 revision
  4049. 'ie': 'ile',
  4050. 'ig': 'ibo',
  4051. 'ii': 'iii',
  4052. 'ik': 'ipk',
  4053. 'io': 'ido',
  4054. 'is': 'isl',
  4055. 'it': 'ita',
  4056. 'iu': 'iku',
  4057. 'ja': 'jpn',
  4058. 'jv': 'jav',
  4059. 'ka': 'kat',
  4060. 'kg': 'kon',
  4061. 'ki': 'kik',
  4062. 'kj': 'kua',
  4063. 'kk': 'kaz',
  4064. 'kl': 'kal',
  4065. 'km': 'khm',
  4066. 'kn': 'kan',
  4067. 'ko': 'kor',
  4068. 'kr': 'kau',
  4069. 'ks': 'kas',
  4070. 'ku': 'kur',
  4071. 'kv': 'kom',
  4072. 'kw': 'cor',
  4073. 'ky': 'kir',
  4074. 'la': 'lat',
  4075. 'lb': 'ltz',
  4076. 'lg': 'lug',
  4077. 'li': 'lim',
  4078. 'ln': 'lin',
  4079. 'lo': 'lao',
  4080. 'lt': 'lit',
  4081. 'lu': 'lub',
  4082. 'lv': 'lav',
  4083. 'mg': 'mlg',
  4084. 'mh': 'mah',
  4085. 'mi': 'mri',
  4086. 'mk': 'mkd',
  4087. 'ml': 'mal',
  4088. 'mn': 'mon',
  4089. 'mr': 'mar',
  4090. 'ms': 'msa',
  4091. 'mt': 'mlt',
  4092. 'my': 'mya',
  4093. 'na': 'nau',
  4094. 'nb': 'nob',
  4095. 'nd': 'nde',
  4096. 'ne': 'nep',
  4097. 'ng': 'ndo',
  4098. 'nl': 'nld',
  4099. 'nn': 'nno',
  4100. 'no': 'nor',
  4101. 'nr': 'nbl',
  4102. 'nv': 'nav',
  4103. 'ny': 'nya',
  4104. 'oc': 'oci',
  4105. 'oj': 'oji',
  4106. 'om': 'orm',
  4107. 'or': 'ori',
  4108. 'os': 'oss',
  4109. 'pa': 'pan',
  4110. 'pi': 'pli',
  4111. 'pl': 'pol',
  4112. 'ps': 'pus',
  4113. 'pt': 'por',
  4114. 'qu': 'que',
  4115. 'rm': 'roh',
  4116. 'rn': 'run',
  4117. 'ro': 'ron',
  4118. 'ru': 'rus',
  4119. 'rw': 'kin',
  4120. 'sa': 'san',
  4121. 'sc': 'srd',
  4122. 'sd': 'snd',
  4123. 'se': 'sme',
  4124. 'sg': 'sag',
  4125. 'si': 'sin',
  4126. 'sk': 'slk',
  4127. 'sl': 'slv',
  4128. 'sm': 'smo',
  4129. 'sn': 'sna',
  4130. 'so': 'som',
  4131. 'sq': 'sqi',
  4132. 'sr': 'srp',
  4133. 'ss': 'ssw',
  4134. 'st': 'sot',
  4135. 'su': 'sun',
  4136. 'sv': 'swe',
  4137. 'sw': 'swa',
  4138. 'ta': 'tam',
  4139. 'te': 'tel',
  4140. 'tg': 'tgk',
  4141. 'th': 'tha',
  4142. 'ti': 'tir',
  4143. 'tk': 'tuk',
  4144. 'tl': 'tgl',
  4145. 'tn': 'tsn',
  4146. 'to': 'ton',
  4147. 'tr': 'tur',
  4148. 'ts': 'tso',
  4149. 'tt': 'tat',
  4150. 'tw': 'twi',
  4151. 'ty': 'tah',
  4152. 'ug': 'uig',
  4153. 'uk': 'ukr',
  4154. 'ur': 'urd',
  4155. 'uz': 'uzb',
  4156. 've': 'ven',
  4157. 'vi': 'vie',
  4158. 'vo': 'vol',
  4159. 'wa': 'wln',
  4160. 'wo': 'wol',
  4161. 'xh': 'xho',
  4162. 'yi': 'yid',
  4163. 'ji': 'yid', # Replaced by yi in 1989 revision
  4164. 'yo': 'yor',
  4165. 'za': 'zha',
  4166. 'zh': 'zho',
  4167. 'zu': 'zul',
  4168. }
  4169. @classmethod
  4170. def short2long(cls, code):
  4171. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  4172. return cls._lang_map.get(code[:2])
  4173. @classmethod
  4174. def long2short(cls, code):
  4175. """Convert language code from ISO 639-2/T to ISO 639-1"""
  4176. for short_name, long_name in cls._lang_map.items():
  4177. if long_name == code:
  4178. return short_name
  4179. class ISO3166Utils(object):
  4180. # From http://data.okfn.org/data/core/country-list
  4181. _country_map = {
  4182. 'AF': 'Afghanistan',
  4183. 'AX': 'Åland Islands',
  4184. 'AL': 'Albania',
  4185. 'DZ': 'Algeria',
  4186. 'AS': 'American Samoa',
  4187. 'AD': 'Andorra',
  4188. 'AO': 'Angola',
  4189. 'AI': 'Anguilla',
  4190. 'AQ': 'Antarctica',
  4191. 'AG': 'Antigua and Barbuda',
  4192. 'AR': 'Argentina',
  4193. 'AM': 'Armenia',
  4194. 'AW': 'Aruba',
  4195. 'AU': 'Australia',
  4196. 'AT': 'Austria',
  4197. 'AZ': 'Azerbaijan',
  4198. 'BS': 'Bahamas',
  4199. 'BH': 'Bahrain',
  4200. 'BD': 'Bangladesh',
  4201. 'BB': 'Barbados',
  4202. 'BY': 'Belarus',
  4203. 'BE': 'Belgium',
  4204. 'BZ': 'Belize',
  4205. 'BJ': 'Benin',
  4206. 'BM': 'Bermuda',
  4207. 'BT': 'Bhutan',
  4208. 'BO': 'Bolivia, Plurinational State of',
  4209. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  4210. 'BA': 'Bosnia and Herzegovina',
  4211. 'BW': 'Botswana',
  4212. 'BV': 'Bouvet Island',
  4213. 'BR': 'Brazil',
  4214. 'IO': 'British Indian Ocean Territory',
  4215. 'BN': 'Brunei Darussalam',
  4216. 'BG': 'Bulgaria',
  4217. 'BF': 'Burkina Faso',
  4218. 'BI': 'Burundi',
  4219. 'KH': 'Cambodia',
  4220. 'CM': 'Cameroon',
  4221. 'CA': 'Canada',
  4222. 'CV': 'Cape Verde',
  4223. 'KY': 'Cayman Islands',
  4224. 'CF': 'Central African Republic',
  4225. 'TD': 'Chad',
  4226. 'CL': 'Chile',
  4227. 'CN': 'China',
  4228. 'CX': 'Christmas Island',
  4229. 'CC': 'Cocos (Keeling) Islands',
  4230. 'CO': 'Colombia',
  4231. 'KM': 'Comoros',
  4232. 'CG': 'Congo',
  4233. 'CD': 'Congo, the Democratic Republic of the',
  4234. 'CK': 'Cook Islands',
  4235. 'CR': 'Costa Rica',
  4236. 'CI': 'Côte d\'Ivoire',
  4237. 'HR': 'Croatia',
  4238. 'CU': 'Cuba',
  4239. 'CW': 'Curaçao',
  4240. 'CY': 'Cyprus',
  4241. 'CZ': 'Czech Republic',
  4242. 'DK': 'Denmark',
  4243. 'DJ': 'Djibouti',
  4244. 'DM': 'Dominica',
  4245. 'DO': 'Dominican Republic',
  4246. 'EC': 'Ecuador',
  4247. 'EG': 'Egypt',
  4248. 'SV': 'El Salvador',
  4249. 'GQ': 'Equatorial Guinea',
  4250. 'ER': 'Eritrea',
  4251. 'EE': 'Estonia',
  4252. 'ET': 'Ethiopia',
  4253. 'FK': 'Falkland Islands (Malvinas)',
  4254. 'FO': 'Faroe Islands',
  4255. 'FJ': 'Fiji',
  4256. 'FI': 'Finland',
  4257. 'FR': 'France',
  4258. 'GF': 'French Guiana',
  4259. 'PF': 'French Polynesia',
  4260. 'TF': 'French Southern Territories',
  4261. 'GA': 'Gabon',
  4262. 'GM': 'Gambia',
  4263. 'GE': 'Georgia',
  4264. 'DE': 'Germany',
  4265. 'GH': 'Ghana',
  4266. 'GI': 'Gibraltar',
  4267. 'GR': 'Greece',
  4268. 'GL': 'Greenland',
  4269. 'GD': 'Grenada',
  4270. 'GP': 'Guadeloupe',
  4271. 'GU': 'Guam',
  4272. 'GT': 'Guatemala',
  4273. 'GG': 'Guernsey',
  4274. 'GN': 'Guinea',
  4275. 'GW': 'Guinea-Bissau',
  4276. 'GY': 'Guyana',
  4277. 'HT': 'Haiti',
  4278. 'HM': 'Heard Island and McDonald Islands',
  4279. 'VA': 'Holy See (Vatican City State)',
  4280. 'HN': 'Honduras',
  4281. 'HK': 'Hong Kong',
  4282. 'HU': 'Hungary',
  4283. 'IS': 'Iceland',
  4284. 'IN': 'India',
  4285. 'ID': 'Indonesia',
  4286. 'IR': 'Iran, Islamic Republic of',
  4287. 'IQ': 'Iraq',
  4288. 'IE': 'Ireland',
  4289. 'IM': 'Isle of Man',
  4290. 'IL': 'Israel',
  4291. 'IT': 'Italy',
  4292. 'JM': 'Jamaica',
  4293. 'JP': 'Japan',
  4294. 'JE': 'Jersey',
  4295. 'JO': 'Jordan',
  4296. 'KZ': 'Kazakhstan',
  4297. 'KE': 'Kenya',
  4298. 'KI': 'Kiribati',
  4299. 'KP': 'Korea, Democratic People\'s Republic of',
  4300. 'KR': 'Korea, Republic of',
  4301. 'KW': 'Kuwait',
  4302. 'KG': 'Kyrgyzstan',
  4303. 'LA': 'Lao People\'s Democratic Republic',
  4304. 'LV': 'Latvia',
  4305. 'LB': 'Lebanon',
  4306. 'LS': 'Lesotho',
  4307. 'LR': 'Liberia',
  4308. 'LY': 'Libya',
  4309. 'LI': 'Liechtenstein',
  4310. 'LT': 'Lithuania',
  4311. 'LU': 'Luxembourg',
  4312. 'MO': 'Macao',
  4313. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  4314. 'MG': 'Madagascar',
  4315. 'MW': 'Malawi',
  4316. 'MY': 'Malaysia',
  4317. 'MV': 'Maldives',
  4318. 'ML': 'Mali',
  4319. 'MT': 'Malta',
  4320. 'MH': 'Marshall Islands',
  4321. 'MQ': 'Martinique',
  4322. 'MR': 'Mauritania',
  4323. 'MU': 'Mauritius',
  4324. 'YT': 'Mayotte',
  4325. 'MX': 'Mexico',
  4326. 'FM': 'Micronesia, Federated States of',
  4327. 'MD': 'Moldova, Republic of',
  4328. 'MC': 'Monaco',
  4329. 'MN': 'Mongolia',
  4330. 'ME': 'Montenegro',
  4331. 'MS': 'Montserrat',
  4332. 'MA': 'Morocco',
  4333. 'MZ': 'Mozambique',
  4334. 'MM': 'Myanmar',
  4335. 'NA': 'Namibia',
  4336. 'NR': 'Nauru',
  4337. 'NP': 'Nepal',
  4338. 'NL': 'Netherlands',
  4339. 'NC': 'New Caledonia',
  4340. 'NZ': 'New Zealand',
  4341. 'NI': 'Nicaragua',
  4342. 'NE': 'Niger',
  4343. 'NG': 'Nigeria',
  4344. 'NU': 'Niue',
  4345. 'NF': 'Norfolk Island',
  4346. 'MP': 'Northern Mariana Islands',
  4347. 'NO': 'Norway',
  4348. 'OM': 'Oman',
  4349. 'PK': 'Pakistan',
  4350. 'PW': 'Palau',
  4351. 'PS': 'Palestine, State of',
  4352. 'PA': 'Panama',
  4353. 'PG': 'Papua New Guinea',
  4354. 'PY': 'Paraguay',
  4355. 'PE': 'Peru',
  4356. 'PH': 'Philippines',
  4357. 'PN': 'Pitcairn',
  4358. 'PL': 'Poland',
  4359. 'PT': 'Portugal',
  4360. 'PR': 'Puerto Rico',
  4361. 'QA': 'Qatar',
  4362. 'RE': 'Réunion',
  4363. 'RO': 'Romania',
  4364. 'RU': 'Russian Federation',
  4365. 'RW': 'Rwanda',
  4366. 'BL': 'Saint Barthélemy',
  4367. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  4368. 'KN': 'Saint Kitts and Nevis',
  4369. 'LC': 'Saint Lucia',
  4370. 'MF': 'Saint Martin (French part)',
  4371. 'PM': 'Saint Pierre and Miquelon',
  4372. 'VC': 'Saint Vincent and the Grenadines',
  4373. 'WS': 'Samoa',
  4374. 'SM': 'San Marino',
  4375. 'ST': 'Sao Tome and Principe',
  4376. 'SA': 'Saudi Arabia',
  4377. 'SN': 'Senegal',
  4378. 'RS': 'Serbia',
  4379. 'SC': 'Seychelles',
  4380. 'SL': 'Sierra Leone',
  4381. 'SG': 'Singapore',
  4382. 'SX': 'Sint Maarten (Dutch part)',
  4383. 'SK': 'Slovakia',
  4384. 'SI': 'Slovenia',
  4385. 'SB': 'Solomon Islands',
  4386. 'SO': 'Somalia',
  4387. 'ZA': 'South Africa',
  4388. 'GS': 'South Georgia and the South Sandwich Islands',
  4389. 'SS': 'South Sudan',
  4390. 'ES': 'Spain',
  4391. 'LK': 'Sri Lanka',
  4392. 'SD': 'Sudan',
  4393. 'SR': 'Suriname',
  4394. 'SJ': 'Svalbard and Jan Mayen',
  4395. 'SZ': 'Swaziland',
  4396. 'SE': 'Sweden',
  4397. 'CH': 'Switzerland',
  4398. 'SY': 'Syrian Arab Republic',
  4399. 'TW': 'Taiwan, Province of China',
  4400. 'TJ': 'Tajikistan',
  4401. 'TZ': 'Tanzania, United Republic of',
  4402. 'TH': 'Thailand',
  4403. 'TL': 'Timor-Leste',
  4404. 'TG': 'Togo',
  4405. 'TK': 'Tokelau',
  4406. 'TO': 'Tonga',
  4407. 'TT': 'Trinidad and Tobago',
  4408. 'TN': 'Tunisia',
  4409. 'TR': 'Turkey',
  4410. 'TM': 'Turkmenistan',
  4411. 'TC': 'Turks and Caicos Islands',
  4412. 'TV': 'Tuvalu',
  4413. 'UG': 'Uganda',
  4414. 'UA': 'Ukraine',
  4415. 'AE': 'United Arab Emirates',
  4416. 'GB': 'United Kingdom',
  4417. 'US': 'United States',
  4418. 'UM': 'United States Minor Outlying Islands',
  4419. 'UY': 'Uruguay',
  4420. 'UZ': 'Uzbekistan',
  4421. 'VU': 'Vanuatu',
  4422. 'VE': 'Venezuela, Bolivarian Republic of',
  4423. 'VN': 'Viet Nam',
  4424. 'VG': 'Virgin Islands, British',
  4425. 'VI': 'Virgin Islands, U.S.',
  4426. 'WF': 'Wallis and Futuna',
  4427. 'EH': 'Western Sahara',
  4428. 'YE': 'Yemen',
  4429. 'ZM': 'Zambia',
  4430. 'ZW': 'Zimbabwe',
  4431. }
  4432. @classmethod
  4433. def short2full(cls, code):
  4434. """Convert an ISO 3166-2 country code to the corresponding full name"""
  4435. return cls._country_map.get(code.upper())
  4436. class GeoUtils(object):
  4437. # Major IPv4 address blocks per country
  4438. _country_ip_map = {
  4439. 'AD': '46.172.224.0/19',
  4440. 'AE': '94.200.0.0/13',
  4441. 'AF': '149.54.0.0/17',
  4442. 'AG': '209.59.64.0/18',
  4443. 'AI': '204.14.248.0/21',
  4444. 'AL': '46.99.0.0/16',
  4445. 'AM': '46.70.0.0/15',
  4446. 'AO': '105.168.0.0/13',
  4447. 'AP': '182.50.184.0/21',
  4448. 'AQ': '23.154.160.0/24',
  4449. 'AR': '181.0.0.0/12',
  4450. 'AS': '202.70.112.0/20',
  4451. 'AT': '77.116.0.0/14',
  4452. 'AU': '1.128.0.0/11',
  4453. 'AW': '181.41.0.0/18',
  4454. 'AX': '185.217.4.0/22',
  4455. 'AZ': '5.197.0.0/16',
  4456. 'BA': '31.176.128.0/17',
  4457. 'BB': '65.48.128.0/17',
  4458. 'BD': '114.130.0.0/16',
  4459. 'BE': '57.0.0.0/8',
  4460. 'BF': '102.178.0.0/15',
  4461. 'BG': '95.42.0.0/15',
  4462. 'BH': '37.131.0.0/17',
  4463. 'BI': '154.117.192.0/18',
  4464. 'BJ': '137.255.0.0/16',
  4465. 'BL': '185.212.72.0/23',
  4466. 'BM': '196.12.64.0/18',
  4467. 'BN': '156.31.0.0/16',
  4468. 'BO': '161.56.0.0/16',
  4469. 'BQ': '161.0.80.0/20',
  4470. 'BR': '191.128.0.0/12',
  4471. 'BS': '24.51.64.0/18',
  4472. 'BT': '119.2.96.0/19',
  4473. 'BW': '168.167.0.0/16',
  4474. 'BY': '178.120.0.0/13',
  4475. 'BZ': '179.42.192.0/18',
  4476. 'CA': '99.224.0.0/11',
  4477. 'CD': '41.243.0.0/16',
  4478. 'CF': '197.242.176.0/21',
  4479. 'CG': '160.113.0.0/16',
  4480. 'CH': '85.0.0.0/13',
  4481. 'CI': '102.136.0.0/14',
  4482. 'CK': '202.65.32.0/19',
  4483. 'CL': '152.172.0.0/14',
  4484. 'CM': '102.244.0.0/14',
  4485. 'CN': '36.128.0.0/10',
  4486. 'CO': '181.240.0.0/12',
  4487. 'CR': '201.192.0.0/12',
  4488. 'CU': '152.206.0.0/15',
  4489. 'CV': '165.90.96.0/19',
  4490. 'CW': '190.88.128.0/17',
  4491. 'CY': '31.153.0.0/16',
  4492. 'CZ': '88.100.0.0/14',
  4493. 'DE': '53.0.0.0/8',
  4494. 'DJ': '197.241.0.0/17',
  4495. 'DK': '87.48.0.0/12',
  4496. 'DM': '192.243.48.0/20',
  4497. 'DO': '152.166.0.0/15',
  4498. 'DZ': '41.96.0.0/12',
  4499. 'EC': '186.68.0.0/15',
  4500. 'EE': '90.190.0.0/15',
  4501. 'EG': '156.160.0.0/11',
  4502. 'ER': '196.200.96.0/20',
  4503. 'ES': '88.0.0.0/11',
  4504. 'ET': '196.188.0.0/14',
  4505. 'EU': '2.16.0.0/13',
  4506. 'FI': '91.152.0.0/13',
  4507. 'FJ': '144.120.0.0/16',
  4508. 'FK': '80.73.208.0/21',
  4509. 'FM': '119.252.112.0/20',
  4510. 'FO': '88.85.32.0/19',
  4511. 'FR': '90.0.0.0/9',
  4512. 'GA': '41.158.0.0/15',
  4513. 'GB': '25.0.0.0/8',
  4514. 'GD': '74.122.88.0/21',
  4515. 'GE': '31.146.0.0/16',
  4516. 'GF': '161.22.64.0/18',
  4517. 'GG': '62.68.160.0/19',
  4518. 'GH': '154.160.0.0/12',
  4519. 'GI': '95.164.0.0/16',
  4520. 'GL': '88.83.0.0/19',
  4521. 'GM': '160.182.0.0/15',
  4522. 'GN': '197.149.192.0/18',
  4523. 'GP': '104.250.0.0/19',
  4524. 'GQ': '105.235.224.0/20',
  4525. 'GR': '94.64.0.0/13',
  4526. 'GT': '168.234.0.0/16',
  4527. 'GU': '168.123.0.0/16',
  4528. 'GW': '197.214.80.0/20',
  4529. 'GY': '181.41.64.0/18',
  4530. 'HK': '113.252.0.0/14',
  4531. 'HN': '181.210.0.0/16',
  4532. 'HR': '93.136.0.0/13',
  4533. 'HT': '148.102.128.0/17',
  4534. 'HU': '84.0.0.0/14',
  4535. 'ID': '39.192.0.0/10',
  4536. 'IE': '87.32.0.0/12',
  4537. 'IL': '79.176.0.0/13',
  4538. 'IM': '5.62.80.0/20',
  4539. 'IN': '117.192.0.0/10',
  4540. 'IO': '203.83.48.0/21',
  4541. 'IQ': '37.236.0.0/14',
  4542. 'IR': '2.176.0.0/12',
  4543. 'IS': '82.221.0.0/16',
  4544. 'IT': '79.0.0.0/10',
  4545. 'JE': '87.244.64.0/18',
  4546. 'JM': '72.27.0.0/17',
  4547. 'JO': '176.29.0.0/16',
  4548. 'JP': '133.0.0.0/8',
  4549. 'KE': '105.48.0.0/12',
  4550. 'KG': '158.181.128.0/17',
  4551. 'KH': '36.37.128.0/17',
  4552. 'KI': '103.25.140.0/22',
  4553. 'KM': '197.255.224.0/20',
  4554. 'KN': '198.167.192.0/19',
  4555. 'KP': '175.45.176.0/22',
  4556. 'KR': '175.192.0.0/10',
  4557. 'KW': '37.36.0.0/14',
  4558. 'KY': '64.96.0.0/15',
  4559. 'KZ': '2.72.0.0/13',
  4560. 'LA': '115.84.64.0/18',
  4561. 'LB': '178.135.0.0/16',
  4562. 'LC': '24.92.144.0/20',
  4563. 'LI': '82.117.0.0/19',
  4564. 'LK': '112.134.0.0/15',
  4565. 'LR': '102.183.0.0/16',
  4566. 'LS': '129.232.0.0/17',
  4567. 'LT': '78.56.0.0/13',
  4568. 'LU': '188.42.0.0/16',
  4569. 'LV': '46.109.0.0/16',
  4570. 'LY': '41.252.0.0/14',
  4571. 'MA': '105.128.0.0/11',
  4572. 'MC': '88.209.64.0/18',
  4573. 'MD': '37.246.0.0/16',
  4574. 'ME': '178.175.0.0/17',
  4575. 'MF': '74.112.232.0/21',
  4576. 'MG': '154.126.0.0/17',
  4577. 'MH': '117.103.88.0/21',
  4578. 'MK': '77.28.0.0/15',
  4579. 'ML': '154.118.128.0/18',
  4580. 'MM': '37.111.0.0/17',
  4581. 'MN': '49.0.128.0/17',
  4582. 'MO': '60.246.0.0/16',
  4583. 'MP': '202.88.64.0/20',
  4584. 'MQ': '109.203.224.0/19',
  4585. 'MR': '41.188.64.0/18',
  4586. 'MS': '208.90.112.0/22',
  4587. 'MT': '46.11.0.0/16',
  4588. 'MU': '105.16.0.0/12',
  4589. 'MV': '27.114.128.0/18',
  4590. 'MW': '102.70.0.0/15',
  4591. 'MX': '187.192.0.0/11',
  4592. 'MY': '175.136.0.0/13',
  4593. 'MZ': '197.218.0.0/15',
  4594. 'NA': '41.182.0.0/16',
  4595. 'NC': '101.101.0.0/18',
  4596. 'NE': '197.214.0.0/18',
  4597. 'NF': '203.17.240.0/22',
  4598. 'NG': '105.112.0.0/12',
  4599. 'NI': '186.76.0.0/15',
  4600. 'NL': '145.96.0.0/11',
  4601. 'NO': '84.208.0.0/13',
  4602. 'NP': '36.252.0.0/15',
  4603. 'NR': '203.98.224.0/19',
  4604. 'NU': '49.156.48.0/22',
  4605. 'NZ': '49.224.0.0/14',
  4606. 'OM': '5.36.0.0/15',
  4607. 'PA': '186.72.0.0/15',
  4608. 'PE': '186.160.0.0/14',
  4609. 'PF': '123.50.64.0/18',
  4610. 'PG': '124.240.192.0/19',
  4611. 'PH': '49.144.0.0/13',
  4612. 'PK': '39.32.0.0/11',
  4613. 'PL': '83.0.0.0/11',
  4614. 'PM': '70.36.0.0/20',
  4615. 'PR': '66.50.0.0/16',
  4616. 'PS': '188.161.0.0/16',
  4617. 'PT': '85.240.0.0/13',
  4618. 'PW': '202.124.224.0/20',
  4619. 'PY': '181.120.0.0/14',
  4620. 'QA': '37.210.0.0/15',
  4621. 'RE': '102.35.0.0/16',
  4622. 'RO': '79.112.0.0/13',
  4623. 'RS': '93.86.0.0/15',
  4624. 'RU': '5.136.0.0/13',
  4625. 'RW': '41.186.0.0/16',
  4626. 'SA': '188.48.0.0/13',
  4627. 'SB': '202.1.160.0/19',
  4628. 'SC': '154.192.0.0/11',
  4629. 'SD': '102.120.0.0/13',
  4630. 'SE': '78.64.0.0/12',
  4631. 'SG': '8.128.0.0/10',
  4632. 'SI': '188.196.0.0/14',
  4633. 'SK': '78.98.0.0/15',
  4634. 'SL': '102.143.0.0/17',
  4635. 'SM': '89.186.32.0/19',
  4636. 'SN': '41.82.0.0/15',
  4637. 'SO': '154.115.192.0/18',
  4638. 'SR': '186.179.128.0/17',
  4639. 'SS': '105.235.208.0/21',
  4640. 'ST': '197.159.160.0/19',
  4641. 'SV': '168.243.0.0/16',
  4642. 'SX': '190.102.0.0/20',
  4643. 'SY': '5.0.0.0/16',
  4644. 'SZ': '41.84.224.0/19',
  4645. 'TC': '65.255.48.0/20',
  4646. 'TD': '154.68.128.0/19',
  4647. 'TG': '196.168.0.0/14',
  4648. 'TH': '171.96.0.0/13',
  4649. 'TJ': '85.9.128.0/18',
  4650. 'TK': '27.96.24.0/21',
  4651. 'TL': '180.189.160.0/20',
  4652. 'TM': '95.85.96.0/19',
  4653. 'TN': '197.0.0.0/11',
  4654. 'TO': '175.176.144.0/21',
  4655. 'TR': '78.160.0.0/11',
  4656. 'TT': '186.44.0.0/15',
  4657. 'TV': '202.2.96.0/19',
  4658. 'TW': '120.96.0.0/11',
  4659. 'TZ': '156.156.0.0/14',
  4660. 'UA': '37.52.0.0/14',
  4661. 'UG': '102.80.0.0/13',
  4662. 'US': '6.0.0.0/8',
  4663. 'UY': '167.56.0.0/13',
  4664. 'UZ': '84.54.64.0/18',
  4665. 'VA': '212.77.0.0/19',
  4666. 'VC': '207.191.240.0/21',
  4667. 'VE': '186.88.0.0/13',
  4668. 'VG': '66.81.192.0/20',
  4669. 'VI': '146.226.0.0/16',
  4670. 'VN': '14.160.0.0/11',
  4671. 'VU': '202.80.32.0/20',
  4672. 'WF': '117.20.32.0/21',
  4673. 'WS': '202.4.32.0/19',
  4674. 'YE': '134.35.0.0/16',
  4675. 'YT': '41.242.116.0/22',
  4676. 'ZA': '41.0.0.0/11',
  4677. 'ZM': '102.144.0.0/13',
  4678. 'ZW': '102.177.192.0/18',
  4679. }
  4680. @classmethod
  4681. def random_ipv4(cls, code_or_block):
  4682. if len(code_or_block) == 2:
  4683. block = cls._country_ip_map.get(code_or_block.upper())
  4684. if not block:
  4685. return None
  4686. else:
  4687. block = code_or_block
  4688. addr, preflen = block.split('/')
  4689. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  4690. addr_max = addr_min | (0xffffffff >> int(preflen))
  4691. return compat_str(socket.inet_ntoa(
  4692. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  4693. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  4694. def __init__(self, proxies=None):
  4695. # Set default handlers
  4696. for type in ('http', 'https'):
  4697. setattr(self, '%s_open' % type,
  4698. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  4699. meth(r, proxy, type))
  4700. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  4701. def proxy_open(self, req, proxy, type):
  4702. req_proxy = req.headers.get('Ytdl-request-proxy')
  4703. if req_proxy is not None:
  4704. proxy = req_proxy
  4705. del req.headers['Ytdl-request-proxy']
  4706. if proxy == '__noproxy__':
  4707. return None # No Proxy
  4708. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  4709. req.add_header('Ytdl-socks-proxy', proxy)
  4710. # youtube-dl's http/https handlers do wrapping the socket with socks
  4711. return None
  4712. return compat_urllib_request.ProxyHandler.proxy_open(
  4713. self, req, proxy, type)
  4714. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  4715. # released into Public Domain
  4716. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  4717. def long_to_bytes(n, blocksize=0):
  4718. """long_to_bytes(n:long, blocksize:int) : string
  4719. Convert a long integer to a byte string.
  4720. If optional blocksize is given and greater than zero, pad the front of the
  4721. byte string with binary zeros so that the length is a multiple of
  4722. blocksize.
  4723. """
  4724. # after much testing, this algorithm was deemed to be the fastest
  4725. s = b''
  4726. n = int(n)
  4727. while n > 0:
  4728. s = compat_struct_pack('>I', n & 0xffffffff) + s
  4729. n = n >> 32
  4730. # strip off leading zeros
  4731. for i in range(len(s)):
  4732. if s[i] != b'\000'[0]:
  4733. break
  4734. else:
  4735. # only happens when n == 0
  4736. s = b'\000'
  4737. i = 0
  4738. s = s[i:]
  4739. # add back some pad bytes. this could be done more efficiently w.r.t. the
  4740. # de-padding being done above, but sigh...
  4741. if blocksize > 0 and len(s) % blocksize:
  4742. s = (blocksize - len(s) % blocksize) * b'\000' + s
  4743. return s
  4744. def bytes_to_long(s):
  4745. """bytes_to_long(string) : long
  4746. Convert a byte string to a long integer.
  4747. This is (essentially) the inverse of long_to_bytes().
  4748. """
  4749. acc = 0
  4750. length = len(s)
  4751. if length % 4:
  4752. extra = (4 - length % 4)
  4753. s = b'\000' * extra + s
  4754. length = length + extra
  4755. for i in range(0, length, 4):
  4756. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  4757. return acc
  4758. def ohdave_rsa_encrypt(data, exponent, modulus):
  4759. '''
  4760. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  4761. Input:
  4762. data: data to encrypt, bytes-like object
  4763. exponent, modulus: parameter e and N of RSA algorithm, both integer
  4764. Output: hex string of encrypted data
  4765. Limitation: supports one block encryption only
  4766. '''
  4767. payload = int(binascii.hexlify(data[::-1]), 16)
  4768. encrypted = pow(payload, exponent, modulus)
  4769. return '%x' % encrypted
  4770. def pkcs1pad(data, length):
  4771. """
  4772. Padding input data with PKCS#1 scheme
  4773. @param {int[]} data input data
  4774. @param {int} length target length
  4775. @returns {int[]} padded data
  4776. """
  4777. if len(data) > length - 11:
  4778. raise ValueError('Input data too long for PKCS#1 padding')
  4779. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  4780. return [0, 2] + pseudo_random + [0] + data
  4781. def encode_base_n(num, n, table=None):
  4782. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4783. if not table:
  4784. table = FULL_TABLE[:n]
  4785. if n > len(table):
  4786. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  4787. if num == 0:
  4788. return table[0]
  4789. ret = ''
  4790. while num:
  4791. ret = table[num % n] + ret
  4792. num = num // n
  4793. return ret
  4794. def decode_packed_codes(code):
  4795. mobj = re.search(PACKED_CODES_RE, code)
  4796. obfucasted_code, base, count, symbols = mobj.groups()
  4797. base = int(base)
  4798. count = int(count)
  4799. symbols = symbols.split('|')
  4800. symbol_table = {}
  4801. while count:
  4802. count -= 1
  4803. base_n_count = encode_base_n(count, base)
  4804. symbol_table[base_n_count] = symbols[count] or base_n_count
  4805. return re.sub(
  4806. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  4807. obfucasted_code)
  4808. def caesar(s, alphabet, shift):
  4809. if shift == 0:
  4810. return s
  4811. l = len(alphabet)
  4812. return ''.join(
  4813. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  4814. for c in s)
  4815. def rot47(s):
  4816. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  4817. def parse_m3u8_attributes(attrib):
  4818. info = {}
  4819. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  4820. if val.startswith('"'):
  4821. val = val[1:-1]
  4822. info[key] = val
  4823. return info
  4824. def urshift(val, n):
  4825. return val >> n if val >= 0 else (val + 0x100000000) >> n
  4826. # Based on png2str() written by @gdkchan and improved by @yokrysty
  4827. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  4828. def decode_png(png_data):
  4829. # Reference: https://www.w3.org/TR/PNG/
  4830. header = png_data[8:]
  4831. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  4832. raise IOError('Not a valid PNG file.')
  4833. int_map = {1: '>B', 2: '>H', 4: '>I'}
  4834. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  4835. chunks = []
  4836. while header:
  4837. length = unpack_integer(header[:4])
  4838. header = header[4:]
  4839. chunk_type = header[:4]
  4840. header = header[4:]
  4841. chunk_data = header[:length]
  4842. header = header[length:]
  4843. header = header[4:] # Skip CRC
  4844. chunks.append({
  4845. 'type': chunk_type,
  4846. 'length': length,
  4847. 'data': chunk_data
  4848. })
  4849. ihdr = chunks[0]['data']
  4850. width = unpack_integer(ihdr[:4])
  4851. height = unpack_integer(ihdr[4:8])
  4852. idat = b''
  4853. for chunk in chunks:
  4854. if chunk['type'] == b'IDAT':
  4855. idat += chunk['data']
  4856. if not idat:
  4857. raise IOError('Unable to read PNG data.')
  4858. decompressed_data = bytearray(zlib.decompress(idat))
  4859. stride = width * 3
  4860. pixels = []
  4861. def _get_pixel(idx):
  4862. x = idx % stride
  4863. y = idx // stride
  4864. return pixels[y][x]
  4865. for y in range(height):
  4866. basePos = y * (1 + stride)
  4867. filter_type = decompressed_data[basePos]
  4868. current_row = []
  4869. pixels.append(current_row)
  4870. for x in range(stride):
  4871. color = decompressed_data[1 + basePos + x]
  4872. basex = y * stride + x
  4873. left = 0
  4874. up = 0
  4875. if x > 2:
  4876. left = _get_pixel(basex - 3)
  4877. if y > 0:
  4878. up = _get_pixel(basex - stride)
  4879. if filter_type == 1: # Sub
  4880. color = (color + left) & 0xff
  4881. elif filter_type == 2: # Up
  4882. color = (color + up) & 0xff
  4883. elif filter_type == 3: # Average
  4884. color = (color + ((left + up) >> 1)) & 0xff
  4885. elif filter_type == 4: # Paeth
  4886. a = left
  4887. b = up
  4888. c = 0
  4889. if x > 2 and y > 0:
  4890. c = _get_pixel(basex - stride - 3)
  4891. p = a + b - c
  4892. pa = abs(p - a)
  4893. pb = abs(p - b)
  4894. pc = abs(p - c)
  4895. if pa <= pb and pa <= pc:
  4896. color = (color + a) & 0xff
  4897. elif pb <= pc:
  4898. color = (color + b) & 0xff
  4899. else:
  4900. color = (color + c) & 0xff
  4901. current_row.append(color)
  4902. return width, height, pixels
  4903. def write_xattr(path, key, value):
  4904. # This mess below finds the best xattr tool for the job
  4905. try:
  4906. # try the pyxattr module...
  4907. import xattr
  4908. if hasattr(xattr, 'set'): # pyxattr
  4909. # Unicode arguments are not supported in python-pyxattr until
  4910. # version 0.5.0
  4911. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  4912. pyxattr_required_version = '0.5.0'
  4913. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  4914. # TODO: fallback to CLI tools
  4915. raise XAttrUnavailableError(
  4916. 'python-pyxattr is detected but is too old. '
  4917. 'youtube-dl requires %s or above while your version is %s. '
  4918. 'Falling back to other xattr implementations' % (
  4919. pyxattr_required_version, xattr.__version__))
  4920. setxattr = xattr.set
  4921. else: # xattr
  4922. setxattr = xattr.setxattr
  4923. try:
  4924. setxattr(path, key, value)
  4925. except EnvironmentError as e:
  4926. raise XAttrMetadataError(e.errno, e.strerror)
  4927. except ImportError:
  4928. if compat_os_name == 'nt':
  4929. # Write xattrs to NTFS Alternate Data Streams:
  4930. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  4931. assert ':' not in key
  4932. assert os.path.exists(path)
  4933. ads_fn = path + ':' + key
  4934. try:
  4935. with open(ads_fn, 'wb') as f:
  4936. f.write(value)
  4937. except EnvironmentError as e:
  4938. raise XAttrMetadataError(e.errno, e.strerror)
  4939. else:
  4940. user_has_setfattr = check_executable('setfattr', ['--version'])
  4941. user_has_xattr = check_executable('xattr', ['-h'])
  4942. if user_has_setfattr or user_has_xattr:
  4943. value = value.decode('utf-8')
  4944. if user_has_setfattr:
  4945. executable = 'setfattr'
  4946. opts = ['-n', key, '-v', value]
  4947. elif user_has_xattr:
  4948. executable = 'xattr'
  4949. opts = ['-w', key, value]
  4950. cmd = ([encodeFilename(executable, True)]
  4951. + [encodeArgument(o) for o in opts]
  4952. + [encodeFilename(path, True)])
  4953. try:
  4954. p = subprocess.Popen(
  4955. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  4956. except EnvironmentError as e:
  4957. raise XAttrMetadataError(e.errno, e.strerror)
  4958. stdout, stderr = p.communicate()
  4959. stderr = stderr.decode('utf-8', 'replace')
  4960. if p.returncode != 0:
  4961. raise XAttrMetadataError(p.returncode, stderr)
  4962. else:
  4963. # On Unix, and can't find pyxattr, setfattr, or xattr.
  4964. if sys.platform.startswith('linux'):
  4965. raise XAttrUnavailableError(
  4966. "Couldn't find a tool to set the xattrs. "
  4967. "Install either the python 'pyxattr' or 'xattr' "
  4968. "modules, or the GNU 'attr' package "
  4969. "(which contains the 'setfattr' tool).")
  4970. else:
  4971. raise XAttrUnavailableError(
  4972. "Couldn't find a tool to set the xattrs. "
  4973. "Install either the python 'xattr' module, "
  4974. "or the 'xattr' binary.")
  4975. def random_birthday(year_field, month_field, day_field):
  4976. start_date = datetime.date(1950, 1, 1)
  4977. end_date = datetime.date(1995, 12, 31)
  4978. offset = random.randint(0, (end_date - start_date).days)
  4979. random_date = start_date + datetime.timedelta(offset)
  4980. return {
  4981. year_field: str(random_date.year),
  4982. month_field: str(random_date.month),
  4983. day_field: str(random_date.day),
  4984. }