forked from nicotine-plus/nicotine-plus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.py
830 lines (711 loc) · 28.7 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# COPYRIGHT (C) 2020-2022 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <[email protected]>
# COPYRIGHT (C) 2016-2018 Mutnick <[email protected]>
# COPYRIGHT (C) 2008-2011 quinox <[email protected]>
# COPYRIGHT (C) 2009 hedonist <[email protected]>
# COPYRIGHT (C) 2007 gallows <[email protected]>
# COPYRIGHT (C) 2006-2009 daelstorm <[email protected]>
# COPYRIGHT (C) 2003-2004 Hyriand <[email protected]>
# COPYRIGHT (C) 2001-2003 Alexander Kanavin
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains configuration classes for Nicotine.
"""
import configparser
import os
import platform
import sys
from ast import literal_eval
from collections import defaultdict
class Config:
"""
This class holds configuration information and provides the
following methods:
need_config() - returns true if configuration information is incomplete
read_config() - reads configuration information from file
write_configuration - writes configuration information to file
The actual configuration information is stored as a two-level dictionary.
First-level keys are config sections, second-level keys are config
parameters.
"""
def __init__(self):
config_dir, self.data_dir = self.get_user_directories()
self.filename = os.path.join(config_dir, "config")
self.version = "3.3.0.dev4"
self.python_version = platform.python_version()
self.gtk_version = ""
self.application_name = "Nicotine+"
self.application_id = "org.nicotine_plus.Nicotine"
self.author = "Nicotine+ Team"
self.copyright = """© 2004–2023 Nicotine+ Contributors
© 2003–2004 Nicotine Contributors
© 2001–2003 PySoulSeek Contributors"""
self.website_url = "https://nicotine-plus.org"
self.privileges_url = "https://www.slsknet.org/qtlogin.php?username=%s"
self.portchecker_url = "https://www.slsknet.org/porttest.php?port=%s"
self.issue_tracker_url = "https://github.com/nicotine-plus/nicotine-plus/issues"
self.translations_url = "https://nicotine-plus.org/doc/TRANSLATIONS"
self.config_loaded = False
self.parser = configparser.ConfigParser(strict=False, interpolation=None)
self.sections = defaultdict(dict)
self.defaults = {}
self.removed_options = {}
@staticmethod
def get_user_directories():
""" Returns a tuple:
- the config directory
- the data directory """
if sys.platform == "win32":
try:
data_dir = os.path.join(os.environ["APPDATA"], "nicotine")
except KeyError:
data_dir, _filename = os.path.split(sys.argv[0])
config_dir = os.path.join(data_dir, "config")
return config_dir, data_dir
home = os.path.expanduser("~")
legacy_dir = os.path.join(home, ".nicotine")
if os.path.isdir(legacy_dir.encode("utf-8")):
return legacy_dir, legacy_dir
def xdg_path(xdg, default):
path = os.environ.get(xdg)
path = path.split(":")[0] if path else default
return os.path.join(path, "nicotine")
config_dir = xdg_path("XDG_CONFIG_HOME", os.path.join(home, ".config"))
data_dir = xdg_path("XDG_DATA_HOME", os.path.join(home, ".local", "share"))
return config_dir, data_dir
def create_config_folder(self):
""" Create the folder for storing the config file in, if the folder
doesn't exist """
path, _filename = os.path.split(self.filename)
if not path:
# Only file name specified, use current folder
return True
from pynicotine.utils import encode_path
path_encoded = encode_path(path)
try:
if not os.path.isdir(path_encoded):
os.makedirs(path_encoded)
except OSError as msg:
from pynicotine.logfacility import log
log.add(_("Can't create directory '%(path)s', reported error: %(error)s"),
{"path": path, "error": msg})
return False
return True
def create_data_folder(self):
""" Create the folder for storing data in (shared files etc.),
if the folder doesn't exist """
from pynicotine.utils import encode_path
data_dir_encoded = encode_path(self.data_dir)
try:
if not os.path.isdir(data_dir_encoded):
os.makedirs(data_dir_encoded)
except OSError as msg:
from pynicotine.logfacility import log
log.add(_("Can't create directory '%(path)s', reported error: %(error)s"),
{"path": self.data_dir, "error": msg})
def load_config(self):
from pynicotine.utils import load_file
log_dir = os.path.join(self.data_dir, "logs")
self.defaults = {
"server": {
"server": ("server.slsknet.org", 2242),
"login": "",
"passw": "",
"interface": "",
"ctcpmsgs": False,
"autosearch": [],
"autoreply": "",
"portrange": (2234, 2239),
"upnp": True,
"upnp_interval": 4,
"auto_connect_startup": True,
"userlist": [],
"banlist": [],
"ignorelist": [],
"ipignorelist": {},
"ipblocklist": {},
"autojoin": ["nicotine"],
"autoaway": 15,
"away": False,
"private_chatrooms": False,
"command_aliases": {}
},
"transfers": {
"incompletedir": os.path.join(self.data_dir, "incomplete"),
"downloaddir": os.path.join(self.data_dir, "downloads"),
"uploaddir": os.path.join(self.data_dir, "received"),
"usernamesubfolders": False,
"shared": [],
"buddyshared": [],
"uploadbandwidth": 50,
"use_upload_speed_limit": "unlimited",
"uploadlimit": 1000,
"uploadlimitalt": 100,
"use_download_speed_limit": "unlimited",
"downloadlimit": 1000,
"downloadlimitalt": 100,
"preferfriends": False,
"useupslots": False,
"uploadslots": 2,
"afterfinish": "",
"afterfolder": "",
"lock": True,
"reverseorder": False,
"fifoqueue": False,
"usecustomban": False,
"limitby": True,
"customban": "Banned, don't bother retrying",
"usecustomgeoblock": False,
"customgeoblock": "Sorry, your country is blocked",
"queuelimit": 10000,
"filelimit": 100,
"buddysharestrustedonly": False,
"friendsnolimits": False,
"groupdownloads": "folder_grouping",
"groupuploads": "folder_grouping",
"geoblock": False,
"geoblockcc": [""],
"remotedownloads": True,
"uploadallowed": 2,
"autoclear_downloads": False,
"autoclear_uploads": False,
"uploadsinsubdirs": True,
"rescanonstartup": True,
"enablefilters": False,
"downloadregexp": "",
"downloadfilters": [
["desktop.ini", 1],
["*.url", 1],
["thumbs.db", 1],
["albumart(_{........-....-....-....-............}_)?(_?(large|small))?\\.jpg", 0]
],
"download_doubleclick": 2,
"upload_doubleclick": 2,
"downloadsexpanded": True,
"uploadsexpanded": True
},
"userbrowse": {
"expand_folders": True
},
"userinfo": {
"descr": "''",
"pic": ""
},
"words": {
"censored": [],
"autoreplaced": {
"teh ": "the ",
"taht ": "that ",
"tihng": "thing",
"youre": "you're",
"jsut": "just",
"thier": "their",
"tihs": "this"
},
"censorfill": "*",
"censorwords": False,
"replacewords": False,
"tab": True,
"cycle": False,
"dropdown": False,
"characters": 3,
"roomnames": False,
"buddies": True,
"roomusers": True,
"commands": True,
"aliases": True,
"onematch": False
},
"logging": {
"debug": False,
"debugmodes": [],
"debuglogsdir": os.path.join(log_dir, "debug"),
"logcollapsed": True,
"transferslogsdir": os.path.join(log_dir, "transfers"),
"rooms_timestamp": "%H:%M:%S",
"private_timestamp": "%Y-%m-%d %H:%M:%S",
"log_timestamp": "%Y-%m-%d %H:%M:%S",
"privatechat": True,
"chatrooms": True,
"transfers": False,
"debug_file_output": False,
"roomlogsdir": os.path.join(log_dir, "rooms"),
"privatelogsdir": os.path.join(log_dir, "private"),
"readroomlogs": True,
"readroomlines": 200,
"readprivatelines": 200,
"rooms": []
},
"privatechat": {
"store": True,
"users": []
},
"columns": {
"file_search": {},
"download": {},
"upload": {},
"user_browse": {},
"buddy_list": {},
"chat_room": {}
},
"searches": {
"expand_searches": True,
"group_searches": "folder_grouping",
"maxresults": 150,
"enable_history": True,
"history": [],
"enablefilters": False,
"filters_visible": False,
"defilter": ["", "", "", "", 0, "", ""],
"filtercc": [],
"filterin": [],
"filterout": [],
"filtersize": [],
"filterbr": [],
"filtertype": [],
"filterlength": [],
"search_results": True,
"max_displayed_results": 1500,
"min_search_chars": 3,
"remove_special_chars": True,
"private_search_results": True
},
"ui": {
"language": "",
"dark_mode": False,
"header_bar": True,
"icontheme": "",
"chatme": "#908e8b",
"chatremote": "",
"chatlocal": "",
"chatcommand": "#908e8b",
"chathilite": "#5288ce",
"urlcolor": "#5288ce",
"useronline": "#16bb5c",
"useraway": "#c9ae13",
"useroffline": "#e04f5e",
"usernamehotspots": True,
"usernamestyle": "bold",
"textbg": "",
"search": "",
"searchq": "GREY",
"inputcolor": "",
"spellcheck": True,
"exitdialog": 1,
"tab_default": "",
"tab_hilite": "#497ec2",
"tab_changed": "#497ec2",
"tab_select_previous": True,
"tabmain": "Top",
"tabrooms": "Top",
"tabprivate": "Top",
"tabinfo": "Top",
"tabbrowse": "Top",
"tabsearch": "Top",
"tab_status_icons": True,
"globalfont": "",
"textviewfont": "",
"chatfont": "",
"tabclosers": True,
"searchfont": "",
"listfont": "",
"browserfont": "",
"transfersfont": "",
"last_tab_id": "",
"modes_visible": {
"search": True,
"downloads": True,
"uploads": True,
"userbrowse": True,
"userinfo": True,
"private": True,
"chatrooms": True,
"interests": True
},
"modes_order": [
"search",
"downloads",
"uploads",
"userbrowse",
"userinfo",
"private",
"userlist",
"chatrooms",
"interests"
],
"buddylistinchatrooms": "tab",
"trayicon": True,
"startup_hidden": False,
"filemanager": "",
"speechenabled": False,
"speechprivate": "User %(user)s told you: %(message)s",
"speechrooms": "In room %(room)s, user %(user)s said: %(message)s",
"speechcommand": "flite -t $",
"width": 800,
"height": 600,
"xposition": -1,
"yposition": -1,
"maximized": True,
"urgencyhint": True,
"file_path_tooltips": True,
"reverse_file_paths": True,
"exact_file_sizes": False
},
"private_rooms": {
"rooms": {}
},
"urls": {
"protocols": {}
},
"interests": {
"likes": [],
"dislikes": []
},
"players": {
"default": "",
"npothercommand": "",
"npplayer": "mpris",
"npformatlist": [],
"npformat": ""
},
"notifications": {
"notification_window_title": True,
"notification_tab_colors": False,
"notification_popup_sound": False,
"notification_popup_file": True,
"notification_popup_folder": True,
"notification_popup_private_message": True,
"notification_popup_chatroom": False,
"notification_popup_chatroom_mention": True,
"notification_popup_wish": True
},
"plugins": {
"enable": True,
"enabled": []
},
"statistics": {
"since_timestamp": 0,
"started_downloads": 0,
"completed_downloads": 0,
"downloaded_size": 0,
"started_uploads": 0,
"completed_uploads": 0,
"uploaded_size": 0
}
}
self.removed_options = {
"transfers": (
"pmqueueddir",
"autoretry_downloads",
"shownotification",
"shownotificationperfolder",
"prioritize",
"sharedownloaddir",
"geopanic",
"enablebuddyshares",
"friendsonly",
"enabletransferbuttons",
"uselimit",
"usealtlimits"
),
"server": (
"lastportstatuscheck",
"serverlist",
"enc",
"fallbackencodings",
"roomencoding",
"userencoding",
"firewalled"
),
"ui": (
"enabletrans",
"mozembed",
"open_in_mozembed",
"tooltips",
"transalpha",
"transfilter",
"transtint",
"soundenabled",
"soundtheme",
"soundcommand",
"tab_colors",
"tab_icons",
"searchoffline",
"chat_hidebuttons",
"tab_reorderable",
"private_search_results",
"private_shares",
"labelmain",
"labelrooms",
"labelprivate",
"labelinfo",
"labelbrowse",
"labelsearch",
"notexists",
"roomlistcollapsed",
"showaway",
"decimalsep"
),
"columns": (
"downloads",
"uploads",
"search",
"search_widths",
"downloads_columns",
"downloads_widths",
"uploads_columns",
"uploads_widths",
"userbrowse",
"userbrowse_widths",
"userlist",
"userlist_widths",
"chatrooms",
"chatrooms_widths",
"download_columns",
"download_widths",
"upload_columns",
"upload_widths",
"filesearch_columns",
"filesearch_widths",
"hideflags"
),
"searches": (
"distrib_timer",
"distrib_ignore",
"reopen_tabs",
"max_stored_results",
"re_filter"
),
"userinfo": (
"descrutf8"
),
"private_rooms": (
"enabled"
),
"logging": (
"logsdir",
"timestamps"
),
"ticker": (
"default",
"rooms",
"hide"
),
"language": (
"language",
"setlanguage"
),
"urls": (
"urlcatching",
"humanizeurls"
),
"notifications": (
"notification_tab_icons"
)
}
self.create_config_folder()
self.create_data_folder()
load_file(self.filename, self.parse_config)
# Update config values from file
self.set_config()
language = self.sections["ui"]["language"]
if language:
from pynicotine.i18n import apply_translations
apply_translations(language)
from pynicotine.logfacility import log
log.init_log_levels()
log.add_debug("Using configuration: %(file)s", {"file": self.filename})
def parse_config(self, filename):
""" Parses the config file """
from pynicotine.utils import encode_path
try:
with open(encode_path(filename), "a+", encoding="utf-8") as file_handle:
file_handle.seek(0)
self.parser.read_file(file_handle)
except UnicodeDecodeError:
self.convert_config()
self.parse_config(filename)
def convert_config(self):
""" Converts the config to utf-8.
Mainly for upgrading Windows build. (22 July, 2020) """
try:
from chardet import detect
except ImportError:
from pynicotine.logfacility import log
log.add("Failed to convert config file to UTF-8. Please install python3-chardet and start "
"the application again.")
sys.exit()
from pynicotine.utils import encode_path
conv_filename = encode_path(f"{self.filename}.conv")
os.replace(self.filename, conv_filename)
with open(conv_filename, "rb") as file_handle:
rawdata = file_handle.read()
from_encoding = detect(rawdata)["encoding"]
with open(conv_filename, encoding=from_encoding) as file_read:
with open(encode_path(self.filename), "w", encoding="utf-8") as file_write:
for line in file_read:
file_write.write(line[:-1] + "\r\n")
os.remove(conv_filename)
def need_config(self):
# Check if we have specified a username or password
if not self.sections["server"]["login"] or not self.sections["server"]["passw"]:
return True
return False
def set_config(self):
""" Set config values parsed from file earlier """
from pynicotine.logfacility import log
for i in self.parser.sections():
for j, val in self.parser.items(i, raw=True):
# Check if config section exists in defaults
if i not in self.defaults and i not in self.removed_options:
log.add_debug("Unknown config section '%s'", i)
# Check if config option exists in defaults
elif (j not in self.defaults.get(i, {}) and j not in self.removed_options.get(i, {})
and i != "plugins" and j != "filter"):
log.add_debug("Unknown config option '%(option)s' in section '%(section)s'",
{"option": j, "section": i})
else:
""" Attempt to get the default value for a config option. If there's no default
value, it's a custom option from a plugin, so no checks are needed. """
try:
default_val = self.defaults[i][j]
except KeyError:
try:
val = literal_eval(val)
except Exception:
pass
self.sections[i][j] = val
continue
""" Check that the value of a config option is of the same type as the default
value. If that's not the case, reset the value. """
try:
if not isinstance(default_val, str):
# Values are always read as strings, evaluate them if they aren't
# supposed to remain as strings
eval_val = literal_eval(val)
else:
eval_val = val
if i != "plugins" and j != "filter":
if (isinstance(eval_val, type(default_val))
or (isinstance(default_val, bool)
and isinstance(eval_val, int) and eval_val in (0, 1))):
# Value is valid
pass
else:
raise TypeError("Invalid config value type detected")
self.sections[i][j] = eval_val
except Exception:
# Value was unexpected, reset option
self.sections[i][j] = default_val
log.add("Config error: Couldn't decode '%s' section '%s' value '%s', value has been reset", (
(i[:120] + "…") if len(i) > 120 else i,
(j[:120] + "…") if len(j) > 120 else j,
(val[:120] + "…") if len(val) > 120 else val
))
# Add any default options not present in the config file
for section, options in self.defaults.items():
if section not in self.sections:
self.sections[section] = {}
for option, value in options.items():
if option in self.sections[section]:
continue
# Migrate download speed limit preference
if option == "use_download_speed_limit" and section == "transfers":
if self.sections[section].get("usealtlimits", False):
use_speed_limit = "alternative"
elif self.sections[section].get("downloadlimit", 0) > 0:
use_speed_limit = "primary"
else:
use_speed_limit = "unlimited"
self.sections[section][option] = use_speed_limit
continue
# Migrate upload speed limit preference
if option == "use_upload_speed_limit" and section == "transfers":
if self.sections[section].get("usealtlimits", False):
use_speed_limit = "alternative"
elif self.sections[section].get("uselimit", False):
use_speed_limit = "primary"
else:
use_speed_limit = "unlimited"
self.sections[section][option] = use_speed_limit
continue
# Set default value
self.sections[section][option] = value
# Convert special download folder share to regular share
if self.sections["transfers"].get("sharedownloaddir", False):
shares = self.sections["transfers"]["shared"]
virtual_name = "Downloaded"
shared_folder = (virtual_name, self.sections["transfers"]["downloaddir"])
if shared_folder not in shares and virtual_name not in (x[0] for x in shares):
shares.append(shared_folder)
# Check if server value is valid
server_addr = self.sections["server"]["server"]
if (len(server_addr) != 2 or not isinstance(server_addr[0], str) or not isinstance(server_addr[1], int)):
self.sections["server"]["server"] = self.defaults["server"]["server"]
# Check if port range value is valid
port_range = self.sections["server"]["portrange"]
if (len(port_range) != 2 or not all(isinstance(i, int) for i in port_range)):
self.sections["server"]["portrange"] = self.defaults["server"]["portrange"]
else:
# Setting the port range in numerical order
self.sections["server"]["portrange"] = (min(port_range), max(port_range))
self.config_loaded = True
def write_config_callback(self, filename):
self.parser.write(filename)
def write_configuration(self):
if not self.config_loaded:
return
# Write new config options to file
for section, options in self.sections.items():
if not self.parser.has_section(section):
self.parser.add_section(section)
for option, value in options.items():
if value is None:
value = ""
self.parser.set(section, option, str(value))
# Remove legacy config options
for section, options in self.removed_options.items():
if not self.parser.has_section(section):
continue
for option in options:
self.parser.remove_option(section, option)
if not self.create_config_folder():
return
from pynicotine.logfacility import log
from pynicotine.utils import write_file_and_backup
write_file_and_backup(self.filename, self.write_config_callback, protect=True)
log.add_debug("Saved configuration: %(file)s", {"file": self.filename})
def write_config_backup(self, filename):
from pynicotine.logfacility import log
from pynicotine.utils import encode_path
if not filename.endswith(".tar.bz2"):
filename += ".tar.bz2"
filename_encoded = encode_path(filename)
try:
if os.path.exists(filename_encoded):
raise FileExistsError(f"File {filename} exists")
import tarfile
with tarfile.open(filename_encoded, "w:bz2") as tar:
if not os.path.exists(filename_encoded):
raise FileNotFoundError("Config file missing")
tar.add(self.filename)
except Exception as error:
log.add(_("Error backing up config: %s"), error)
return
log.add(_("Config backed up to: %s"), filename)
config = Config()