logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

utils.py (173375B)


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