-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_sync.py
More file actions
1680 lines (1447 loc) · 97.1 KB
/
github_sync.py
File metadata and controls
1680 lines (1447 loc) · 97.1 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
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
import logging
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import os
import re
from base64 import b64decode, b64encode
import base64
from github import Github, GithubException
import json
import traceback
from AddFilesWindow import AddFilesWindow
from LoadWindow import LoadWindow
from LoadingWindow import LoadingWindow
from ToolTip import ToolTip
from PIL import Image, ImageDraw, ImageFont, ImageTk
from get_theme import get_system_theme
import sv_ttk
import time
import requests
from requests.exceptions import ReadTimeout
from tkinterdnd2 import DND_FILES, TkinterDnD
import asyncio
import aiohttp
from aiohttp import ClientSession
from http.client import IncompleteRead
import urllib3
import hashlib
import sqlite3
import atexit
import binascii
import certifi
import platform
import urllib.request
import sys
TIMEOUT = 400
# Configure logging - Changed to 'w' mode to overwrite the log file
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - [%(levelname)s] - %(message)s",
handlers=[
logging.FileHandler("app.log", mode='w'), # Log to a file, overwrite each time
logging.StreamHandler() # Log to console
]
)
system = platform.system()
# Define the database file path in the AppData directorysystem = platform.system()
if system == "Windows":
APP_DATA_DIR = os.path.join(os.getenv('APPDATA'), 'CrowdGit')
elif system.lower() in ["darwin","macos"]: # macOS
APP_DATA_DIR = os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', 'CrowdGit')
elif system == "Linux":
APP_DATA_DIR = os.path.join(os.path.expanduser('~'), '.config', 'CrowdGit')
os.makedirs(APP_DATA_DIR, exist_ok=True) # Create the directory if it doesn't exist
DATABASE_FILE = os.path.join(APP_DATA_DIR, "file_metadata.db")
SETTINGS_FILE = os.path.join(APP_DATA_DIR, "saved_settings.json")
class SyncApp:
def __init__(self, root): # Инициализация приложения
self.ready = False
self.root = root
self.root.title("CrowdGit")
self.cancel_flag = False
self.timeout = TIMEOUT
self.base_url = "https://api.github.com" # Ensure base_url is set correctly
# Construct the path to the icon relative to the executable
if getattr(sys, 'frozen', False):
# Running as a bundled executable
base_path = sys._MEIPASS
else:
# Running as a script
base_path = os.path.dirname(os.path.abspath(__file__))
icon_path = os.path.join(base_path, os.path.join('icons', "CrowdGit.png"))
try:
self.root.iconphoto(True, tk.PhotoImage(file=icon_path))
except tk.TclError:
logging.error(f"Icon file not found at {icon_path}.")
except Exception as e:
logging.error(f"An error occurred while setting the icon: {e}")
logging.info("Application started.")
# Смотрим, юзер уже работал с приложением или нет
settings = self.load_settings()
GITHUB_TOKEN = settings.get("token", "")
STUDENT_NAME = settings.get("student", "")
PATH = settings.get("path", os.getcwd())
THEME = settings.get("theme", get_system_theme())
self.folder_structure = settings.get("structure")
self.token_var = tk.StringVar(value=GITHUB_TOKEN if GITHUB_TOKEN else "")
self.path_var = tk.StringVar(value=PATH if PATH else "")
self.path_var.set(PATH)
self.student_var = tk.StringVar(value=STUDENT_NAME if STUDENT_NAME else "")
self.repo_var = tk.StringVar(value="kvdep/CoolSekeleton")
self.base = tk.StringVar(value="FU")
self.progress_running = False
self.all_logs = tk.BooleanVar(value=False)
self.uploaded = tk.IntVar(value=0) # Initialize uploaded counter to 0
self.folder_dict = {
"seminar": "sem",
"lecture": "lec",
"hw": "hw",
"data": "data",
"other": "other",
}
self.buttons = {}
self.create_widgets()
self.create_buttons()
self.grid_layout()
self.create_rotated_button()
self.update_rotated_button_colors()
self.set_theme(THEME) # Применим тему
self.token_var.trace_add(
"write", lambda *args: self.check_token()
) # Добавляем отслеживание изменений токена
self.token_var.set(GITHUB_TOKEN + " ")
self.token_var.set(GITHUB_TOKEN)
# Move the logic that depends on buttons here
if not self.folder_structure:
self.create_folder_structure()
self.save_settings()
logging.info("Folder structure loaded.")
try:
if len(self.folder_structure.items()):
self.buttons["add_files_btn"].grid()
else:
self.buttons["add_files_btn"].grid_remove()
except:
pass
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_rowconfigure(7, weight=1)
self.file_hash_cache = {} # Initialize the file hash cache
self.blob_cache = {} # Initialize the cache
self.session = None
self.create_database()
atexit.register(self.close_database)
self.processed = tk.IntVar(value=0) # Add processed counter
self.ready = True
# Блок внешнего вида
def create_buttons(self):
logging.info("Creating buttons.")
# Создание кнопок
self.buttons["add_files_btn"] = ttk.Button(self.root, text="Добавить файлы", command=self.open_add_files_window)
self.buttons["create_btn"] = ttk.Button(self.root, text="Создать структуру", command=self.run_create_structure)
self.buttons["sync_btn"] = ttk.Button(self.root, text="Синхронизировать", command=self.run_sync)
self.buttons["all_logs_entry"] = ttk.Checkbutton(self.root, text="Все логи", variable=self.all_logs)
self.buttons["save_btn"] = ttk.Button(self.root, text="Сохранить профиль", command=self.save_settings)
self.buttons["create_info"] = ttk.Label(self.root, text="Скачает сюда всю структуру папок с Git. Подпапку не создаст. Не нашли нужную папку?")
self.buttons["uploaded_info"] = ttk.Label(self.root, text="Загружено:")
self.buttons["uploaded_show"] = ttk.Label(self.root, textvariable=self.uploaded)
self.buttons["log_scroll"] = ttk.Scrollbar(self.root, orient="vertical", command=self.log_text.yview)
self.buttons["log_text"] = self.log_text
self.buttons["example_label"] = ttk.Label(self.root, text="Пример верного path: 'FU\\course_2\\semester_4\\nm_Численные Методы\\hw\\nm_hw_4_Kidysyuk.ipynb'")
self.buttons["progress"] = self.progress
self.buttons["add_files_btn"].grid(row=10, column=0, padx=5, pady=5)
self.buttons["about_btn"] = ttk.Button(self.root, text="О программе", command=self.show_about_menu)
self.buttons["about_btn"].grid(row=10, column=3, padx=5, pady=2)
# --- Новая кнопка для открытия окна загрузки ---
self.buttons["load_btn"] = ttk.Button(self.root, text="Загрузить с GitHub", command=self.open_load_window)
self.buttons["load_btn"].grid(row=6, column=1, padx=5, pady=5) # Разместите кнопку где удобно
self.buttons["cancel_btn"] = ttk.Button(self.root, text="Отмена", command=self.cancel_operation)
self.buttons["cancel_btn"].grid(row=8, column=3, padx=5, pady=5) # Добавляем кнопку отмены
self.buttons["cancel_btn"].grid_remove() # Скрываем кнопку по умолчанию
# Add tooltips
ToolTip(
self.buttons["add_files_btn"],
"Открывает окно для добавления файлов в локальную структуру.\n"
"В этом окне вы можете выбрать файлы, указать их тип (домашнее задание, лекция и т.д.),\n"
"а также указать номер задания. После этого файлы будут скопированы в соответствующие папки.",
)
ToolTip(
self.buttons["create_btn"],
"Скачивает структуру папок из репозитория GitHub в указанную локальную директорию.\n"
"Это действие создаст локальные папки, соответствующие структуре репозитория.\n"
"Если папки уже существуют, они не будут перезаписаны.",
)
ToolTip(
self.buttons["sync_btn"],
"Синхронизирует локальные файлы с репозиторием GitHub.\n"
"Проверяет наличие изменений в локальных файлах и загружает их на GitHub.\n"
"Также проверяет наличие новых файлов на GitHub и скачивает их локально.",
)
ToolTip(
self.buttons["all_logs_entry"],
"Включает отображение всех логов, включая информацию о пропущенных файлах.\n"
"Полезно для отладки и проверки, какие файлы не были синхронизированы.",
)
ToolTip(
self.buttons["save_btn"],
"Сохраняет текущие настройки профиля (токен, имя студента).\n"
"Сохраненные настройки будут автоматически загружены при следующем запуске приложения.",
)
ToolTip(
self.buttons["create_info"],
"Информация о том, как работает создание структуры.\n"
"Приложение скачивает структуру папок с GitHub и создает их локально.\n"
"Подпапки не создаются, если их нет в репозитории.",
)
ToolTip(
self.buttons["uploaded_info"],
"Показывает количество файлов, загруженных на GitHub.\n"
"Счетчик обновляется после каждой успешной синхронизации.",
)
ToolTip(
self.buttons["example_label"],
"Показывает пример правильного пути к файлу.\n"
"Файлы должны быть расположены в папках, соответствующих структуре репозитория.\n"
"Имя файла должно соответствовать шаблону: 'abbrev_type_num_student.ext'.",
)
ToolTip(self.token_entry, "Введите ваш персональный токен доступа к GitHub.\n"
"Токен можно сгенерировать в настройках вашего аккаунта GitHub.")
ToolTip(self.path_entry, "Укажите путь к локальной папке, где будет храниться структура.\n"
"Это место, куда будут скачаны файлы с GitHub и куда будут загружаться ваши локальные изменения.")
ToolTip(self.student_entry, "Введите вашу фамилию.\n"
"Это имя будет использоваться в именах файлов при синхронизации.")
ToolTip(self.repo_entry, "Укажите имя репозитория на GitHub в формате 'username/repository'.\n"
"Например: 'kvdep/CoolSekeleton'.")
ToolTip(self.base_entry, "Укажите базовую папку для вашей структуры.\n"
"Например: 'FU'.")
ToolTip(self.log_text, "Здесь отображаются логи работы приложения.\n"
"Вы можете отслеживать процесс синхронизации и создания структуры.")
ToolTip(self.browse_btn, "Нажмите, чтобы выбрать папку для локальной структуры.")
ToolTip(self.progress, "Индикатор выполнения текущей операции.")
ToolTip(
self.buttons["about_btn"],
"Открывает меню с информацией о программе и настройками внешнего вида.",
)
ToolTip(self.buttons["load_btn"],
"Открывает окно для просмотра содержимого репозитория на GitHub и скачивания файлов.\n"
"Поддерживается скачивание обычных файлов и сборка файлов, разделенных на части.")
def load_theme(self):
"""Loads the system theme and applies it to the application."""
system_theme = get_system_theme()
self.set_theme(system_theme)
def show_about_menu(self):
"""Displays the 'About' menu with options for 'Creators' and 'Appearance'."""
about_menu = tk.Menu(self.root, tearoff=0)
about_menu.add_command(label="Создатели", command=self.show_creators)
about_menu.add_command(label="Внешний вид", command=self.show_appearance_options)
# Calculate the position for the menu
x = self.buttons["about_btn"].winfo_rootx()
y = self.buttons["about_btn"].winfo_rooty() + self.buttons["about_btn"].winfo_height()
about_menu.tk_popup(x, y)
def show_creators(self):
"""Displays information about the creators of the application."""
creators_text = (
"Программисты kvdep и ackrome столкнулись с непростой задачей: создать программу, "
"которая должна была стать инновационной, но оставаться простой в использовании. "
"Ночи за кодом, бесконечные дебаты о структуре и неожиданные ошибки стали их рутиной. "
"Каждая строчка кода требовала проверки, а баланс между креативностью и функциональностью "
"казался недостижимым. «Это как собрать пазл вслепую», — шутил ackrome, пока kvdep искал "
"решение очередного бага. Несмотря на трудности, их упорство привело к результату — "
"программа ожила, став символом их совместных усилий и страсти к программированию."
)
creators_window = tk.Toplevel(self.root)
creators_window.title("Создатели")
label = ttk.Label(creators_window, text=creators_text, wraplength=400, justify="left", padding=10)
label.pack()
creators_window.transient(self.root) # Make it a child of the main window
creators_window.grab_set() # Make it modal
def show_appearance_options(self):
"""Displays options for changing the application's appearance."""
appearance_window = tk.Toplevel(self.root)
appearance_window.title("Внешний вид")
# Add theme options here (e.g., light, dark)
ttk.Label(appearance_window, text="Выберите тему:").grid(row=0, column=0, sticky="nsew")
# Example: Add a button to switch to a dark theme
dark_theme_btn = ttk.Button(appearance_window, text="Темная тема", command=lambda: self.set_theme("dark"))
dark_theme_btn.grid(row=1, column=0, sticky='nsew')
# Example: Add a button to switch to a light theme
light_theme_btn = ttk.Button(appearance_window, text="Светлая тема", command=lambda: self.set_theme("light"))
light_theme_btn.grid(row=2, column=0, sticky='nsew')
# Example: Add a button to switch to a light theme
light_theme_btn = ttk.Button(appearance_window, text="Использовать системную", command=lambda: self.load_theme())
light_theme_btn.grid(row=3, column=0, sticky='nsew')
def set_theme(self, theme):
"""Sets the application's theme (light or dark)."""
if theme in ["dark", "light"]:
sv_ttk.set_theme(theme)
self.update_tooltips_theme()
self.update_rotated_button_colors()
self.save_settings() # Сохраним тему
else:
logging.info("Unknown theme")
def update_tooltips_theme(self):
"""Update the theme of all tooltips."""
for widget in self.root.winfo_children():
self.update_tooltip_theme_recursive(widget)
def update_tooltip_theme_recursive(self, widget):
"""Recursively update the theme of tooltips in a widget and its children."""
if isinstance(widget, tk.Canvas):
for item in widget.find_all():
tags = widget.gettags(item)
for tag in tags:
if tag.startswith("tooltip_"):
tooltip_instance = widget.itemcget(item, "tooltip_instance")
if tooltip_instance:
tooltip_instance.update_theme()
for child in widget.winfo_children():
self.update_tooltip_theme_recursive(child)
def set_buttons_visibility(self, visible):
# Set button visibility
for button in self.buttons.values():
if visible:
button.grid()
else:
button.grid_remove()
def create_widgets(self):
logging.info("Creating widgets.")
# Создание виджетов
ttk.Label(self.root, text="GitHub Token:").grid(row=0, column=0, sticky="w")
self.token_entry = ttk.Entry(self.root, textvariable=self.token_var, width=40, show="*", validate="key")
ttk.Label(self.root, text="Локальный путь:").grid(row=1, column=0, sticky="w")
self.path_entry = ttk.Entry(self.root, textvariable=self.path_var, width=35)
self.browse_btn = ttk.Button(self.root, text="Обзор", command=self.select_path)
ttk.Label(self.root, text="Фамилия студента:").grid(row=2, column=0, sticky="w")
self.student_entry = ttk.Entry(self.root, textvariable=self.student_var, width=40)
ttk.Label(self.root, text="Репозиторий:").grid(row=3, column=0, sticky="w")
self.repo_entry = ttk.Entry(self.root, textvariable=self.repo_var, width=40)
ttk.Label(self.root, text="Базовая папка:").grid(row=4, column=0, sticky="w")
self.base_entry = ttk.Entry(self.root, textvariable=self.base, width=40)
self.log_text = tk.Text(height=10, state='disabled')
self.progress = ttk.Progressbar(self.root, mode="indeterminate")
def grid_layout(self):
logging.info("Setting up grid layout.")
# Размещение виджетов
self.token_entry.grid(row=0, column=1, columnspan=2, padx=5, pady=2, sticky="we")
self.path_entry.grid(row=1, column=1, padx=5, pady=2, sticky="we")
self.browse_btn.grid(row=1, column=2, padx=5, pady=2)
self.student_entry.grid(row=2, column=1, columnspan=2, padx=5, pady=2, sticky="we")
self.repo_entry.grid(row=3, column=1, columnspan=2, padx=5, pady=2, sticky="we")
self.base_entry.grid(row=4, column=1, columnspan=2, padx=5, pady=2, sticky="we")
self.buttons["create_info"].grid(row=5, column=1, columnspan=2, padx=5, pady=2, sticky="we")
self.buttons["create_btn"].grid(row=5, column=0, padx=5, pady=5)
self.buttons["sync_btn"].grid(row=6, column=0, padx=5, pady=5)
self.log_text.grid(row=7, column=0, columnspan=3, padx=5, pady=5, sticky="nsew")
self.buttons["log_scroll"].grid(row=7, column=3, sticky="ns")
self.buttons["uploaded_info"].grid(row=6, column=2)
self.buttons["uploaded_show"].grid(row=6, column=3)
self.buttons["progress"].grid(row=8, column=0, columnspan=3, sticky="we", padx=5, pady=5)
self.buttons["example_label"].grid(row=9, column=0, columnspan=3, padx=5, pady=5, sticky="w")
self.buttons["save_btn"].grid(row=3, column=3, padx=5, pady=2)
self.buttons["all_logs_entry"].grid(row=10, column=1, padx=5, pady=2)
self.buttons["add_files_btn"].grid(row=10, column=0, padx=5, pady=5)
# Глупая проверка валидности токена
def check_token(self, *args):
"""Check if the token is valid and show/hide the button accordingly."""
logging.info(f"Checking token validity. Token length: {len(self.token_var.get())}")
if len(self.token_var.get()) == 93:
self.set_buttons_visibility(True)
self.root.update() # Force the window to update its layout
self.root.geometry("") # Resize the window to fit its contents
else:
self.set_buttons_visibility(False)
self.root.update() # Force the window to update its layout
self.root.geometry("") # Resize the window to fit its contents
# Функциональная часть
def create_folder_structure(self):
"""Create local folder structure from GitHub repo"""
logging.info("Starting folder structure creation.")
self.toggle_progress(True) # Включаем прогрессбар
self.buttons['add_files_btn'].grid_remove()
if not self.token_var.get() or not self.repo_var.get():
self.toggle_progress(False)
return
try:
g = Github(self.token_var.get())
repo = g.get_repo(self.repo_var.get())
def get_dirs(repo_path='', local_path=self.path_var.get()): # Рекурсивная функция для обхода папок
if self.cancel_flag:
self.log_message("[INFO] Создание структуры прервано.")
return {} # Выходим из метода, если установлен флаг отмены
contents = repo.get_contents(repo_path)
dct = {}
for item in contents:
if self.cancel_flag:
self.log_message("[INFO] Создание структуры прервано.")
return {} # Выходим из метода, если установлен флаг отмены
if item.type == "dir":
dct[item.name] = get_dirs(item.path, local_path)
dir_path = os.path.join(local_path, item.path)
os.makedirs(dir_path, exist_ok=True)
self.log_message(f"[OK] {repo_path} : folders uploaded {len(dct)}")
return dct
self.folder_structure = get_dirs()
self.save_settings()
self.log_message("[OK] Структура папок создана")
logging.info("Folder structure created successfully.")
except Exception as e:
self.log_message(f"[ОШИБКА] {type(e).__name__} : {str(e)}")
logging.error(f"Error creating folder structure: {e}")
logging.info("Finished folder structure creation.")
self.buttons['add_files_btn'].grid()
self.toggle_progress(False)
def load_settings(self):
"""Loads settings from a JSON file."""
logging.info("Loading settings from file.")
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
settings = json.load(f)
logging.info("Settings loaded successfully.")
return settings
except json.JSONDecodeError as e:
logging.error(f"Error decoding settings file: {e}")
messagebox.showerror("Ошибка загрузки настроек", f"Не удалось прочитать файл настроек: {e}")
return {}
except Exception as e:
logging.error(f"An unexpected error occurred while loading settings: {e}")
messagebox.showerror("Ошибка загрузки настроек", f"Произошла непредвиденная ошибка при загрузке настроек: {e}")
return {}
else:
logging.info("Settings file not found.")
return {}
def save_settings(self, *args):
"""Saves current settings to a JSON file."""
logging.info("Saving settings.")
settings = {
"token": self.token_var.get(),
"student": self.student_var.get(),
"path": str(self.path_var.get()),
"theme": sv_ttk.get_theme(), # Добавим тему
"structure": self.folder_structure
}
try:
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(settings, f, indent=4)
self.log_message(f"[OK] Настройки сохранены в файл: {SETTINGS_FILE}")
logging.info("Settings saved successfully.")
except IOError as e:
logging.error(f"Error saving settings file: {e}")
messagebox.showerror("Ошибка сохранения настроек", f"Не удалось записать файл настроек: {e}")
except Exception as e:
logging.error(f"An unexpected error occurred while saving settings: {e}")
messagebox.showerror("Ошибка сохранения настроек", f"Произошла непредвиденная ошибка при сохранении настроек: {e}")
def read_file_in_chunks(self, file_path, chunk_size=1024 * 1024):
"""Reads a file in chunks to handle large files."""
logging.info(f"Reading file in chunks: {file_path}")
with open(file_path, 'rb') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
logging.info(f"Chunk size: {len(chunk)}")
logging.debug(f"Chunk content (hex): {binascii.hexlify(chunk[:100])}")
yield chunk
def cancel_operation(self):
self.cancel_flag = True
self.log_message("[INFO] Операция отменена пользователем.")
self.buttons["cancel_btn"].grid_remove() # Скрываем кнопку после отмены
def open_add_files_window(self):
"""Open window for adding files to structure"""
logging.info("open_add_files_window: Starting")
logging.info("Opening add files window.")
if hasattr(self, 'add_window') and self.add_window.winfo_exists():
self.add_window.lift()
logging.info("open_add_files_window: Window already exists, lifting it")
else:
self.add_window = AddFilesWindow(self, self.path_var.get(), self.token_var, self.repo_var, DND_FILES)
logging.info("open_add_files_window: New window created")
def open_load_window(self):
"""Opens the LoadWindow to browse and download from GitHub."""
logging.info("Attempting to open LoadWindow.")
token = self.token_var.get()
repo_name = self.repo_var.get()
local_path = self.path_var.get()
if not token or not repo_name or not local_path:
logging.warning("LoadWindow not opened: Missing token, repo, or local path.")
return
try:
# Create and show the LoadWindow
load_window = LoadWindow(self.root, token, repo_name, local_path, self)
load_window.transient(self.root) # Make it a child of the main window
load_window.grab_set() # Make it modal (optional, but can be useful)
self.root.wait_window(load_window) # Wait until the LoadWindow is closed
logging.info("LoadWindow closed.")
except Exception as e:
logging.error(f"Error opening LoadWindow: {e}")
def save_profile(self, *args):
# Сохранение профиля
token = self.token_var.get()
student = self.student_var.get()
if token.strip() and student.strip():
logging.info("Saving profile.")
self.save_settings()
logging.info("Profile saved successfully.")
else:
self.log_message("[ОШИБКА] Поля не должны быть пустыми")
logging.warning("Failed to save profile: Fields are empty.")
def select_path(self):
# Выбор пути
path = filedialog.askdirectory()
if path:
# Установка пути
self.path_var.set(path)
def log_message(self, msg):
self.log_text.configure(state='normal')
self.log_text.insert('end', msg + '\n')
self.log_text.see('end')
self.log_text.configure(state='disabled')
logging.info(msg)
def toggle_progress(self, start=True):
logging.info(f"Toggling progress bar: {'Start' if start else 'Stop'}")
# Включение/выключение прогрессбара
if start:
self.progress.start()
self.progress_running = True
logging.info("Progress bar started.")
else:
self.progress.stop()
self.progress_running = False
logging.info("Progress bar stopped.")
# Работа с файлами
def download_part_file(self, base_url, repo_path, part_name, destination_dir, attempt=1):
"""Downloads a part file from a GitHub repository.
Args:
base_url (str): The base URL of the GitHub API.
repo_path (str): The path to the repository (e.g., "user/repo").
part_name (str): The name of the part file.
destination_dir (str): The local directory to save the part file.
attempt (int): The current attempt number.
"""
full_url = f"{base_url}/repos/{repo_path}/contents/{part_name}"
headers = {
"Authorization": f"token {self.token_var.get()}" # Assuming you have a token
}
try:
response = requests.get(full_url, headers=headers)
response.raise_for_status() # Raise an exception for bad status codes
# Check if the response is JSON and contains the content
if response.headers['Content-Type'] == 'application/json':
content = response.json().get('content')
if content:
# Decode the base64 content
decoded_content = base64.b64decode(content).decode('utf-8')
# Save the decoded content to a file
local_file_path = os.path.join(destination_dir, part_name.split('/')[-1])
logging.info(f"Saving part file to: {local_file_path}")
with open(local_file_path, 'w', encoding='utf-8') as f:
f.write(decoded_content)
logging.info(f"[OK] Successfully downloaded part file: {part_name}")
else:
logging.error(f"Error: Content not found in response for {part_name}")
else:
logging.error(f"Error: Unexpected response type for {part_name}")
# Save the content to a file
local_file_path = os.path.join(destination_dir, part_name.split('/')[-1])
logging.info(f"Saving part file to: {local_file_path}")
with open(local_file_path, 'wb') as f:
f.write(response.content)
logging.info(f"[OK] Successfully downloaded part file: {part_name}")
except requests.exceptions.HTTPError as e:
logging.error(f"HTTP error downloading part file {part_name} (Original: {os.path.splitext(os.path.basename(part_name))[0]}), attempt {attempt}/3: {e}")
if attempt < 3:
logging.info(f"LoadWindow: [FAILED] HTTP error while downloading part file {part_name} (Original: {os.path.splitext(os.path.basename(part_name))[0]}), attempt {attempt}/3: {e}")
self.download_part_file(base_url, repo_path, part_name, destination_dir, attempt + 1)
else:
logging.info(f"LoadWindow: [FAILED] Failed to download part file {part_name}: [FAILED] Failed to download part file {part_name} (Original: {os.path.splitext(os.path.basename(part_name))[0]}) after 3 attempts: {e}")
raise
except requests.exceptions.RequestException as e:
logging.error(f"Error downloading {part_name}: {e}")
raise
def run_create_structure(self):
# Запуск создания структуры
logging.info("Starting create structure process.")
self.toggle_progress(True)
threading.Thread(target=self.threaded_create_structure, daemon=True).start()
def threaded_create_structure(self):
# Потоковое создание структуры
self.cancel_flag = False # Сбрасываем флаг отмены
self.buttons["cancel_btn"].grid() # Показываем кнопку отмены
self.create_folder_structure()
self.buttons["cancel_btn"].grid_remove() # Скрываем кнопку после завершения
self.toggle_progress(False)
def run_sync(self):
# Запуск синхронизации
logging.info("Starting synchronization process.")
self.toggle_progress(True)
threading.Thread(target=self.threaded_sync, daemon=True).start()
async def get_blob_async(self, repo, sha, session):
"""Asynchronously fetches and decodes a Git blob."""
if sha in self.blob_cache:
logging.info(f"Blob {sha} found in cache.")
return self.blob_cache[sha]
try:
logging.info(f"Fetching blob {sha} from GitHub.")
# Increased timeout for get_git_blob to 180 seconds (3 minutes)
blob = repo.get_git_blob(sha, timeout=self.timeout)
if blob.encoding == 'base64':
remote_content = b64decode(blob.content)
else:
remote_content = blob.content
self.blob_cache[sha] = remote_content # Cache the blob
return remote_content
except GithubException as e:
logging.error(f"Error fetching blob {sha}: {e}")
return None
def create_database(self):
"""Creates the database and table if they don't exist."""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS file_metadata (
file_path TEXT PRIMARY KEY,
file_hash TEXT,
last_modified REAL,
file_size INTEGER
)
""")
conn.commit()
conn.close()
logging.info(f"Database created/connected successfully at: {DATABASE_FILE}")
except sqlite3.Error as e:
logging.error(f"Error creating or connecting to database: {e}")
# Handle the error appropriately (e.g., display a message to the user, exit the application)
def close_database(self):
"""Closes the database connection."""
pass
def get_file_metadata(self, file_path, conn, cursor):
"""Retrieves file metadata from the database."""
cursor.execute("SELECT file_hash, last_modified, file_size FROM file_metadata WHERE file_path=?", (file_path,))
result = cursor.fetchone()
if result:
return {"file_hash": result[0], "last_modified": result[1], "file_size": result[2]}
return None
def save_file_metadata(self, file_path, file_hash, last_modified, file_size, conn, cursor):
"""Saves file metadata to the database."""
cursor.execute("""
INSERT OR REPLACE INTO file_metadata (file_path, file_hash, last_modified, file_size)
VALUES (?, ?, ?, ?)
""", (file_path, file_hash, last_modified, file_size))
conn.commit()
async def calculate_file_hash_async(self, file_path):
"""Calculates the SHA-256 hash of a file asynchronously."""
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self.calculate_file_hash, file_path)
def calculate_file_hash(self, file_path):
"""Calculates the SHA-256 hash of a file."""
hasher = hashlib.sha256()
try:
with open(file_path, 'rb') as file:
while True:
chunk = file.read(4096) # Read in 4KB chunks
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
except FileNotFoundError:
logging.error(f"File not found: {file_path}")
return None
async def sync_files_async(self, repo, conn, cursor):
"""
Asynchronously iterates through local files and synchronizes them with GitHub.
"""
logging.info("Starting asynchronous file iteration for sync.")
self.uploaded.set(0) # Reset counters at the start of a sync run
self.processed.set(0)
# Шаблон регулярного выражения: subj_abbrev_type_num_name.ext (e.g. nm_hw_4_Kidysyuk.ipynb)
pattern = re.compile(r"^([a-z]+)_(sem|hw|lec)_(\d+([_.]\d+)*)_(.+)\.(\w+)$")
student = self.student_var.get()
async with aiohttp.ClientSession() as session:
tasks = []
logging.info(f"Scanning local directory: {self.path_var.get()}")
for root, _, files in os.walk(self.path_var.get()):
if self.cancel_flag:
logging.info("File scanning cancelled.")
self.log_message("[INFO] Синхронизация прервана.")
return # Выходим из метода, если установлен флаг отмены
for file in files:
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, self.path_var.get())
github_path = rel_path.replace(os.path.sep, "/")
# Check if the file matches the pattern and contains the student's name
match = pattern.match(file)
if not match or student.lower() not in file.lower():
if self.all_logs.get():
logging.warning(f"{file} does not match the synchronization pattern or student name. Skipping.")
self.log_message(f"[ОШИБКА] {file} не подходит для синхронизации (шаблон/имя студента). Не понимаю. Пропускаю.")
continue # Skip this file if it doesn't match
# If the file matches, create a task to sync it
task = asyncio.create_task(self.sync_file_async(repo, file, full_path, github_path, student, pattern, session, conn, cursor))
tasks.append(task)
logging.info(f"Found {len(tasks)} files matching the pattern and student name to potentially sync.")
await asyncio.gather(*tasks)
logging.info("Finished asynchronous file iteration for sync.")
async def sync_file_async(self, repo, file, full_path, github_path, student, pattern, session, conn, cursor):
"""
Asynchronously synchronizes a single file with the GitHub repository.
Checks file size. Files > 40MB are split, encoded, and uploaded as parts.
Files <= 40MB are uploaded directly via Contents API.
"""
# Check for cancellation flag
if self.cancel_flag:
self.log_message("[INFO] Синхронизация прервана.")
return
logging.info(f"Processing file: {file}")
# File name validation based on path and pattern
match = pattern.match(file)
if not match or student.lower() not in file.lower():
if self.all_logs.get():
logging.warning(f"{file} does not match the synchronization pattern or student name. Skipping.")
self.log_message(f"[ОШИБКА] {file} не подходит для синхронизации (шаблон/имя студента). Пропускаю.")
self.processed.set(self.processed.get() + 1) # Still count as processed even if skipped by name
return
logging.info(f"File: {file} passed name check")
# --- File Size Check ---
try:
file_size = os.path.getsize(full_path)
# Define the size limit for direct API upload in bytes (40 MB)
DIRECT_UPLOAD_SIZE_LIMIT_BYTES = 40 * 1024 * 1024
if file_size > DIRECT_UPLOAD_SIZE_LIMIT_BYTES:
logging.warning(f"File {file} ({file_size / (1024*1024):.2f} MB) exceeds the {DIRECT_UPLOAD_SIZE_LIMIT_BYTES / (1024*1024):.0f} MB limit for direct API upload.")
self.log_message(f"[ПРЕДУПРЕЖДЕНИЕ] Файл {file} ({file_size / (1024*1024):.2f} МБ) превышает лимит ({DIRECT_UPLOAD_SIZE_LIMIT_BYTES / (1024*1024):.0f} МБ) для прямой загрузки через API. ")
if False:
# Depriciated
# Call the new function to handle splitting and uploading parts
await self.split_and_upload_parts(repo, full_path, github_path, student, conn, cursor)
self.processed.set(self.processed.get() + 1) # Count the original file as processed after handling parts
return # Exit the function after handling parts
except FileNotFoundError:
logging.error(f"Local file not found during size check: {full_path}. Skipping.")
self.log_message(f"[ОШИБКА] Локальный файл не найден при проверке размера: {file}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
except Exception as e:
logging.error(f"Error during file size check for {file}: {e}. Skipping.")
self.log_message(f"[ОШИБКА] Ошибка при проверке размера файла {file}: {e}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
# --- Metadata and Hash Check (for files <= 40MB) ---
# This part is only reached if the file is NOT larger than DIRECT_UPLOAD_SIZE_LIMIT_BYTES
try:
last_modified = os.path.getmtime(full_path)
# file_size is already obtained above
except FileNotFoundError:
logging.error(f"Local file not found during metadata check: {full_path}. Skipping.")
self.log_message(f"[ОШИБКА] Локальный файл не найден при проверке метаданных: {file}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
except Exception as e:
logging.error(f"Error getting local file metadata for {file}: {e}. Skipping.")
self.log_message(f"[ОШИБКА] Ошибка при получении метаданных локального файла {file}: {e}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
# Retrieve cached metadata from the database
cached_metadata = self.get_file_metadata(full_path, conn, cursor)
# Calculate local file hash
local_file_hash = await self.calculate_file_hash_async(full_path)
if local_file_hash is None:
logging.error(f"Failed to calculate hash for {file}. Skipping.")
self.log_message(f"[ОШИБКА] Не удалось вычислить хеш для {file}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
# Check if metadata is unchanged and hash is cached
if cached_metadata:
if cached_metadata["last_modified"] == last_modified and cached_metadata["file_size"] == file_size and cached_metadata["file_hash"] == local_file_hash:
logging.info(f"{file} is unchanged based on metadata and hash. Skipping.")
self.log_message(f"[OK] {file} без изменений. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Increment processed counter
return
else:
logging.info(f"File {file} metadata or hash has changed. Proceeding with sync.")
else:
logging.info(f"File {file} metadata not found in database. Proceeding with sync.")
# --- File Upload/Update using Contents API (PUT) for files <= 40MB ---
max_retries = 5
retry_delay = 1
repo_owner, repo_name = self.repo_var.get().split('/')
url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/contents/{github_path}"
headers = {
"Authorization": f"token {self.token_var.get()}",
"Accept": "application/vnd.github.v3+json"
}
# Determine if we are creating or updating the file on GitHub
remote_file_sha = None
remote_file_exists = False
try:
contents = repo.get_contents(github_path)
if contents.type == "file":
remote_file_exists = True
remote_file_sha = contents.sha
logging.info(f"Remote file {file} exists with SHA: {remote_file_sha}")
else:
logging.error(f"Error: Path {github_path} on GitHub is not a file.")
self.log_message(f"[ОШИБКА] Путь {github_path} на GitHub не является файлом.")
self.processed.set(self.processed.get() + 1) # Count as processed
return # Skip if path is not a file
except GithubException as e:
if e.status == 404:
logging.info(f"Remote file {file} not found on GitHub. Proceeding with creation.")
self.log_message(f"[INFO] Удаленный файл {file} не найден на GitHub. Создаю его.")
remote_file_exists = False
else:
logging.warning(f"GithubException during initial get_contents for {file}: {e}. Proceeding assuming creation/update.")
self.log_message(f"[ПРЕДУПРЕЖДЕНИЕ] Ошибка GitHub при получении содержимого {file}: {e}. Продолжаю, предполагая создание/обновление.")
logging.error(f"Failed to get remote file SHA for {file} due to GithubException: {e}. Cannot proceed with update.")
self.log_message(f"[ОШИБКА] Не удалось получить SHA удаленного файла {file} из-за ошибки GitHub: {e}. Не могу обновить.")
self.processed.set(self.processed.get() + 1) # Count as processed
return # Cannot proceed if we can't get SHA for potential update
except Exception as e:
logging.error(f"Unexpected error during initial get_contents for {file}: {type(e).__name__} - {e}. Cannot proceed.")
self.log_message(f"[ОШИБКА] Неожиданная ошибка при получении содержимого {file}: {type(e).__name__} - {e}. Не могу продолжить.")
self.processed.set(self.processed.get() + 1) # Count as processed
return # Cannot proceed due to unexpected error
# Read the content of the file to be uploaded and Base64 encode it
logging.info(f'Reading and encoding content for {file}')
try:
local_content_chunks = self.read_file_in_chunks(full_path)
local_content = b''.join(local_content_chunks) # Join chunks to get full content
encoded_content = b64encode(local_content).decode('ascii')
except MemoryError:
logging.error(f"MemoryError while reading or encoding content for {file}. Skipping.")
self.log_message(f"[ОШИБКА] Ошибка памяти при чтении или кодировании содержимого для {file}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
except Exception as e:
logging.error(f"Error reading or encoding content for {file}: {e}. Skipping.")
self.log_message(f"[ОШИБКА] Ошибка при чтении или кодировании содержимого для {file}: {e}. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
if not encoded_content:
logging.warning(f"Encoded content is empty for {file}. Skipping.")
self.log_message(f"[ПРЕДУПРЕЖДЕНИЕ] Кодированное содержимое для {file} пустое. Пропускаю.")
self.processed.set(self.processed.get() + 1) # Count as processed
return # Skip if file is empty
# Prepare the request body for the Contents API
commit_message = f"{'Update' if remote_file_exists else 'Add'} {file}"
data = {
"message": commit_message,
"content": encoded_content,
"branch": repo.default_branch # Specify the target branch
}
# Add SHA if updating an existing file
if remote_file_exists and remote_file_sha:
data["sha"] = remote_file_sha
elif remote_file_exists and not remote_file_sha:
logging.error(f"Remote file {file} exists but SHA could not be retrieved. Cannot update.")
self.log_message(f"[ОШИБКА] Удаленный файл {file} существует, но не удалось получить его SHA. Не могу обновить.")
self.processed.set(self.processed.get() + 1) # Count as processed
return
logging.info(f"Attempting to {'update' if remote_file_exists else 'create'} file {file} via Contents API ({url})")
for attempt in range(max_retries):
try:
logging.info(f"Contents API sync attempt {attempt + 1}/{max_retries} for {file}.")
response = requests.put(url, headers=headers, json=data, verify=certifi.where())
logging.info(f"Contents API response status code: {response.status_code}")
if response.status_code in [200, 201]: # 200 for update, 201 for create
logging.info(f"File {file} {'updated' if remote_file_exists else 'created'} successfully via Contents API.")
self.log_message(f"[OK] Файл {file} успешно {'обновлен' if remote_file_exists else 'создан'} через Contents API")
self.uploaded.set(self.uploaded.get() + 1)
# Save metadata for the successfully synced file
self.save_file_metadata(full_path, local_file_hash, last_modified, file_size, conn, cursor)
self.processed.set(self.processed.get() + 1) # Increment processed counter
return # Exit the function after successful sync
else: