-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTagArtisan_Lite.py
4960 lines (4127 loc) · 199 KB
/
TagArtisan_Lite.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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#TagArtisan
"""
TagArtisan Lite - Simple File Tagging Solution
Version: 1.0.0.0
Developed by: NTTech Studio
Copyright © 2025 NTTech Studio. All rights reserved.
Package Identity Name: NTTechStudio.TagArtisanLite
Publisher: CN=9327792A-5810-46DE-9C59-E902D755EB6F
License: MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import json
import shutil
import sys
import os
from datetime import datetime
import tkinter as tk
from tkinter import ttk, filedialog, Toplevel, StringVar
import ttkbootstrap as tb
from ttkbootstrap.constants import *
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import threading
import locale
from languages import LANGUAGES, LANGUAGE_NAMES
import ctypes
from ctypes import windll
import queue
from tkinterdnd2 import DND_FILES, TkinterDnD
import logging
import tempfile
from packaging import version
import traceback
import itertools
import tkinter.colorchooser as colorchooser
from TagDropWindow import TagDropWindow
import random
from ctypes import windll, wintypes
def get_app_data_dir():
"""获取应用数据目录"""
try:
# 获取 AppData\Roaming 目录
roaming = os.path.join(os.getenv('APPDATA'), 'TagArtisan Lite')
# 确保目录存在
os.makedirs(roaming, exist_ok=True)
return roaming
except Exception as e:
# 如果出现错误,返回当前目录
print(f"Error creating app data directory: {e}")
return os.getcwd()
# 設置日誌
if not getattr(sys, 'frozen', False):
log_path = os.path.join(get_app_data_dir(), 'TagArtisan Lite.log')
# 清除旧的日志文件
if os.path.exists(log_path):
try:
os.remove(log_path)
except:
pass
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_path, encoding='utf-8'),
logging.StreamHandler()
]
)
else:
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.NullHandler()
]
)
logger = logging.getLogger('TagArtisan')
class AutoUpdater:
def __init__(self, current_version, app_instance=None):
self.current_version = current_version
self.app_instance = app_instance
# 修改為你的 GitHub 倉庫地址
self.update_url = "https://api.github.com/repos/naveedtsai/EasyTag_Lite/releases/latest"
self.temp_dir = tempfile.gettempdir()
def check_for_updates(self):
try:
logger.info(f"Checking for updates, current version: {self.current_version}")
response = requests.get(self.update_url)
logger.info(f"Update check response status code: {response.status_code}")
if response.status_code == 200:
latest_release = response.json()
latest_version = latest_release['tag_name'].lstrip('v')
logger.info(f"Found latest version: {latest_version}")
if version.parse(latest_version) > version.parse(self.current_version):
logger.info("Found new version, preparing update")
return latest_version, latest_release['assets'][0]['browser_download_url']
else:
logger.info("Current version is up to date")
return None, None
except Exception as e:
logger.error(f"Error occurred while checking for updates: {str(e)}")
return None, None
def download_update(self, download_url):
try:
logger.info(f"Start downloading update: {download_url}")
response = requests.get(download_url, stream=True)
if response.status_code == 200:
update_file = os.path.join(self.temp_dir, "EasyTag_update.msix")
with open(update_file, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
logger.info(f"Update file downloaded to: {update_file}")
return update_file
logger.error(f"Download update failed, status code: {response.status_code}")
return None
except Exception as e:
logger.error(f"Error occurred while downloading update: {str(e)}")
return None
def install_update(self, update_file):
try:
return True
except Exception as e:
logger.error(f"Error occurred while installing update: {str(e)}")
return False
def check_and_update(self):
latest_version, download_url = self.check_for_updates()
if latest_version and self.app_instance:
# 詢問用戶是否要更新
if CustomMessageBox.show_question(
self.app_instance,
self.app_instance.get_text("update_available"),
self.app_instance.get_text("update_prompt").format(version=latest_version)
):
update_file = self.download_update(download_url)
if update_file:
if self.install_update(update_file):
CustomMessageBox.show_info(
self.app_instance,
self.app_instance.get_text("success"),
self.app_instance.get_text("update_success")
)
self.app_instance.destroy()
else:
CustomMessageBox.show_error(
self.app_instance,
self.app_instance.get_text("error"),
self.app_instance.get_text("update_failed")
)
class CrashReporter:
def __init__(self):
pass
def report_crash(self, error_info):
"""報告崩潰信息"""
try:
logger.error(f"Application crashed: {error_info}")
except Exception as e:
logger.error(f"Error reporting crash: {str(e)}")
# 自訂的對話框類
class CustomMessageBox:
def __init__(self, parent, title, message, style="info", width=400, height=200):
self.parent = parent
self.result = None
self.window = Toplevel(parent)
self.window.title(title)
self.window.geometry(f"{width}x{height}")
self.window.resizable(False, False)
self.window.transient(parent)
self.window.grab_set()
self.window.withdraw() # 暫時隱藏窗口
# 信息標籤
label = tb.Label(self.window, text=message, wraplength=width-20, bootstyle=style)
label.pack(pady=20, padx=10, expand=True)
# 按鈕框架
button_frame = tb.Frame(self.window)
button_frame.pack(pady=10)
# 按鈕根據樣式不同而不同
if style in ["info", "warning", "error"]:
btn_text = parent.get_text("confirm") if hasattr(parent, 'get_text') else "確定"
btn_style = {
"info": "success",
"warning": "warning",
"error": "danger"
}.get(style, "info")
btn = tb.Button(button_frame, text=btn_text, command=self.ok, bootstyle=btn_style)
btn.pack()
elif style == "question":
yes_text = parent.get_text("yes") if hasattr(parent, 'get_text') else "是"
no_text = parent.get_text("no") if hasattr(parent, 'get_text') else "否"
btn_yes = tb.Button(button_frame, text=yes_text, command=self.yes, bootstyle="success")
btn_yes.pack(side=tk.LEFT, padx=10)
btn_no = tb.Button(button_frame, text=no_text, command=self.no, bootstyle="danger")
btn_no.pack(side=tk.RIGHT, padx=10)
self.window.protocol("WM_DELETE_WINDOW", self.no if style == "question" else self.ok)
# 將窗口居中
self.center_window(self.window, width, height, parent)
self.window.deiconify() # 顯示窗口
self.parent.wait_window(self.window)
def center_window(self, window, width, height, parent=None):
if parent:
parent.update_idletasks()
parent_x = parent.winfo_rootx()
parent_y = parent.winfo_rooty()
parent_width = parent.winfo_width()
parent_height = parent.winfo_height()
else:
parent_x = parent_y = 0
parent_width = window.winfo_screenwidth()
parent_height = window.winfo_screenheight()
x = parent_x + (parent_width // 2) - (width // 2)
y = parent_y + (parent_height // 2) - (height // 2)
window.geometry(f"{width}x{height}+{x}+{y}")
def ok(self):
self.result = True
self.window.destroy()
def yes(self):
self.result = True
self.window.destroy()
def no(self):
self.result = False
self.window.destroy()
@staticmethod
def show_info(parent, title, message, width=400, height=200):
return CustomMessageBox(parent, title, message, style="info", width=width, height=height).result
@staticmethod
def show_warning(parent, title, message, width=400, height=200):
return CustomMessageBox(parent, title, message, style="warning", width=width, height=height).result
@staticmethod
def show_error(parent, title, message, width=400, height=200):
return CustomMessageBox(parent, title, message, style="error", width=width, height=height).result
@staticmethod
def show_question(parent, title, message, width=400, height=200):
msg_box = CustomMessageBox(parent, title, message, style="question", width=width, height=height)
return msg_box.result
def create_modal_dialog(parent, title, width, height):
"""
創建一個模態對話框,支援 DPI 縮放。
"""
# 根據 DPI 縮放調整視窗大小
scaled_width = int(width * parent.dpi_factor)
scaled_height = int(height * parent.dpi_factor)
dialog = Toplevel(parent)
dialog.withdraw() # 暫時隱藏
dialog.title(title)
dialog.geometry(f"{scaled_width}x{scaled_height}")
dialog.resizable(False, False)
dialog.transient(parent) # 設置為主視窗的子視窗
dialog.grab_set() # 模態化
# 確保所有幾何信息都已更新
dialog.update_idletasks()
# 將彈出視窗居中於主視窗
parent.center_window(dialog, scaled_width, scaled_height, parent)
dialog.deiconify() # 顯示視窗
return dialog
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, file_manager, callback):
super().__init__()
self.file_manager = file_manager
self.callback = callback
self.last_event_time = 0
self.event_delay = 2 # 增加事件延遲到2秒
self._lock = threading.Lock()
self._pending_events = set() # 用於追蹤待處理的事件
self._event_timer = None
def on_any_event(self, event):
# 忽略 .tmp 檔案和隱藏檔案
if event.src_path.endswith('.tmp') or '/.' in event.src_path:
return
current_time = time.time()
with self._lock:
# 將事件添加到待處理集合
self._pending_events.add(event.src_path)
# 如果已經有計時器在運行,取消它
if self._event_timer:
self._event_timer.cancel()
# 設置新的計時器
self._event_timer = threading.Timer(
2.0, # 2秒後執行
self._process_pending_events
)
self._event_timer.start()
def _process_pending_events(self):
"""處理所有待處理的事件"""
with self._lock:
if self._pending_events:
self._pending_events.clear()
self.callback()
self._event_timer = None
class FileManager:
def __init__(self):
"""初始化檔案管理器"""
self.folder_paths = []
self.files_tags = {}
self.db_data = {}
self.hash_cache = {}
# 获取应用数据目录
self.app_data_dir = get_app_data_dir()
# 设置数据文件路径
self.db_file = os.path.join(self.app_data_dir, 'file_tags.json')
self.backup_dir = os.path.join(self.app_data_dir, 'backups')
self.observers = [] # 初始化observers列表
self.event_handler = None
self.tag_colors = {} # 添加標籤顏色字典
self.tag_color_timestamps = {} # 添加標籤顏色修改時間字典
os.makedirs(self.backup_dir, exist_ok=True)
self.load_db()
self.file_monitor = None
self.monitoring = False
self.default_color = "#2b3e50" # 設置預設顏色為 superhero 主題的背景色
def calculate_file_hash(self, file_path):
"""使用檔案大小和檔案頭尾字節作為檔案的唯一標識"""
try:
# 獲取檔案大小
file_size = os.path.getsize(file_path)
# 如果檔案小於8字節,直接讀取整個檔案內容
if file_size < 8:
with open(file_path, 'rb') as f:
content = f.read()
return f"{file_size}_{content.hex()}"
# 讀取檔案頭尾各4個字節
with open(file_path, 'rb') as f:
head = f.read(4)
f.seek(-4, 2) # 從檔案末尾向前4個字節
tail = f.read(4)
# 生成唯一標識(使用大小和頭尾字節的組合)
file_id = f"{file_size}_{head.hex()}_{tail.hex()}"
# 更新緩存
self.hash_cache[file_path] = file_id
return file_id
except Exception as e:
logger.error(f"計算檔案標識時出錯: {str(e)}")
return None
def clean_cache(self):
"""清理不存在的檔案的緩存"""
for file_path in list(self.hash_cache.keys()):
if not os.path.exists(file_path):
del self.hash_cache[file_path]
def set_folder_paths(self, folder_paths):
"""設置要監控的資料夾路徑,更新檔案列表和雜湊值"""
self.folder_paths = [os.path.abspath(path) for path in folder_paths]
self.files_tags = {}
# 掃描所有資料夾中的檔案
for folder_path in self.folder_paths:
if not os.path.exists(folder_path):
continue
for root, _, files in os.walk(folder_path):
for file in files:
full_path = os.path.abspath(os.path.join(root, file))
file_name = os.path.basename(full_path)
# 檢查資料庫中是否有相同檔名的記錄
name_exists = False
for db_key, info in self.db_data.items():
if info.get("name") == file_name:
name_exists = True
break
# 如果檔案名稱不存在於資料庫中,直接加入檔案列表
if not name_exists:
self.files_tags[full_path] = {
"tags": [],
"note": "",
"hash": None,
"name": file_name
}
continue
current_hash = self.calculate_file_hash(full_path)
if not current_hash:
continue
# 使用檔案名稱和雜湊值組合作為鍵值
current_db_key = f"{file_name}_{current_hash}"
# 檢查是否存在相同檔名但不同雜湊值的紀錄
found_old_record = False
for db_key in list(self.db_data.keys()):
if file_name in db_key and full_path in self.db_data[db_key]["paths"]:
if db_key != current_db_key: # 雜湊值不同
# 從舊紀錄中移除當前路徑
self.db_data[db_key]["paths"].remove(full_path)
# 如果舊紀錄沒有其他路徑且有標籤或備註,則複製到新紀錄
if (not self.db_data[db_key]["paths"] and
(self.db_data[db_key]["tags"] or self.db_data[db_key]["note"])):
# 建立新紀錄,沿用舊紀錄的標籤和備註
self.db_data[current_db_key] = {
"tags": self.db_data[db_key]["tags"].copy(),
"note": self.db_data[db_key]["note"],
"hash": current_hash,
"paths": [full_path],
"name": file_name
}
# 如果舊紀錄沒有其他路徑,可以刪除
del self.db_data[db_key]
else:
# 如果舊紀錄有標籤或備註,建立新紀錄
if self.db_data[db_key]["tags"] or self.db_data[db_key]["note"]:
self.db_data[current_db_key] = {
"tags": self.db_data[db_key]["tags"].copy(),
"note": self.db_data[db_key]["note"],
"hash": current_hash,
"paths": [full_path],
"name": file_name
}
found_old_record = True
break
# 如果沒有找到舊紀錄,則檢查是否有相同雜湊值的紀錄
if not found_old_record:
if current_db_key in self.db_data:
if full_path not in self.db_data[current_db_key]["paths"]:
self.db_data[current_db_key]["paths"].append(full_path)
self.db_data[current_db_key]["hash"] = current_hash
self.db_data[current_db_key]["name"] = file_name
else:
# 建立新記錄
self.db_data[current_db_key] = {
"tags": [],
"note": "",
"hash": current_hash,
"paths": [full_path],
"name": file_name
}
# 更新 files_tags
if current_db_key in self.db_data:
self.files_tags[full_path] = {
"tags": self.db_data[current_db_key]["tags"],
"note": self.db_data[current_db_key]["note"],
"hash": current_hash,
"name": file_name
}
else:
self.files_tags[full_path] = {
"tags": [],
"note": "",
"hash": current_hash,
"name": file_name
}
# 清理沒有標籤和備註的紀錄
for key in list(self.db_data.keys()):
if not self.db_data[key]["tags"] and not self.db_data[key]["note"]:
del self.db_data[key]
# 儲存更新後的資料庫
self.save_db()
# 在最後加入更新監控的程式碼
if hasattr(self, 'event_handler') and self.event_handler:
self.start_monitoring(self.event_handler.callback)
def load_db(self):
"""載入資料庫,包括標籤顏色信息"""
if os.path.exists(self.db_file):
with open(self.db_file, 'r', encoding='utf-8') as file:
data = json.load(file)
if isinstance(data, dict) and 'files' in data:
self.db_data = data['files']
self.tag_colors = data.get('tag_colors', {})
self.tag_color_timestamps = data.get('tag_color_timestamps', {})
else:
# 舊版本格式,只有文件數據
self.db_data = data
self.tag_colors = {}
self.tag_color_timestamps = {}
else:
self.db_data = {}
def merge_subfolder_tags(self):
"""合併子資料夾的標籤資訊到上層資料夾"""
new_data = {}
# 對每個資料夾路徑進行處理
for folder_path in self.db_data.keys():
# 將此資料夾的標籤資訊加入到所有上層資料夾
current_path = folder_path
while True:
parent_path = os.path.dirname(current_path)
# 如果已經到達根目錄或磁碟根目錄,則停止
if parent_path == current_path or not parent_path:
break
# 如果上層資料夾不在資料中,則創建
if parent_path not in new_data:
new_data[parent_path] = {}
# 將當前資料夾的檔案標籤資訊複製到上層資料夾
for file_path, info in self.db_data[folder_path].items():
if file_path not in new_data[parent_path]:
new_data[parent_path][file_path] = info.copy()
current_path = parent_path
# 將新的標籤資合併到原有資料中
self.db_data.update(new_data)
def save_db(self):
"""保存資料庫,包括標籤顏色信息"""
data = {
'files': self.db_data,
'tag_colors': self.tag_colors,
'tag_color_timestamps': self.tag_color_timestamps
}
with open(self.db_file, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4, ensure_ascii=False)
def create_restore_point(self):
"""创建数据文件的备份"""
if os.path.exists(self.db_file):
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
# 只使用文件名而不是完整路径
backup_filename = f'{timestamp}_file_tags.json'
backup_file = os.path.join(self.backup_dir, backup_filename)
shutil.copy2(self.db_file, backup_file)
self.cleanup_restore_points()
def cleanup_restore_points(self):
"""清理还原点,只保留最新的50个"""
backups = []
# 获取所有备份文件并解析其时间
for backup in os.listdir(self.backup_dir):
try:
# 从文件名解析时间 (格式: YYYYMMDD_HHMMSS_file_tags.json)
if not backup.endswith('_file_tags.json'):
continue
date_str = backup[:8] # YYYYMMDD
time_str = backup[9:15] # HHMMSS
backup_time = datetime.strptime(f"{date_str}_{time_str}", "%Y%m%d_%H%M%S")
backups.append((backup, backup_time))
except Exception:
continue # 跳过无法解析时间的文件
# 按时间排序,最新的在前
backups.sort(key=lambda x: x[1], reverse=True)
# 如果备份数量超过50个,删除多余的
if len(backups) > 50:
for backup, _ in backups[50:]: # 保留前50个,删除其余的
try:
os.remove(os.path.join(self.backup_dir, backup))
except Exception:
continue # 如果删除失败,继续处理下一个
def restore_db(self, backup_file):
"""从备份文件恢复数据库"""
# 如果提供的是相对于backup_dir的文件名,构建完整路径
if not os.path.isabs(backup_file):
backup_file = os.path.join(self.backup_dir, backup_file)
if not os.path.exists(backup_file):
raise FileNotFoundError(f"备份文件不存在: {backup_file}")
shutil.copy2(backup_file, self.db_file)
self.load_db()
def get_restore_points(self):
"""获取所有可用的还原点"""
backups = []
if os.path.exists(self.backup_dir):
for backup in os.listdir(self.backup_dir):
if backup.endswith('_file_tags.json'):
backup_path = os.path.join(self.backup_dir, backup)
backups.append(backup)
return sorted(backups, reverse=True) # 按文件名排序,最新的在前
def set_folder_paths(self, folder_paths):
"""設置要監控的資料夾路徑,更新檔案列表和雜湊值"""
self.folder_paths = [os.path.abspath(path) for path in folder_paths]
self.files_tags = {}
# 掃描所有資料夾中的檔案
for folder_path in self.folder_paths:
if not os.path.exists(folder_path):
continue
for root, _, files in os.walk(folder_path):
for file in files:
full_path = os.path.abspath(os.path.join(root, file))
file_name = os.path.basename(full_path)
# 檢查資料庫中是否有相同檔名的記錄
name_exists = False
for db_key, info in self.db_data.items():
if info.get("name") == file_name:
name_exists = True
break
# 如果檔案名稱不存在於資料庫中,直接加入檔案列表
if not name_exists:
self.files_tags[full_path] = {
"tags": [],
"note": "",
"hash": None,
"name": file_name
}
continue
current_hash = self.calculate_file_hash(full_path)
if not current_hash:
continue
# 使用檔案名稱和雜湊值組合作為鍵值
current_db_key = f"{file_name}_{current_hash}"
# 檢查是否存在相同檔名但不同雜湊值的紀錄
found_old_record = False
for db_key in list(self.db_data.keys()):
if file_name in db_key and full_path in self.db_data[db_key]["paths"]:
if db_key != current_db_key: # 雜湊值不同
# 從舊紀錄中移除當前路徑
self.db_data[db_key]["paths"].remove(full_path)
# 如果舊紀錄沒有其他路徑且有標籤或備註,則複製到新紀錄
if (not self.db_data[db_key]["paths"] and
(self.db_data[db_key]["tags"] or self.db_data[db_key]["note"])):
# 建立新紀錄,沿用舊紀錄的標籤和備註
self.db_data[current_db_key] = {
"tags": self.db_data[db_key]["tags"].copy(),
"note": self.db_data[db_key]["note"],
"hash": current_hash,
"paths": [full_path],
"name": file_name
}
# 如果舊紀錄沒有其他路徑,可以刪除
del self.db_data[db_key]
else:
# 如果舊紀錄有標籤或備註,建立新紀錄
if self.db_data[db_key]["tags"] or self.db_data[db_key]["note"]:
self.db_data[current_db_key] = {
"tags": self.db_data[db_key]["tags"].copy(),
"note": self.db_data[db_key]["note"],
"hash": current_hash,
"paths": [full_path],
"name": file_name
}
found_old_record = True
break
# 如果沒有找到舊紀錄,則檢查是否有相同雜湊值的紀錄
if not found_old_record:
if current_db_key in self.db_data:
if full_path not in self.db_data[current_db_key]["paths"]:
self.db_data[current_db_key]["paths"].append(full_path)
self.db_data[current_db_key]["hash"] = current_hash
self.db_data[current_db_key]["name"] = file_name
else:
# 建立新記錄
self.db_data[current_db_key] = {
"tags": [],
"note": "",
"hash": current_hash,
"paths": [full_path],
"name": file_name
}
# 更新 files_tags
if current_db_key in self.db_data:
self.files_tags[full_path] = {
"tags": self.db_data[current_db_key]["tags"],
"note": self.db_data[current_db_key]["note"],
"hash": current_hash,
"name": file_name
}
else:
self.files_tags[full_path] = {
"tags": [],
"note": "",
"hash": current_hash,
"name": file_name
}
# 清理沒有標籤和備註的紀錄
for key in list(self.db_data.keys()):
if not self.db_data[key]["tags"] and not self.db_data[key]["note"]:
del self.db_data[key]
# 儲存更新後的資料庫
self.save_db()
# 在最後加入更新監控的程式碼
if hasattr(self, 'event_handler') and self.event_handler:
self.start_monitoring(self.event_handler.callback)
def refresh_db(self):
"""只清理已刪除的檔案記錄"""
if not self.folder_paths:
return
# 檢查資料庫中的檔案是
for file_path in list(self.db_data.keys()):
if not os.path.exists(file_path):
del self.db_data[file_path]
self.save_db()
def add_tag(self, file_path, tag):
if tag.strip():
file_name = os.path.basename(file_path)
current_hash = self.calculate_file_hash(file_path)
if not current_hash:
return
db_key = f"{file_name}_{current_hash}"
# 確保檔案記錄存在
if file_path not in self.files_tags:
self.files_tags[file_path] = {
"tags": [],
"note": "",
"hash": current_hash,
"name": file_name # 確保記錄檔案名稱
}
# 新增標籤
if tag not in self.files_tags[file_path]["tags"]:
self.files_tags[file_path]["tags"].append(tag)
# 更新資料庫
if db_key not in self.db_data:
self.db_data[db_key] = {
"tags": [tag],
"note": "",
"hash": current_hash,
"paths": [file_path],
"name": file_name # 確保記錄檔案名稱
}
else:
if tag not in self.db_data[db_key]["tags"]:
self.db_data[db_key]["tags"].append(tag)
# 確保雜湊值和檔案名稱是最新的
self.db_data[db_key]["hash"] = current_hash
self.db_data[db_key]["name"] = file_name
self.save_db()
def remove_tag(self, file_path, tag):
file_name = os.path.basename(file_path)
current_hash = self.calculate_file_hash(file_path)
if not current_hash:
return
db_key = f"{file_name}_{current_hash}"
# 從 files_tags 中移除標籤
if file_path in self.files_tags and tag in self.files_tags[file_path]["tags"]:
self.files_tags[file_path]["tags"].remove(tag)
# 從 db_data 中移除標籤
if db_key in self.db_data and tag in self.db_data[db_key]["tags"]:
self.db_data[db_key]["tags"].remove(tag)
# 如果檔案沒有任何標籤和備註,從資料庫中移除
if not self.db_data[db_key]["tags"] and not self.db_data[db_key]["note"]:
del self.db_data[db_key]
self.save_db()
def set_note(self, file_path, note):
if len(note) > 500:
note = note[:500]
file_name = os.path.basename(file_path)
current_hash = self.calculate_file_hash(file_path)
if not current_hash:
return
db_key = f"{file_name}_{current_hash}"
# 確保檔案記錄存在
if file_path not in self.files_tags:
self.files_tags[file_path] = {
"tags": [],
"note": "",
"hash": current_hash,
"name": file_name # 確保記錄檔案名稱
}
# 設置備註
self.files_tags[file_path]["note"] = note
self.files_tags[file_path]["name"] = file_name # 更新檔案名稱
# 更新資料庫
if note or (db_key in self.db_data and self.db_data[db_key]["tags"]):
if db_key not in self.db_data:
self.db_data[db_key] = {
"tags": [],
"note": note,
"hash": current_hash,
"paths": [file_path],
"name": file_name # 確保記錄檔案名稱
}
else:
self.db_data[db_key]["note"] = note
self.db_data[db_key]["name"] = file_name # 更新檔案名稱
elif db_key in self.db_data and not self.db_data[db_key]["tags"]:
# 如果沒有備註也沒有標籤,從資料庫中移除
del self.db_data[db_key]
self.save_db()
def get_note(self, file_path):
file_name = os.path.basename(file_path)
current_hash = self.calculate_file_hash(file_path)
if not current_hash:
return ""
db_key = f"{file_name}_{current_hash}"
return self.db_data.get(db_key, {}).get("note", "")
def search_by_tags(self, tags):
if not tags:
# 返回所有檔案的全路徑,使用字典的副本
return sorted(list(self.files_tags.keys()))
# 將標籤字串分割成列表
tags_list = [tag.strip() for tag in tags.split(',')]
# 使用字典的副本進行遍歷
files_tags_copy = self.files_tags.copy()
# 找出同時包含所有指定標籤的檔案
matching_files = []
for file_path, info in files_tags_copy.items():
file_tags = set(info.get("tags", []))
# 檢查檔案是否包含所有指定的標籤
if all(tag in file_tags for tag in tags_list):
matching_files.append(file_path)
return sorted(matching_files)
def list_untagged_files(self):
"""返回沒有標籤的檔案的全路徑"""
untagged_files = []
# 使用字典的副本進行遍歷
files_tags_copy = self.files_tags.copy()
for file_path, info in files_tags_copy.items():
# 確保 tags 存在且為空列表
tags = info.get("tags", [])
if not tags:
untagged_files.append(file_path)
return sorted(untagged_files)
def get_all_used_tags(self):
all_tags = set()
# 使用字典的副本進行遍歷
files_tags_copy = self.files_tags.copy()
for info in files_tags_copy.values():
all_tags.update(info.get("tags", []))
return sorted(all_tags)
def get_all_file_types(self):
"""返回所有檔案的擴展名,已排序並去重"""
file_types = set()
# 使用字典的副本進行遍歷
files_tags_copy = self.files_tags.copy()
for file_path in files_tags_copy.keys():
_, ext = os.path.splitext(file_path)
if ext:
file_types.add(ext.lower())
return sorted(file_types)
def rename_tag(self, old_tag, new_tag, merge=False):
# 保存旧标签的颜色
old_tag_color = self.get_tag_color(old_tag)
old_tag_color_timestamp = self.get_tag_color_timestamp(old_tag)
if merge:
for file_path, info in self.files_tags.items():
if old_tag in info["tags"]:
index = info["tags"].index(old_tag)
info["tags"][index] = new_tag
if new_tag not in info["tags"]:
self.db_data[file_path]["tags"].append(new_tag)
else:
for file_path, info in self.files_tags.items():
if old_tag in info["tags"]:
index = info["tags"].index(old_tag)
info["tags"][index] = new_tag
# 同步更新 db_data
if file_path in self.db_data:
tags = self.db_data[file_path]["tags"]
if old_tag in tags:
index = tags.index(old_tag)
tags[index] = new_tag
# 如果旧标签有自定义颜色,将其应用到新标签
if old_tag_color != self.default_color:
self.set_tag_color(new_tag, old_tag_color)
# 保持原有的时间戳
if old_tag_color_timestamp:
self.tag_color_timestamps[new_tag] = old_tag_color_timestamp
# 删除旧标签的颜色设置
if old_tag in self.tag_colors:
del self.tag_colors[old_tag]
if old_tag in self.tag_color_timestamps:
del self.tag_color_timestamps[old_tag]
self.save_db()
def delete_tag(self, tag):
"""從所有檔案中刪除指定的標籤"""
# 先從 files_tags 中移除標籤
for file_path, info in self.files_tags.items():
if tag in info["tags"]:
info["tags"].remove(tag)
# 同步更新 db_data
if file_path in self.db_data:
if tag in self.db_data[file_path]["tags"]:
self.db_data[file_path]["tags"].remove(tag)
# 如果檔案沒有任何標籤和備註,從資料庫中移除
if not self.db_data[file_path]["tags"] and not self.db_data[file_path]["note"]:
del self.db_data[file_path]
self.save_db()
# Batch operations
def add_tags_batch(self, filenames, tags):
for filename in filenames:
for tag in tags: