-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathold.py
More file actions
3559 lines (3026 loc) · 131 KB
/
old.py
File metadata and controls
3559 lines (3026 loc) · 131 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
#!/usr/bin/env python3
import sys
import os
import base64
import requests
import markdown
import re
from dotenv import load_dotenv, set_key, find_dotenv
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QDialog, QVBoxLayout, QHBoxLayout,
QFormLayout, QDialogButtonBox, QWidget, QLabel, QPushButton,
QListWidget, QListWidgetItem, QCheckBox, QProgressBar, QTextEdit,
QLineEdit, QFileDialog, QTabWidget, QGroupBox, QSplitter, QToolBar,
QComboBox, QStatusBar, QTreeWidget, QTreeWidgetItem, QMessageBox,
QInputDialog, QScrollArea, QPlainTextEdit, QStyle, QSlider,
QStackedWidget, QButtonGroup
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QRect, QPoint, QMimeData, QUrl
from PyQt5.QtGui import QPainter, QBrush, QPixmap, QColor, QIcon, QDragEnterEvent, QDropEvent
from PyQt5.QtWebEngineWidgets import QWebEngineView
DARK_STYLE = """
QMainWindow, QDialog, QWidget {
background-color: #2c2c2c;
font-family: 'Segoe UI', sans-serif;
color: #f0f0f0;
}
QLabel {
font-size: 11pt;
color: #ffffff;
}
QLineEdit, QTextEdit, QPlainTextEdit {
background: #3a3a3a;
border: 1px solid #444;
border-radius: 4px;
padding: 6px;
color: #ffffff;
}
QPushButton {
background-color: #565656;
padding: 7px 12px;
border-radius: 4px;
color: #ffffff;
}
QPushButton:hover {
background-color: #666666;
}
QPushButton:pressed {
background-color: #4e4e4e;
}
QPushButton:disabled {
background-color: #3a3a3a;
color: #888888;
}
QPushButton:checked {
background-color: #505050;
font-weight: bold;
}
QCheckBox {
spacing: 6px;
color: #dddddd;
}
QProgressBar {
background-color: #444;
border-radius: 4px;
text-align: center;
color: #ffffff;
}
QProgressBar::chunk {
background-color: #77b300;
}
QMenu {
background: #3a3a3a;
border: 1px solid #444;
}
QMenu::item:selected {
background: #495057;
}
QTabWidget::pane {
border: 1px solid #444;
}
QTabBar::tab {
background: #3a3a3a;
padding: 8px;
}
QTabBar::tab:selected {
background: #565656;
}
QComboBox {
background-color: #3a3a3a;
border: 1px solid #444;
border-radius: 4px;
padding: 5px;
color: #ffffff;
min-width: 6em;
}
QComboBox:hover {
border: 1px solid #666;
}
QComboBox::drop-down {
subcontrol-origin: padding;
subcontrol-position: top right;
width: 15px;
border-left: 1px solid #444;
}
QTreeWidget {
background-color: #3a3a3a;
border: 1px solid #444;
color: #ffffff;
}
QTreeWidget::item {
height: 25px;
}
QTreeWidget::item:selected {
background-color: #565656;
}
QScrollBar:vertical {
border: none;
background: #3a3a3a;
width: 10px;
margin: 0px;
}
QScrollBar::handle:vertical {
background: #565656;
min-height: 20px;
border-radius: 5px;
}
QScrollBar::handle:vertical:hover {
background: #666666;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical,
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
background: none;
}
QWebEngineView {
background-color: #3a3a3a;
}
"""
class GitHubAPI:
"""GitHub API wrapper."""
def __init__(self, token):
self.token = token
self.headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github+json",
}
def validate_token(self):
try:
r = requests.get("https://api.github.com/user", headers=self.headers)
if r.status_code == 200:
return True, r.json()
return False, f"Error {r.status_code}: Token invalid"
except Exception as e:
return False, str(e)
def get_user_info(self, username):
try:
r = requests.get(f"https://api.github.com/users/{username}", headers=self.headers)
if r.status_code == 200:
return True, r.json()
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def search_users(self, query):
try:
r = requests.get(f"https://api.github.com/search/users?q={query}", headers=self.headers)
if r.status_code == 200:
return True, r.json().get('items', [])
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def follow_user(self, user):
try:
r = requests.put(f"https://api.github.com/user/following/{user}", headers=self.headers)
return (r.status_code == 204), (f"Followed {user}" if r.status_code == 204 else f"Error {r.status_code}")
except Exception as e:
return False, str(e)
def unfollow_user(self, user):
try:
r = requests.delete(f"https://api.github.com/user/following/{user}", headers=self.headers)
return (r.status_code == 204), (f"Unfollowed {user}" if r.status_code == 204 else f"Error {r.status_code}")
except Exception as e:
return False, str(e)
def star_repo(self, owner, repo):
try:
r = requests.put(f"https://api.github.com/user/starred/{owner}/{repo}", headers=self.headers)
return (r.status_code == 204), (f"Starred {owner}/{repo}" if r.status_code == 204 else f"Error {r.status_code}")
except Exception as e:
return False, str(e)
def unstar_repo(self, owner, repo):
try:
r = requests.delete(f"https://api.github.com/user/starred/{owner}/{repo}", headers=self.headers)
return (r.status_code == 204), (f"Unstarred {owner}/{repo}" if r.status_code == 204 else f"Error {r.status_code}")
except Exception as e:
return False, str(e)
def get_following(self):
try:
r = requests.get("https://api.github.com/user/following", headers=self.headers)
if r.status_code == 200:
return True, r.json()
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def get_repos(self):
try:
r = requests.get("https://api.github.com/user/repos?per_page=100", headers=self.headers)
if r.status_code == 200:
return True, r.json()
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def create_repo(self, name, desc, private):
data = {"name": name, "description": desc, "private": private}
try:
r = requests.post("https://api.github.com/user/repos", headers=self.headers, json=data)
if r.status_code == 201:
return True, r.json()
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def upload_file(self, owner, repo, path, content):
try:
enc = base64.b64encode(content).decode()
fn = os.path.basename(path)
up_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{fn}"
data = {"message": f"Add {fn}", "content": enc}
r = requests.put(up_url, headers=self.headers, json=data)
if r.status_code in [200, 201]:
return True, f"Uploaded {fn}"
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def get_contents(self, owner, repo, path=""):
"""Get contents of path within the repository. path can be a file or directory."""
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
try:
r = requests.get(url, headers=self.headers)
if r.status_code == 200:
return True, r.json()
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def update_file(self, owner, repo, path, message, new_content, sha):
"""Update an existing file in a repo."""
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
data = {
"message": message,
"content": base64.b64encode(new_content.encode()).decode(),
"sha": sha
}
try:
r = requests.put(url, headers=self.headers, json=data)
if r.status_code in [200, 201]:
return True, r.json()
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def delete_file(self, owner, repo, path, message, sha):
"""Delete a file in a repo."""
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
data = {"message": message, "sha": sha}
try:
r = requests.delete(url, headers=self.headers, json=data)
if r.status_code == 200:
return True, f"File '{path}' deleted"
return False, f"Error {r.status_code}"
except Exception as e:
return False, str(e)
def enable_wiki(self, owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}"
data = {"has_wiki": True}
r = requests.patch(url, headers=self.headers, json=data)
if r.status_code == 200:
return True, "Wiki enabled."
return False, f"Error {r.status_code}"
def disable_wiki(self, owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}"
data = {"has_wiki": False}
r = requests.patch(url, headers=self.headers, json=data)
if r.status_code == 200:
return True, "Wiki disabled."
return False, f"Error {r.status_code}"
def create_branch(self, owner, repo, branch_name, base_sha):
url = f"https://api.github.com/repos/{owner}/{repo}/git/refs"
data = {
"ref": f"refs/heads/{branch_name}",
"sha": base_sha
}
r = requests.post(url, headers=self.headers, json=data)
if r.status_code == 201:
return True, f"Branch '{branch_name}' created."
return False, f"Error {r.status_code}"
def delete_branch(self, owner, repo, branch_name):
url = f"https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch_name}"
r = requests.delete(url, headers=self.headers)
if r.status_code == 204:
return True, f"Branch '{branch_name}' deleted."
return False, f"Error {r.status_code}"
def update_profile(self, name, bio, company, location, blog):
"""Update user profile information"""
url = "https://api.github.com/user"
data = {
"name": name,
"bio": bio,
"company": company,
"location": location,
"blog": blog
}
try:
r = requests.patch(url, headers=self.headers, json=data)
if r.status_code == 200:
return True, r.json()
return False, f"Error {r.status_code}: {r.json().get('message', '')}"
except Exception as e:
return False, str(e)
class ActionThread(QThread):
progress = pyqtSignal(int, str)
done = pyqtSignal(bool, str)
def __init__(self, api, operation, items):
super().__init__()
self.api = api
self.operation = operation
self.items = items
def run(self):
total = len(self.items)
success = 0
for i, elem in enumerate(self.items, start=1):
msg = ""
ok = False
if self.operation == 'follow':
ok, msg = self.api.follow_user(elem)
elif self.operation == 'unfollow':
ok, msg = self.api.unfollow_user(elem)
elif self.operation == 'star':
parts = elem.split('/')
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
ok, msg = self.api.star_repo(owner, repo)
elif self.operation == 'unstar':
parts = elem.split('/')
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
ok, msg = self.api.unstar_repo(owner, repo)
self.progress.emit(int(i / total * 100), msg)
if ok:
success += 1
self.done.emit(True, f"Completed {success}/{total} operations")
class MultiAccountThread(QThread):
progress = pyqtSignal(int, str)
done = pyqtSignal(bool, str)
def __init__(self, tokens, operation, items):
super().__init__()
self.tokens = tokens
self.operation = operation
self.items = items
def run(self):
total_ops = len(self.tokens) * len(self.items)
done_count = 0
success = 0
for token in self.tokens:
api = GitHubAPI(token)
for elem in self.items:
msg = ""
ok = False
if self.operation == 'follow':
ok, msg = api.follow_user(elem)
elif self.operation == 'unfollow':
ok, msg = api.unfollow_user(elem)
elif self.operation == 'star':
parts = elem.split('/')
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
ok, msg = api.star_repo(owner, repo)
elif self.operation == 'unstar':
parts = elem.split('/')
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
ok, msg = api.unstar_repo(owner, repo)
done_count += 1
self.progress.emit(int(done_count / total_ops * 100), msg)
if ok:
success += 1
self.done.emit(True, f"Completed {success}/{total_ops} operations")
class AvatarLabel(QLabel):
def set_avatar(self, url):
try:
px = QPixmap()
px.loadFromData(requests.get(url).content)
round_px = QPixmap(px.size())
round_px.fill(Qt.transparent)
painter = QPainter(round_px)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(QBrush(px))
painter.setPen(Qt.NoPen)
painter.drawEllipse(0, 0, px.width(), px.height())
painter.end()
scaled = round_px.scaled(60, 60, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.setPixmap(scaled)
except:
pass
class UserWidget(QWidget):
"""Generic user display widget with optional checkbox."""
unfollow_clicked = pyqtSignal(str)
def __init__(self, username, avatar, show_check=True, show_unfollow=False):
super().__init__()
self.username = username
self.box = QHBoxLayout(self)
self.box.setContentsMargins(4, 4, 4, 4)
self.check = QCheckBox()
self.label_img = AvatarLabel()
self.label_img.setFixedSize(60, 60)
self.label_img.set_avatar(avatar)
self.label_user = QLabel(username)
self.label_user.setStyleSheet("font-weight: bold;")
if show_check:
self.box.addWidget(self.check)
else:
self.check.setVisible(False)
self.box.addWidget(self.label_img)
self.box.addWidget(self.label_user)
# Add unfollow button if requested
if show_unfollow:
self.unfollow_btn = QPushButton("Unfollow")
self.unfollow_btn.setFixedWidth(80)
self.unfollow_btn.clicked.connect(lambda: self.unfollow_clicked.emit(username))
self.box.addWidget(self.unfollow_btn)
self.box.addStretch()
self.setLayout(self.box)
def is_checked(self):
return self.check.isChecked()
class TokenManagerDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Token Manager")
self.resize(450, 400)
lay = QVBoxLayout(self)
form_box = QGroupBox("Add New")
f_lay = QFormLayout(form_box)
self.ed_name = QLineEdit()
self.ed_token = QLineEdit()
self.ed_token.setEchoMode(QLineEdit.Password)
btn_add = QPushButton("Add Token")
btn_add.clicked.connect(self.add_token)
f_lay.addRow("Name:", self.ed_name)
f_lay.addRow("Token:", self.ed_token)
f_lay.addRow("", btn_add)
lay.addWidget(form_box)
exist_box = QGroupBox("Existing")
v_lay = QVBoxLayout(exist_box)
self.list_tokens = QListWidget()
# Add edit button for tokens
edit_hbox = QHBoxLayout()
self.btn_rem = QPushButton("Remove Selected")
self.btn_edit = QPushButton("Edit Selected")
self.btn_rem.clicked.connect(self.remove_token)
self.btn_edit.clicked.connect(self.edit_token)
edit_hbox.addWidget(self.btn_edit)
edit_hbox.addWidget(self.btn_rem)
v_lay.addWidget(self.list_tokens)
v_lay.addLayout(edit_hbox)
lay.addWidget(exist_box)
close_btn = QDialogButtonBox(QDialogButtonBox.Close)
close_btn.rejected.connect(self.close)
lay.addWidget(close_btn)
self.setLayout(lay)
self.load_tokens()
def load_tokens(self):
self.list_tokens.clear()
load_dotenv(find_dotenv(usecwd=True))
for k in os.environ:
if k.startswith("GITHUB_TOKEN_"):
self.list_tokens.addItem(k[13:])
def add_token(self):
name = self.ed_name.text().strip()
tok = self.ed_token.text().strip()
if not name or not tok:
return
api = GitHubAPI(tok)
ok, check = api.validate_token()
if not ok:
return
env_file = find_dotenv(usecwd=True)
if not env_file:
with open('.env', 'w'):
pass
env_file = '.env'
set_key(env_file, "GITHUB_TOKEN_" + name, tok)
self.ed_name.clear()
self.ed_token.clear()
self.load_tokens()
def remove_token(self):
curr = self.list_tokens.currentItem()
if curr:
name = curr.text()
env_file = find_dotenv(usecwd=True)
if env_file and os.path.exists(env_file):
with open(env_file, 'r') as f:
lines = f.readlines()
with open(env_file, 'w') as f:
for ln in lines:
if not ln.startswith("GITHUB_TOKEN_"+name+"="):
f.write(ln)
self.load_tokens()
def edit_token(self):
curr = self.list_tokens.currentItem()
if curr:
old_name = curr.text()
env_file = find_dotenv(usecwd=True)
load_dotenv(env_file)
current_token = os.environ.get("GITHUB_TOKEN_" + old_name, "")
# Create an edit dialog to edit both name and token
edit_dialog = QDialog(self)
edit_dialog.setWindowTitle("Edit Token")
dialog_layout = QFormLayout(edit_dialog)
name_edit = QLineEdit(old_name)
token_edit = QLineEdit(current_token)
token_edit.setEchoMode(QLineEdit.Password)
dialog_layout.addRow("Name:", name_edit)
dialog_layout.addRow("Token:", token_edit)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(edit_dialog.accept)
button_box.rejected.connect(edit_dialog.reject)
dialog_layout.addRow(button_box)
if edit_dialog.exec_():
new_name = name_edit.text().strip()
new_token = token_edit.text().strip()
if not new_name or not new_token:
QMessageBox.warning(self, "Invalid Input", "Name and token cannot be empty")
return
# First validate the token
api = GitHubAPI(new_token)
valid, _ = api.validate_token()
if valid:
# Remove old token
with open(env_file, 'r') as f:
lines = f.readlines()
with open(env_file, 'w') as f:
for ln in lines:
if not ln.startswith("GITHUB_TOKEN_"+old_name+"="):
f.write(ln)
# Add new token with new name
set_key(env_file, "GITHUB_TOKEN_" + new_name, new_token)
QMessageBox.information(self, "Success", "Token updated successfully")
self.load_tokens()
else:
QMessageBox.warning(self, "Invalid Token", "The token you entered is invalid")
class LoginWindow(QDialog):
def __init__(self):
super().__init__()
# Set frameless window
self.setWindowFlags(Qt.FramelessWindowHint)
self.resize(500, 300)
self.move_to_center()
# Main layout
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(0)
# Custom title bar
title_bar = QWidget()
title_bar.setFixedHeight(40)
title_bar.setStyleSheet("background-color: #1a1a1a;")
title_bar_layout = QHBoxLayout(title_bar)
title_bar_layout.setContentsMargins(10, 0, 10, 0)
title_label = QLabel("Select a GitHub from your tokens:")
title_label.setStyleSheet("color: white; font-weight: bold; font-size: 12pt;")
close_btn = QPushButton("✕")
close_btn.setFixedSize(35, 30)
close_btn.setStyleSheet("""
QPushButton {
background-color: transparent;
color: white;
border: none;
font-weight: bold;
}
QPushButton:hover {
background-color: #E81123;
color: white;
}
""")
close_btn.clicked.connect(self.reject)
title_bar_layout.addWidget(title_label)
title_bar_layout.addStretch()
title_bar_layout.addWidget(close_btn)
# Content area
content = QWidget()
content_layout = QVBoxLayout(content)
# Existing controls
self.list_tokens = QListWidget()
self.btn_login = QPushButton("Login")
self.btn_login.setEnabled(False)
self.btn_refresh = QPushButton("Refresh")
self.btn_manage = QPushButton("Manage Tokens")
self.btn_edit_token = QPushButton("Edit Token")
self.btn_edit_token.setEnabled(False)
self.selected_token = None
self.selected_user = None
hl = QHBoxLayout()
hl.addWidget(self.btn_manage)
hl.addWidget(self.btn_edit_token)
hl.addStretch()
hl.addWidget(self.btn_refresh)
hl.addWidget(self.btn_login)
content_layout.addWidget(self.list_tokens)
content_layout.addLayout(hl)
# Add to main layout
main_layout.addWidget(title_bar)
main_layout.addWidget(content)
# Connect signals
self.btn_login.clicked.connect(self.accept)
self.btn_refresh.clicked.connect(self.load_tokens)
self.btn_manage.clicked.connect(self.manage_tokens)
self.btn_edit_token.clicked.connect(self.edit_selected_token)
self.list_tokens.itemClicked.connect(self.token_selected)
# Store for dragging the window
self.drag_pos = None
# Load tokens
self.load_tokens()
def mousePressEvent(self, event):
"""Handle mouse press events for moving the window"""
if event.button() == Qt.LeftButton:
self.drag_pos = event.globalPos() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
"""Handle mouse move events for dragging the window"""
if event.buttons() == Qt.LeftButton and hasattr(self, 'drag_pos'):
self.move(event.globalPos() - self.drag_pos)
event.accept()
def move_to_center(self):
screen_rect = QApplication.desktop().screenGeometry()
window_size = self.geometry()
x = (screen_rect.width() - window_size.width()) // 2
y = (screen_rect.height() - window_size.height()) // 2
self.move(x, y)
def load_tokens(self):
self.list_tokens.clear()
load_dotenv(find_dotenv(usecwd=True))
for k, v in os.environ.items():
if k.startswith("GITHUB_TOKEN_"):
api = GitHubAPI(v)
ok, data = api.validate_token()
if ok:
item = QListWidgetItem(k[13:] + f" ({data['login']})")
item.setData(Qt.UserRole, (v, data))
else:
item = QListWidgetItem(k[13:] + " (Invalid)")
item.setForeground(QColor("red"))
self.list_tokens.addItem(item)
self.btn_login.setEnabled(False)
self.btn_edit_token.setEnabled(False)
def token_selected(self, item):
d = item.data(Qt.UserRole)
if d:
self.selected_token, user_data = d
self.selected_user = user_data
self.btn_login.setEnabled(True)
self.btn_edit_token.setEnabled(True)
def manage_tokens(self):
dlg = TokenManagerDialog(self)
if dlg.exec_():
self.load_tokens()
def edit_selected_token(self):
if not self.selected_token:
return
current_item = self.list_tokens.currentItem()
if not current_item:
return
token_name = current_item.text().split(" (")[0]
new_token, ok = QInputDialog.getText(
self,
"Edit Token",
f"Update token for {token_name}:",
QLineEdit.Password,
self.selected_token
)
if ok and new_token:
# Validate the token
api = GitHubAPI(new_token)
valid, data = api.validate_token()
if valid:
# Update the token in the .env file
env_file = find_dotenv(usecwd=True)
set_key(env_file, "GITHUB_TOKEN_" + token_name, new_token)
QMessageBox.information(self, "Success", f"Token for {token_name} updated successfully")
self.load_tokens() # Refresh the list
else:
QMessageBox.warning(self, "Invalid Token", "The token you entered is invalid")
class MultiTokenDialog(QDialog):
def __init__(self, tokens_dict, parent=None):
super().__init__(parent)
self.setWindowTitle("Select Tokens")
self.resize(400, 300)
self.selected_tokens = []
self.tokens_dict = tokens_dict
main_lay = QVBoxLayout(self)
self.list_tokens = QListWidget()
for name in tokens_dict:
item = QListWidgetItem(name)
item.setCheckState(Qt.Unchecked)
self.list_tokens.addItem(item)
btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
btn_box.accepted.connect(self.on_ok)
btn_box.rejected.connect(self.reject)
main_lay.addWidget(self.list_tokens)
main_lay.addWidget(btn_box)
def on_ok(self):
self.selected_tokens = []
for i in range(self.list_tokens.count()):
item = self.list_tokens.item(i)
if item.checkState() == Qt.Checked:
name = item.text()
tok = self.tokens_dict.get(name, None)
if tok:
self.selected_tokens.append(tok)
if not self.selected_tokens:
self.reject()
else:
self.accept()
class DropArea(QWidget):
"""Widget that accepts file drops for uploading to GitHub"""
fileDrop = pyqtSignal(list) # Signal emitted when files are dropped
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
layout = QVBoxLayout(self)
self.label = QLabel("Drop files here to upload")
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("""
border: 2px dashed #565656;
padding: 20px;
border-radius: 8px;
font-size: 14pt;
""")
layout.addWidget(self.label)
self.setLayout(layout)
self.setMinimumHeight(100)
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
event.acceptProposedAction()
self.label.setStyleSheet("""
border: 2px dashed #77b300;
padding: 20px;
border-radius: 8px;
font-size: 14pt;
background-color: rgba(119, 179, 0, 0.1);
""")
def dragLeaveEvent(self, event):
self.label.setStyleSheet("""
border: 2px dashed #565656;
padding: 20px;
border-radius: 8px;
font-size: 14pt;
""")
def dropEvent(self, event: QDropEvent):
urls = event.mimeData().urls()
file_paths = [url.toLocalFile() for url in urls if url.isLocalFile()]
if file_paths:
self.fileDrop.emit(file_paths)
self.label.setStyleSheet("""
border: 2px dashed #565656;
padding: 20px;
border-radius: 8px;
font-size: 14pt;
""")
class MarkdownPreview(QWidget):
"""Widget to preview markdown or code with proper styling"""
def __init__(self, parent=None):
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
# Preview WebView
self.preview = QWebEngineView()
self.preview.setMinimumHeight(200)
layout.addWidget(self.preview)
self.setLayout(layout)
# Default GitHub-style CSS
self.github_css = """
<style>
html, body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
color: #e6edf3;
background-color: #0d1117;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow-x: hidden;
box-sizing: border-box;
}
.markdown-body {
box-sizing: border-box;
width: 100%;
max-width: 100%;
margin: 0;
padding: 16px;
overflow-wrap: break-word;
word-wrap: break-word;
}
.markdown-body img {
max-width: 100%;
height: auto;
}
h1, h2, h3, h4, h5, h6 {
margin-top: 24px;
margin-bottom: 16px;
font-weight: 600;
line-height: 1.25;
color: #e6edf3;
}
h1 { font-size: 2em; padding-bottom: 0.3em; border-bottom: 1px solid #3b434b; }
h2 { font-size: 1.5em; padding-bottom: 0.3em; border-bottom: 1px solid #3b434b; }
h3 { font-size: 1.25em; }
h4 { font-size: 1em; }
p, blockquote, ul, ol, dl, table, pre { margin-top: 0; margin-bottom: 16px; }
code, pre {
font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace;
}
pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #161b22;
border-radius: 3px;
white-space: pre-wrap;
word-wrap: break-word;
max-width: 100%;
}
code {
padding: 0.2em 0.4em;
margin: 0;
font-size: 85%;
background-color: rgba(240,246,252,0.15);
border-radius: 3px;
}
pre code {
background-color: transparent;
padding: 0;
margin: 0;
font-size: 100%;
word-break: normal;
white-space: pre-wrap;
border: 0;
}
blockquote {
padding: 0 1em;
color: #8b949e;
border-left: 0.25em solid #3b434b;
}
table {
border-spacing: 0;
border-collapse: collapse;
width: 100%;
max-width: 100%;
overflow-x: auto;
display: block;
}
table th, table td {
padding: 6px 13px;
border: 1px solid #3b434b;
}
table tr:nth-child(2n) {
background-color: #161b22;
}
/* Force content to fit within viewport */
@media screen and (max-width: 100%) {
body, .markdown-body {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
pre, code, table {
max-width: 100%;
overflow-x: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
}
</style>
"""
self.update_preview("")
# Set fixed zoom to 75%
self.preview.setZoomFactor(0.75)
def update_preview(self, content, file_type="markdown", dark_mode=True):
"""Update the preview with the given content"""
self.current_content = content
self.current_file_type = file_type
if not content:
html = f"{self.github_css}<div class='markdown-body'>Preview will appear here</div>"
self.preview.setHtml(html)
return