settings.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. from youtube import util
  2. import ast
  3. import re
  4. import os
  5. import collections
  6. import flask
  7. from flask import request
  8. SETTINGS_INFO = collections.OrderedDict([
  9. ('app_public', {
  10. 'type': bool,
  11. 'default': False,
  12. 'comment': '''Set app public mode, disabled by default''',
  13. 'hidden': True,
  14. 'category': 'network',
  15. }),
  16. ('app_url', {
  17. 'type': str,
  18. 'default': 'http://localhost',
  19. 'comment': '''Set URL of app 'http://localhost' by default''',
  20. 'hidden': True,
  21. 'category': 'network',
  22. }),
  23. ('route_tor', {
  24. 'type': int,
  25. 'default': 0,
  26. 'label': 'Route Tor',
  27. 'comment': '''0 - Off
  28. 1 - On, except video
  29. 2 - On, including video (see warnings)''',
  30. 'options': [
  31. (0, 'Off'),
  32. (1, 'On, except video'),
  33. (2, 'On, including video (see warnings)'),
  34. ],
  35. 'category': 'network',
  36. }),
  37. ('tor_port', {
  38. 'type': int,
  39. 'default': 9050,
  40. 'comment': '',
  41. 'category': 'network',
  42. }),
  43. ('tor_control_port', {
  44. 'type': int,
  45. 'default': 9151,
  46. 'comment': '',
  47. 'category': 'network',
  48. }),
  49. ('port_number', {
  50. 'type': int,
  51. 'default': 9010,
  52. 'comment': '',
  53. 'category': 'network',
  54. }),
  55. ('allow_foreign_addresses', {
  56. 'type': bool,
  57. 'default': False,
  58. 'comment': '''This will allow others to connect to your YT Local instance as a website.
  59. For security reasons, enabling this is not recommended.''',
  60. 'hidden': True,
  61. 'category': 'network',
  62. }),
  63. ('allow_foreign_post_requests', {
  64. 'type': bool,
  65. 'default': False,
  66. 'comment': '''Enables requests from foreign addresses to make post requests.
  67. For security reasons, enabling this is not recommended.''',
  68. 'hidden': True,
  69. 'category': 'network',
  70. }),
  71. ('subtitles_mode', {
  72. 'type': int,
  73. 'default': 0,
  74. 'comment': '''0 - off by default
  75. 1 - only manually created subtitles on by default
  76. 2 - enable even if automatically generated is all that's available''',
  77. 'label': 'Default subtitles mode',
  78. 'options': [
  79. (0, 'Off'),
  80. (1, 'Manually created only'),
  81. (2, 'Automatic if manual unavailable'),
  82. ],
  83. 'category': 'playback',
  84. }),
  85. ('subtitles_language', {
  86. 'type': str,
  87. 'default': 'en',
  88. 'comment': '''ISO 639 language code: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes''',
  89. 'category': 'playback',
  90. }),
  91. ('related_videos_mode', {
  92. 'type': int,
  93. 'default': 1,
  94. 'comment': '''0 - Related videos disabled
  95. 1 - Related videos always shown
  96. 2 - Related videos hidden; shown by clicking a button''',
  97. 'options': [
  98. (0, 'Disabled'),
  99. (1, 'Always shown'),
  100. (2, 'Shown by clicking button'),
  101. ],
  102. 'category': 'interface',
  103. }),
  104. ('comments_mode', {
  105. 'type': int,
  106. 'default': 1,
  107. 'comment': '''0 - Video comments disabled
  108. 1 - Video comments always shown
  109. 2 - Video comments hidden; shown by clicking a button''',
  110. 'options': [
  111. (0, 'Disabled'),
  112. (1, 'Always shown'),
  113. (2, 'Shown by clicking button'),
  114. ],
  115. 'category': 'interface',
  116. }),
  117. ('enable_comment_avatars', {
  118. 'type': bool,
  119. 'default': True,
  120. 'comment': '',
  121. 'category': 'interface',
  122. }),
  123. ('default_comment_sorting', {
  124. 'type': int,
  125. 'default': 0,
  126. 'comment': '''0 to sort by top
  127. 1 to sort by newest''',
  128. 'options': [
  129. (0, 'Top'),
  130. (1, 'Newest'),
  131. ],
  132. }),
  133. ('theater_mode', {
  134. 'type': bool,
  135. 'default': True,
  136. 'comment': '',
  137. 'category': 'interface',
  138. }),
  139. ('autoplay_videos', {
  140. 'type': bool,
  141. 'default': False,
  142. 'comment': '',
  143. 'category': 'playback',
  144. }),
  145. ('default_resolution', {
  146. 'type': int,
  147. 'default': 720,
  148. 'comment': '',
  149. 'options': [
  150. (144, '144p'),
  151. (240, '240p'),
  152. (360, '360p'),
  153. (480, '480p'),
  154. (720, '720p'),
  155. (1080, '1080p'),
  156. (1440, '1440p'),
  157. (2160, '2160p'),
  158. ],
  159. 'category': 'playback',
  160. }),
  161. ('codec_rank_av1', {
  162. 'type': int,
  163. 'default': 1,
  164. 'label': 'AV1 Codec Ranking',
  165. 'comment': '',
  166. 'options': [(1, '#1'), (2, '#2'), (3, '#3')],
  167. 'category': 'playback',
  168. }),
  169. ('codec_rank_vp', {
  170. 'type': int,
  171. 'default': 2,
  172. 'label': 'VP8/VP9 Codec Ranking',
  173. 'comment': '',
  174. 'options': [(1, '#1'), (2, '#2'), (3, '#3')],
  175. 'category': 'playback',
  176. }),
  177. ('codec_rank_h264', {
  178. 'type': int,
  179. 'default': 3,
  180. 'label': 'H.264 Codec Ranking',
  181. 'comment': '',
  182. 'options': [(1, '#1'), (2, '#2'), (3, '#3')],
  183. 'category': 'playback',
  184. 'description': (
  185. 'Which video codecs to prefer. Codecs given the same '
  186. 'ranking will use smaller file size as a tiebreaker.'
  187. )
  188. }),
  189. ('prefer_uni_sources', {
  190. 'label': 'Use integrated sources',
  191. 'type': int,
  192. 'default': 1,
  193. 'comment': '',
  194. 'options': [
  195. (0, 'Prefer not'),
  196. (1, 'Prefer'),
  197. (2, 'Always'),
  198. ],
  199. 'category': 'playback',
  200. 'description': 'If set to Prefer or Always and the default resolution is set to 360p or 720p, uses the unified (integrated) video files which contain audio and video, with buffering managed by the browser. If set to prefer not, uses the separate audio and video files through custom buffer management in av-merge via MediaSource unless they are unavailable.',
  201. }),
  202. ('use_video_player', {
  203. 'type': int,
  204. 'default': 1,
  205. 'comment': '',
  206. 'options': [
  207. (0, 'Native'),
  208. (1, 'Native with hotkeys'),
  209. (2, 'Plyr'),
  210. ],
  211. 'category': 'interface',
  212. }),
  213. ('use_video_download', {
  214. 'type': int,
  215. 'default': 0,
  216. 'comment': '',
  217. 'options': [
  218. (0, 'Disabled'),
  219. (1, 'Enabled'),
  220. ],
  221. 'category': 'interface',
  222. 'comment': '''If enabled, you may incur legal issues with RIAA. Disabled by default.
  223. More info: https://torrentfreak.com/riaa-thwarts-youts-attempt-to-declare-youtube-ripping-legal-221002/
  224. Archive: https://archive.ph/OZQbN''',
  225. }),
  226. ('proxy_images', {
  227. 'label': 'Route images',
  228. 'type': bool,
  229. 'default': True,
  230. 'comment': '',
  231. 'category': 'network',
  232. }),
  233. ('use_comments_js', {
  234. 'label': 'Enable comments.js',
  235. 'type': bool,
  236. 'default': True,
  237. 'comment': '',
  238. 'category': 'interface',
  239. }),
  240. ('use_sponsorblock_js', {
  241. 'label': 'Enable SponsorBlock',
  242. 'type': bool,
  243. 'default': False,
  244. 'comment': '',
  245. 'category': 'playback',
  246. }),
  247. ('theme', {
  248. 'type': int,
  249. 'default': 0,
  250. 'comment': '',
  251. 'options': [
  252. (0, 'Light'),
  253. (1, 'Gray'),
  254. (2, 'Dark'),
  255. ],
  256. 'category': 'interface',
  257. }),
  258. ('font', {
  259. 'type': int,
  260. 'default': 1,
  261. 'comment': '',
  262. 'options': [
  263. (0, 'Browser default'),
  264. (1, 'Liberation Serif'),
  265. (2, 'Arial'),
  266. (3, 'Verdana'),
  267. (4, 'Tahoma'),
  268. ],
  269. 'category': 'interface',
  270. }),
  271. ('embed_page_mode', {
  272. 'type': bool,
  273. 'label': 'Enable embed page',
  274. 'default': True,
  275. 'comment': '',
  276. 'category': 'interface',
  277. }),
  278. ('autocheck_subscriptions', {
  279. 'type': bool,
  280. 'default': 0,
  281. 'comment': '',
  282. }),
  283. ('include_shorts_in_subscriptions', {
  284. 'type': bool,
  285. 'default': 0,
  286. 'comment': '',
  287. }),
  288. ('include_shorts_in_channel', {
  289. 'type': bool,
  290. 'default': 1,
  291. 'comment': '',
  292. }),
  293. ('gather_googlevideo_domains', {
  294. 'type': bool,
  295. 'default': False,
  296. 'comment': '''Developer use to debug 403s''',
  297. 'hidden': True,
  298. }),
  299. ('debugging_save_responses', {
  300. 'type': bool,
  301. 'default': False,
  302. 'comment': '''Save all responses from youtube for debugging''',
  303. 'hidden': True,
  304. }),
  305. ('settings_version', {
  306. 'type': int,
  307. 'default': 5,
  308. 'comment': '''Do not change, remove, or comment out this value, or else your settings may be lost or corrupted''',
  309. 'hidden': True,
  310. }),
  311. ])
  312. program_directory = os.path.dirname(os.path.realpath(__file__))
  313. acceptable_targets = SETTINGS_INFO.keys() | {
  314. 'enable_comments', 'enable_related_videos', 'preferred_video_codec'
  315. }
  316. def comment_string(comment):
  317. result = ''
  318. for line in comment.splitlines():
  319. result += '# ' + line + '\n'
  320. return result
  321. def save_settings(settings_dict):
  322. with open(settings_file_path, 'w', encoding='utf-8') as file:
  323. for setting_name, setting_info in SETTINGS_INFO.items():
  324. file.write(comment_string(setting_info['comment']) + setting_name + ' = ' + repr(settings_dict[setting_name]) + '\n\n')
  325. def add_missing_settings(settings_dict):
  326. result = default_settings()
  327. result.update(settings_dict)
  328. return result
  329. def default_settings():
  330. return {key: setting_info['default'] for key, setting_info in SETTINGS_INFO.items()}
  331. def upgrade_to_2(settings_dict):
  332. '''Upgrade to settings version 2'''
  333. new_settings = settings_dict.copy()
  334. if 'enable_comments' in settings_dict:
  335. new_settings['comments_mode'] = int(settings_dict['enable_comments'])
  336. del new_settings['enable_comments']
  337. if 'enable_related_videos' in settings_dict:
  338. new_settings['related_videos_mode'] = int(settings_dict['enable_related_videos'])
  339. del new_settings['enable_related_videos']
  340. new_settings['settings_version'] = 2
  341. return new_settings
  342. def upgrade_to_3(settings_dict):
  343. new_settings = settings_dict.copy()
  344. if 'route_tor' in settings_dict:
  345. new_settings['route_tor'] = int(settings_dict['route_tor'])
  346. new_settings['settings_version'] = 3
  347. return new_settings
  348. def upgrade_to_4(settings_dict):
  349. new_settings = settings_dict.copy()
  350. if 'preferred_video_codec' in settings_dict:
  351. pref = settings_dict['preferred_video_codec']
  352. if pref == 0:
  353. new_settings['codec_rank_h264'] = 1
  354. new_settings['codec_rank_vp'] = 2
  355. new_settings['codec_rank_av1'] = 3
  356. else:
  357. new_settings['codec_rank_h264'] = 3
  358. new_settings['codec_rank_vp'] = 2
  359. new_settings['codec_rank_av1'] = 1
  360. del new_settings['preferred_video_codec']
  361. new_settings['settings_version'] = 4
  362. return new_settings
  363. def upgrade_to_5(settings_dict):
  364. new_settings = settings_dict.copy()
  365. if 'prefer_uni_sources' in settings_dict:
  366. new_settings['prefer_uni_sources'] = int(settings_dict['prefer_uni_sources'])
  367. new_settings['settings_version'] = 5
  368. return new_settings
  369. upgrade_functions = {
  370. 1: upgrade_to_2,
  371. 2: upgrade_to_3,
  372. 3: upgrade_to_4,
  373. 4: upgrade_to_5,
  374. }
  375. def log_ignored_line(line_number, message):
  376. print("WARNING: Ignoring settings.txt line " + str(node.lineno) + " (" + message + ")")
  377. if os.path.isfile("settings.txt"):
  378. print("Running in portable mode")
  379. settings_dir = os.path.normpath('./')
  380. data_dir = os.path.normpath('./data')
  381. else:
  382. print("Running in non-portable mode")
  383. settings_dir = os.path.expanduser(os.path.normpath("~/.yt-local"))
  384. data_dir = os.path.expanduser(os.path.normpath("~/.yt-local/data"))
  385. if not os.path.exists(settings_dir):
  386. os.makedirs(settings_dir)
  387. settings_file_path = os.path.join(settings_dir, 'settings.txt')
  388. try:
  389. with open(settings_file_path, 'r', encoding='utf-8') as file:
  390. settings_text = file.read()
  391. except FileNotFoundError:
  392. current_settings_dict = default_settings()
  393. save_settings(current_settings_dict)
  394. else:
  395. if re.fullmatch(r'\s*', settings_text): # blank file
  396. current_settings_dict = default_settings()
  397. save_settings(current_settings_dict)
  398. else:
  399. # parse settings in a safe way, without exec
  400. current_settings_dict = {}
  401. attributes = {
  402. ast.Constant: 'value',
  403. ast.NameConstant: 'value',
  404. ast.Num: 'n',
  405. ast.Str: 's',
  406. }
  407. module_node = ast.parse(settings_text)
  408. for node in module_node.body:
  409. if type(node) != ast.Assign:
  410. log_ignored_line(node.lineno, "only assignments are allowed")
  411. continue
  412. if len(node.targets) > 1:
  413. log_ignored_line(node.lineno, "only simple single-variable assignments allowed")
  414. continue
  415. target = node.targets[0]
  416. if type(target) != ast.Name:
  417. log_ignored_line(node.lineno, "only simple single-variable assignments allowed")
  418. continue
  419. if target.id not in acceptable_targets:
  420. log_ignored_line(node.lineno, target.id + " is not a valid setting")
  421. continue
  422. if type(node.value) not in attributes:
  423. log_ignored_line(node.lineno, "only literals allowed for values")
  424. continue
  425. current_settings_dict[target.id] = node.value.__getattribute__(attributes[type(node.value)])
  426. # upgrades
  427. latest_version = SETTINGS_INFO['settings_version']['default']
  428. while current_settings_dict.get('settings_version', 1) < latest_version:
  429. current_version = current_settings_dict.get('settings_version', 1)
  430. print('Upgrading settings.txt to version', current_version+1)
  431. upgrade_func = upgrade_functions[current_version]
  432. # Must add missing settings here rather than below because
  433. # save_settings needs all settings to be present
  434. current_settings_dict = add_missing_settings(
  435. upgrade_func(current_settings_dict))
  436. save_settings(current_settings_dict)
  437. # some settings not in the file, add those missing settings to the file
  438. if not current_settings_dict.keys() >= SETTINGS_INFO.keys():
  439. print('Adding missing settings to settings.txt')
  440. current_settings_dict = add_missing_settings(current_settings_dict)
  441. save_settings(current_settings_dict)
  442. globals().update(current_settings_dict)
  443. if route_tor:
  444. print("Tor routing is ON")
  445. else:
  446. print("Tor routing is OFF - your YouTube activity is NOT anonymous")
  447. hooks = {}
  448. def add_setting_changed_hook(setting, func):
  449. '''Called right after new settings take effect'''
  450. if setting in hooks:
  451. hooks[setting].append(func)
  452. else:
  453. hooks[setting] = [func]
  454. def set_img_prefix(old_value=None, value=None):
  455. global img_prefix
  456. if value is None:
  457. value = proxy_images
  458. if value:
  459. img_prefix = '/'
  460. else:
  461. img_prefix = ''
  462. set_img_prefix()
  463. add_setting_changed_hook('proxy_images', set_img_prefix)
  464. categories = ['network', 'interface', 'playback', 'other']
  465. def settings_page():
  466. if request.method == 'GET':
  467. settings_by_category = {categ: [] for categ in categories}
  468. for setting_name, setting_info in SETTINGS_INFO.items():
  469. categ = setting_info.get('category', 'other')
  470. settings_by_category[categ].append(
  471. (setting_name, setting_info, current_settings_dict[setting_name])
  472. )
  473. return flask.render_template(
  474. 'settings.html',
  475. categories=categories,
  476. settings_by_category=settings_by_category,
  477. )
  478. elif request.method == 'POST':
  479. for key, value in request.values.items():
  480. if key in SETTINGS_INFO:
  481. if SETTINGS_INFO[key]['type'] is bool and value == 'on':
  482. current_settings_dict[key] = True
  483. else:
  484. current_settings_dict[key] = SETTINGS_INFO[key]['type'](value)
  485. else:
  486. flask.abort(400)
  487. # need this bullshit because browsers don't send anything when an input is unchecked
  488. expected_inputs = {setting_name for setting_name, setting_info in SETTINGS_INFO.items() if not SETTINGS_INFO[setting_name].get('hidden', False)}
  489. missing_inputs = expected_inputs - set(request.values.keys())
  490. for setting_name in missing_inputs:
  491. assert SETTINGS_INFO[setting_name]['type'] is bool, missing_inputs
  492. current_settings_dict[setting_name] = False
  493. # find settings that have changed to prepare setting hook calls
  494. to_call = []
  495. for setting_name, value in current_settings_dict.items():
  496. old_value = globals()[setting_name]
  497. if value != old_value and setting_name in hooks:
  498. for func in hooks[setting_name]:
  499. to_call.append((func, old_value, value))
  500. globals().update(current_settings_dict)
  501. save_settings(current_settings_dict)
  502. # call setting hooks
  503. for func, old_value, value in to_call:
  504. func(old_value, value)
  505. return flask.redirect(util.URL_ORIGIN + '/settings', 303)
  506. else:
  507. flask.abort(400)