-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxAutoConfig.py
More file actions
355 lines (302 loc) · 11.2 KB
/
Copy pathxAutoConfig.py
File metadata and controls
355 lines (302 loc) · 11.2 KB
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
from phBot import *
from threading import Timer
import QtBind
import shutil
import time
import os
import re
import webbrowser
GITHUB_URL = 'https://github.com/Vette1123'
GITHUB_BTN_STYLE = (
'QPushButton{background:#ffd54a;color:#222;font-weight:bold;'
'border:1px solid #8b6b00;border-radius:6px;padding:2px 10px;}'
'QPushButton:hover{background:#ffe27a;}'
)
def btn_github_clicked():
try:
webbrowser.open(GITHUB_URL)
except Exception:
pass
def _try_style_github(btn):
for fn_name in ('setStyleSheet', 'setStylesheet', 'setStyle'):
fn = getattr(QtBind, fn_name, None)
if callable(fn):
try:
fn(gui, btn, GITHUB_BTN_STYLE)
return
except Exception:
pass
pName = 'xAutoConfig'
pVersion = '2.0.0'
pAuthor = 'JellyBitz, Vette1123 (Gado)'
pUrl = 'https://raw.githubusercontent.com/Vette1123/phbot-plugins/main/xAutoConfig.py'
# GitHub: https://github.com/Vette1123
# ______________________________ Constants ______________________________ #
DATABASE_LOADING_TIME = 90.0
DB3_SIDECARS = ('-shm', '-wal')
# ______________________________ Helpers ______________________________ #
def getConfigFilename():
data = get_character_data()
return data['server'] + "_" + data['name']
def FindFiles(pattern, dir=''):
return [x for x in os.listdir(dir) if re.search(pattern, x)]
def ReplaceFile(newPath, oldPath, message):
shutil.copyfile(newPath, oldPath)
log(message)
def _config_dir():
d = get_config_dir()
if not d.endswith(os.sep) and not d.endswith('/'):
d += os.sep
return d
def list_characters():
"""Return sorted list of '{server}_{name}' identifiers found in Config dir."""
d = _config_dir()
try:
entries = os.listdir(d)
except Exception:
return []
chars = set()
for f in entries:
# main char config: exactly one dot, ends with .json, contains underscore
if not f.lower().endswith('.json'):
continue
base = f[:-5]
if '.' in base:
continue
if base.lower().startswith('default'):
continue
if '_' not in base:
continue
chars.add(base)
return sorted(chars, key=str.lower)
def list_extra_json(char_id):
"""Return list of extra .json filenames for a character (e.g. uniques, named profiles)."""
d = _config_dir()
prefix = char_id + '.'
try:
entries = os.listdir(d)
except Exception:
return []
extras = []
for f in entries:
if not f.lower().endswith('.json'):
continue
if f == char_id + '.json':
continue
if f.startswith(prefix):
extras.append(f)
return sorted(extras, key=str.lower)
# ______________________________ UI ______________________________ #
gui = QtBind.init(__name__, pName)
# ---------- Header ----------
QtBind.createLabel(gui, 'xAutoConfig - Copy Settings Between Characters', 12, 8)
QtBind.createLabel(gui, 'Clones .json settings and the full .db3 item filter (incl. -wal/-shm sidecars) between characters.', 12, 26)
# ---------- LEFT column: source / destination ----------
QtBind.createLabel(gui, 'Source:', 12, 58)
cmbSource = QtBind.createCombobox(gui, 90, 55, 230, 22)
QtBind.createLabel(gui, 'Destination:', 12, 88)
cmbDest = QtBind.createCombobox(gui, 90, 85, 230, 22)
QtBind.createLabel(gui, 'or new name:', 12, 118)
txtNewDest = QtBind.createLineEdit(gui, '', 90, 115, 230, 22)
btnSwap = QtBind.createButton(gui, 'btnSwap_clicked', ' Swap <-> ', 12, 148)
btnRefresh = QtBind.createButton(gui, 'btnRefresh_clicked', ' Refresh ', 170, 148)
# ---------- RIGHT column: what to copy + action ----------
QtBind.createLabel(gui, 'What to copy:', 360, 58)
cbJson = QtBind.createCheckBox(gui, 'noop', 'Main settings (.json)', 360, 80)
cbDb3 = QtBind.createCheckBox(gui, 'noop', 'Item filter database (.db3 + -wal/-shm)', 360, 100)
cbExtra = QtBind.createCheckBox(gui, 'noop', 'Extra .json profiles (uniques, named filters, ...)', 360, 120)
QtBind.setChecked(gui, cbJson, True)
QtBind.setChecked(gui, cbDb3, True)
QtBind.setChecked(gui, cbExtra, False)
btnCopy = QtBind.createButton(gui, 'btnCopy_clicked', ' Copy Settings --> ', 360, 148)
# ---------- Footer: status + hint ----------
lblStatus = QtBind.createLabel(gui, 'Status: ready.' + (' ' * 80), 12, 188)
lblHint = QtBind.createLabel(gui, 'Tip: leave "new name" empty to use the dropdown. Example new name: MyNewAlt or Astyra_MyNewAlt', 12, 210)
btnGithub = QtBind.createButton(gui, 'btn_github_clicked', ' ⭐ (Gado) GitHub ⭐ ', 360, 178)
_try_style_github(btnGithub)
# ______________________________ UI logic ______________________________ #
def noop(*args, **kwargs):
pass
def _set_status(msg):
QtBind.setText(gui, lblStatus, 'Status: ' + msg + (' ' * 4))
def _combo_set_index(combo, idx):
"""QtBind exposes the 'set current index' call under different names across phBot
builds. Try the known variants and silently no-op if none exist."""
for fn_name in ('setIndex', 'setCurrentIndex', 'setSelectedIndex', 'select', 'setCurrent'):
fn = getattr(QtBind, fn_name, None)
if callable(fn):
try:
fn(gui, combo, idx)
return
except Exception:
continue
def _populate_combos(preserve=True):
prev_src = QtBind.text(gui, cmbSource) if preserve else ''
prev_dst = QtBind.text(gui, cmbDest) if preserve else ''
QtBind.clear(gui, cmbSource)
QtBind.clear(gui, cmbDest)
chars = list_characters()
for c in chars:
QtBind.append(gui, cmbSource, c)
QtBind.append(gui, cmbDest, c)
# restore prior selections when possible
def _restore(combo, value, fallback_index):
if value and value in chars:
_combo_set_index(combo, chars.index(value))
elif chars:
_combo_set_index(combo, min(fallback_index, len(chars) - 1))
_restore(cmbSource, prev_src, 0)
_restore(cmbDest, prev_dst, 1 if len(chars) > 1 else 0)
return chars
def btnRefresh_clicked():
chars = _populate_combos(preserve=True)
if chars:
_set_status('found ' + str(len(chars)) + ' character(s).')
else:
_set_status('no character configs found in Config folder.')
def btnSwap_clicked():
a = QtBind.text(gui, cmbSource)
b = QtBind.text(gui, cmbDest)
chars = list_characters()
if a in chars:
_combo_set_index(cmbDest, chars.index(a))
if b in chars:
_combo_set_index(cmbSource, chars.index(b))
_set_status('swapped source and destination.')
def _safe_copy(src_path, dst_path):
shutil.copyfile(src_path, dst_path)
def _remove_if_exists(path):
try:
if os.path.exists(path):
os.remove(path)
except Exception as ex:
log('Plugin: could not remove ' + path + ' - ' + str(ex))
def _resolve_destination(src):
"""Returns destination char-id. Prefers the 'new name' field; falls back to the combo.
A bare name (no underscore) is auto-prefixed with the source's server."""
new_name = QtBind.text(gui, txtNewDest).strip()
if new_name:
# strip any path-unsafe chars
new_name = re.sub(r'[\\/:*?"<>|]+', '', new_name).strip()
if not new_name:
return ''
if '_' not in new_name and '_' in src:
server = src.split('_', 1)[0]
return server + '_' + new_name
return new_name
return QtBind.text(gui, cmbDest).strip()
def btnCopy_clicked():
src = QtBind.text(gui, cmbSource).strip()
dst = _resolve_destination(src)
d = _config_dir()
existing_chars = list_characters()
is_new_char = bool(dst) and dst not in existing_chars
if not src:
_set_status('pick a source character.')
return
if not dst:
_set_status('pick a destination or type a new name.')
return
if src == dst:
_set_status('source and destination are the same.')
return
do_json = QtBind.isChecked(gui, cbJson)
do_db3 = QtBind.isChecked(gui, cbDb3)
do_extra = QtBind.isChecked(gui, cbExtra)
if not (do_json or do_db3 or do_extra):
_set_status('select at least one file type to copy.')
return
copied = 0
errors = 0
# Main .json
if do_json:
s = d + src + '.json'
t = d + dst + '.json'
if os.path.exists(s):
try:
_safe_copy(s, t)
log('Plugin: copied ' + src + '.json -> ' + dst + '.json')
copied += 1
except Exception as ex:
log('Plugin: failed copying main .json - ' + str(ex))
errors += 1
else:
log('Plugin: source main .json missing: ' + s)
errors += 1
# .db3 + WAL sidecars. phBot's filter DB runs in sqlite WAL mode, so the most
# recent edits may live in source.db3-wal rather than the main file. We copy
# all three so the destination opens with the same state. Any dest sidecar
# that doesn't exist on source is removed to avoid a stale WAL replay.
if do_db3:
s = d + src + '.db3'
t = d + dst + '.db3'
if os.path.exists(s):
try:
_safe_copy(s, t)
log('Plugin: copied ' + src + '.db3 -> ' + dst + '.db3')
copied += 1
for suf in DB3_SIDECARS:
ss = s + suf
tt = t + suf
if os.path.exists(ss):
_safe_copy(ss, tt)
log('Plugin: copied ' + src + '.db3' + suf + ' -> ' + dst + '.db3' + suf)
else:
_remove_if_exists(tt)
except Exception as ex:
log('Plugin: failed copying .db3 - ' + str(ex))
errors += 1
else:
log('Plugin: source .db3 missing: ' + s)
errors += 1
# Extra .json profiles
if do_extra:
extras = list_extra_json(src)
if not extras:
log('Plugin: no extra .json profiles found for ' + src)
for fname in extras:
suffix = fname[len(src):] # e.g. ".uniques.json"
t = d + dst + suffix
try:
_safe_copy(d + fname, t)
log('Plugin: copied ' + fname + ' -> ' + dst + suffix)
copied += 1
except Exception as ex:
log('Plugin: failed copying ' + fname + ' - ' + str(ex))
errors += 1
if errors == 0:
_set_status('done. ' + str(copied) + ' file(s) copied ' + src + ' -> ' + dst + '.')
else:
_set_status('done with ' + str(errors) + ' error(s). ' + str(copied) + ' copied. see log.')
# clear new-name field; only refresh dropdowns when a brand-new char was
# created, so existing source/destination selections aren't disturbed.
QtBind.setText(gui, txtNewDest, '')
if is_new_char:
_populate_combos(preserve=True)
# Initial population
_populate_combos(preserve=False)
# ______________________________ Events ______________________________ #
def joined_game():
configDir = get_config_dir()
configFilename = getConfigFilename()
if not os.path.exists(configDir + configFilename + ".json"):
defaultConfigs = FindFiles(r'[Dd]efault\.json|[Dd]efault\.[\s\S]*\.json', configDir)
for cfg in defaultConfigs:
ReplaceFile(configDir + cfg, configDir + configFilename + cfg[7:], 'Plugin: "' + str(cfg) + '" loaded')
defaultFilter = FindFiles(r'[Dd]efault\.db3', configDir)
if not defaultFilter:
_populate_combos(preserve=True)
return
defaultFilter = configDir + defaultFilter[0]
configFilter = configDir + configFilename + ".db3"
if os.path.exists(configFilter):
lastModification = time.time() - os.path.getmtime(configFilter)
if lastModification <= 2:
log("Plugin: Filter created few seconds ago! Default filter will be loaded in " + str(DATABASE_LOADING_TIME) + " seconds...")
Timer(DATABASE_LOADING_TIME, ReplaceFile, [defaultFilter, configFilter, "Plugin: Default filter loaded"]).start()
else:
log("Plugin: Filter not found. Default filter will be loaded in " + str(DATABASE_LOADING_TIME) + " seconds...")
Timer(DATABASE_LOADING_TIME, ReplaceFile, [defaultFilter, configFilter, "Plugin: Default filter loaded"]).start()
# refresh combos so the just-created config shows up
_populate_combos(preserve=True)
log('Plugin: ' + pName + ' v' + pVersion + ' successfully loaded')