-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaidex.py
564 lines (461 loc) · 21.2 KB
/
aidex.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
import sys
import time
import json
import pyotp
import pyperclip
import binascii
import platform
from PyQt5.QtWidgets import (
QApplication, QSystemTrayIcon, QDialog, QPushButton, QLineEdit, QVBoxLayout, QWidget, QHBoxLayout, QMessageBox,
QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QScrollArea, QFrame, QSpacerItem, QSizePolicy
)
from PyQt5.QtCore import QTimer, Qt, pyqtSlot, QEvent
from PyQt5.QtGui import QIcon, QCursor, QDrag, QPainter, QBrush, QColor
from qt_material import apply_stylesheet
from pathlib import Path
if hasattr(sys, '_MEIPASS'):
base_path = Path(sys._MEIPASS)
else:
base_path = Path(__file__).resolve().parent
icon_path = str(base_path / 'icon.icns')
# document path
CONFIG_FILE = str(Path.home() / "Documents" / "totp_config.json")
def correct_secret_padding(secret):
secret = secret.strip().replace(' ', '').upper()
missing_padding = len(secret) % 8
if missing_padding:
secret += '=' * (8 - missing_padding)
return secret
class DraggableTableWidget(QTableWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.viewport().setAcceptDrops(True)
self.setDragDropOverwriteMode(False)
self.setDropIndicatorShown(True)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.drag_start_position = None
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drag_start_position = event.pos()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton):
return
if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
return
drag = QDrag(self)
mimedata = self.model().mimeData(self.selectedIndexes())
if mimedata:
drag.setMimeData(mimedata)
drag.exec_(Qt.MoveAction)
def dropEvent(self, event):
if event.source() == self and (event.dropAction() == Qt.MoveAction or self.dragDropMode() == QAbstractItemView.InternalMove):
success, row, col, topIndex = self.dropOn(event)
if success:
selRows = self.getSelectedRowsFast()
top = selRows[0]
dropRow = row
if dropRow == -1:
dropRow = self.rowCount()
if dropRow > top:
dropRow -= 1
rows = []
for i in range(len(selRows)):
rows.append(self.extractRow(top))
for i in range(len(rows)):
self.insertRow(dropRow)
for j in range(self.columnCount()):
self.setItem(dropRow, j, rows[i][j])
dropRow += 1
event.accept()
self.window().update_data_model()
def extractRow(self, row):
items = []
for column in range(self.columnCount()):
items.append(self.takeItem(row, column))
self.removeRow(row)
return items
def getSelectedRowsFast(self):
selRows = []
for item in self.selectedItems():
if item.row() not in selRows:
selRows.append(item.row())
return selRows
def dropOn(self, event):
index = self.indexAt(event.pos())
if not index.isValid():
return False, self.rowCount(), 0, index
return True, index.row(), index.column(), index
class TOTPConfig:
def __init__(self):
self.configs = self.load_config()
def load_config(self):
try:
with open(CONFIG_FILE, "r") as f:
content = f.read().strip()
if content:
return json.loads(content)
else:
return []
except FileNotFoundError:
return []
def save_config(self):
with open(CONFIG_FILE, "w") as f:
json.dump(self.configs, f, indent=4)
def add_config(self, name, secret, prefix="", suffix=""):
self.configs.append({"name": name, "secret": secret, "prefix": prefix, "suffix": suffix})
self.save_config()
return True
def update_config(self, index, name, secret, prefix="", suffix=""):
self.configs[index] = {"name": name, "secret": secret, "prefix": prefix, "suffix": suffix}
self.save_config()
return True
def delete_config(self, index):
del self.configs[index]
self.save_config()
class MainApp(QDialog):
def __init__(self):
super().__init__()
self.config_manager = TOTPConfig()
self.initUI()
self.copy_timer = QTimer(self)
self.copy_timer.setSingleShot(True)
self.copy_timer.timeout.connect(self.perform_copy)
def initUI(self):
self.setWindowTitle("aidex")
self.setGeometry(300, 300, 450, 400)
self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setWindowOpacity(0.85)
self.setAttribute(Qt.WA_TranslucentBackground)
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.button_layout = QHBoxLayout()
spacer = QSpacerItem(330, 0, QSizePolicy.Fixed, QSizePolicy.Minimum)
self.button_layout.addItem(spacer)
self.add_button = QPushButton("+", self)
self.add_button.clicked.connect(lambda: self.show_config_dialog("", "", "", "", is_new=True))
self.add_button.setFixedWidth(42)
self.add_button.setFocusPolicy(Qt.NoFocus)
self.button_layout.addWidget(self.add_button)
spacer = QSpacerItem(7, 0, QSizePolicy.Fixed, QSizePolicy.Minimum)
self.button_layout.addItem(spacer)
self.quit_button = QPushButton("×", self)
self.quit_button.clicked.connect(lambda: quit())
self.quit_button.setFixedWidth(42)
self.quit_button.setFocusPolicy(Qt.NoFocus)
self.button_layout.addWidget(self.quit_button)
self.button_layout.addStretch()
self.layout.addLayout(self.button_layout, Qt.AlignRight)
self.table_widget = DraggableTableWidget(0, 4, self)
self.table_widget.setShowGrid(False)
self.table_widget.setHorizontalHeaderLabels(["Name", "TOTP", "Time Left", "Action"])
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.table_widget.horizontalHeader().setSectionResizeMode(2, QHeaderView.Interactive)
self.table_widget.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.table_widget.verticalHeader().setDefaultSectionSize(40)
self.table_widget.setFrameStyle(QFrame.NoFrame)
self.scroll_area = QScrollArea(self)
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(self.table_widget)
self.layout.addWidget(self.scroll_area)
self.icon = QIcon(icon_path)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(self.icon)
self.tray_icon.show()
self.tray_icon.activated.connect(self.tray_icon_clicked)
self.refresh_timer = QTimer(self)
self.refresh_timer.timeout.connect(self.refresh_totp_codes)
self.refresh_timer.start(1000)
self.load_totp_configs()
self.setStyleSheet("""
QPushButton {
font-size: 14px; border-radius: 12px;
}
QPushButton:hover {
border: 2px solid #00ffdf; color: #00ffdf;
}
QTableWidget {
border: 0px; font-size: 15px; border-radius: 15px; margin: 1px;
}
QHeaderView::section {
font-size: 13px;
}
QTableWidget::item {
border-bottom: 0.5px solid #B3B3B3; padding: 5px;
}
QHeaderView::section:first {
border-top-left-radius: 7px;
}
QHeaderView::section:last {
border-top-right-radius: 7px;
}
""")
def move_to_cursor(self):
cursor_pos = QCursor.pos()
screen = QApplication.primaryScreen().availableGeometry()
size = self.geometry()
x = cursor_pos.x() - size.width() // 2
if x < screen.left():
x = screen.left()
elif x + size.width() > screen.right():
x = screen.right() - size.width()
if cursor_pos.y() + size.height() <= screen.bottom():
y = cursor_pos.y() + 15
else:
y = cursor_pos.y() - size.height() - 15
self.move(x, y)
def move_to_cursor(self):
icon_rect = self.tray_icon.geometry()
screen = QApplication.primaryScreen().availableGeometry()
size = self.geometry()
if platform.system() == "Darwin": # macOS
x = icon_rect.center().x() - size.width() // 2
y = icon_rect.bottom() + 5
else: # Windows
x = icon_rect.center().x() - size.width() // 2
y = icon_rect.top() - size.height() - 5
# Cross-border judgment
if x < screen.left():
x = screen.left()
elif x + size.width() > screen.right():
x = screen.right() - size.width()
if y < screen.top():
y = screen.top()
elif y + size.height() > screen.bottom():
y = screen.bottom() - size.height()
self.move(x, y)
def load_totp_configs(self):
self.table_widget.setRowCount(0)
for config in self.config_manager.configs:
self.add_totp_item(config["name"], config["secret"], config["prefix"], config["suffix"])
def add_totp_item(self, name, secret, prefix="", suffix=""):
try:
totp = pyotp.TOTP(secret)
code = totp.now()
time_remaining = totp.interval - time.time() % totp.interval + 1
row_position = self.table_widget.rowCount()
self.table_widget.insertRow(row_position)
name_item = QTableWidgetItem(name)
totp_item = QTableWidgetItem(f"{code}")
time_item = QTableWidgetItem(str(int(time_remaining)))
name_item.setTextAlignment(Qt.AlignCenter)
totp_item.setTextAlignment(Qt.AlignCenter)
time_item.setTextAlignment(Qt.AlignCenter)
action_widget = QWidget(self)
action_layout = QHBoxLayout(action_widget)
action_button = QPushButton("≡", self)
action_button.clicked.connect(lambda: self.show_config_dialog(name, secret, prefix, suffix, row_position))
action_button.setFixedWidth(30)
action_button.setFixedHeight(25)
action_button.setStyleSheet("font-size: 13px; border-radius: 8px;")
action_layout.addStretch()
action_layout.addWidget(action_button)
action_layout.addStretch()
action_layout.setContentsMargins(0, 0, 0, 0)
action_widget.setLayout(action_layout)
self.table_widget.setItem(row_position, 0, name_item)
self.table_widget.setItem(row_position, 1, totp_item)
self.table_widget.setItem(row_position, 2, time_item)
self.table_widget.setCellWidget(row_position, 3, action_widget)
self.table_widget.setRowHeight(row_position, 40)
self.table_widget.resizeColumnsToContents()
self.table_widget.verticalHeader().setHidden(True)
self.table_widget.cellDoubleClicked.connect(self.copy_to_clipboard)
except binascii.Error:
QMessageBox.warning(self, "Error", f"Invalid secret for {name}. Please check the secret and try again.")
def refresh_totp_codes(self):
for row in range(self.table_widget.rowCount()):
if row >= len(self.config_manager.configs):
break
name_item = self.table_widget.item(row, 0)
totp_item = self.table_widget.item(row, 1)
time_item = self.table_widget.item(row, 2)
if name_item and totp_item and time_item:
config = self.config_manager.configs[row]
try:
totp = pyotp.TOTP(config["secret"])
code = totp.now()
time_remaining = totp.interval - time.time() % totp.interval + 1
totp_item.setText(f"{code}")
time_item.setText(str(int(time_remaining)))
except binascii.Error:
totp_item.setText("Invalid secret")
time_item.setText("")
def copy_to_clipboard(self, row):
self.copy_row = row
self.copy_timer.start(300)
def perform_copy(self):
if self.copy_row is not None:
config = self.config_manager.configs[self.copy_row]
totp = pyotp.TOTP(config["secret"])
code = totp.now()
pyperclip.copy(f"{config['prefix']}{code}{config['suffix']}")
self.show_notification(f"Copied: {config['prefix']}{code}{config['suffix']}")
self.copy_row = None
self.table_widget.clearSelection() # clear select
def show_notification(self, message):
self.tray_icon.showMessage("aidex", message, self.icon, 2000)
def show_config_dialog(self, name="", secret="", prefix="", suffix="", row=None, is_new=False):
config_dialog = ConfigDialog(self, name, secret, prefix, suffix, row, is_new)
if config_dialog.exec_() == QDialog.Accepted:
name, secret, prefix, suffix, is_delete = config_dialog.get_data()
secret = correct_secret_padding(secret)
if is_delete:
self.config_manager.delete_config(row)
elif is_new:
self.config_manager.add_config(name, secret, prefix, suffix)
else:
self.config_manager.update_config(row, name, secret, prefix, suffix)
self.load_totp_configs()
apply_stylesheet(QApplication.instance(), theme='dark_teal.xml')
def update_data_model(self):
new_configs = []
for row in range(self.table_widget.rowCount()):
name_item = self.table_widget.item(row, 0)
if name_item:
name = name_item.text()
for config in self.config_manager.configs:
if config['name'] == name:
new_configs.append(config)
break
self.config_manager.configs = new_configs
self.config_manager.save_config()
for row in range(self.table_widget.rowCount()):
name_item = self.table_widget.item(row, 0)
if name_item:
name = name_item.text()
config = next((c for c in self.config_manager.configs if c['name'] == name), None)
if config:
self.create_action_button(row, config["name"], config["secret"], config["prefix"], config["suffix"])
def create_action_button(self, row, name, secret, prefix, suffix):
action_widget = QWidget(self)
action_layout = QHBoxLayout(action_widget)
action_button = QPushButton("≡", self)
action_button.clicked.connect(lambda _, row=row: self.show_config_dialog(name, secret, prefix, suffix, row))
action_button.setFixedWidth(30)
action_button.setFixedHeight(25)
action_button.setStyleSheet("font-size: 13px; border-radius: 8px;")
action_layout.addStretch()
action_layout.addWidget(action_button)
action_layout.addStretch()
action_layout.setContentsMargins(0, 0, 0, 0)
action_widget.setLayout(action_layout)
self.table_widget.setCellWidget(row, 3, action_widget)
def show_action(self):
self.show()
self.raise_()
self.activateWindow()
self.move_to_cursor()
def hide_action(self):
self.hide()
self.table_widget.clearSelection()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(QBrush(QColor(48, 54, 59)))
painter.setPen(Qt.NoPen)
rect = self.rect()
rect.setHeight(rect.height() - 1)
rect.setWidth(rect.width() - 1)
painter.drawRoundedRect(rect, 20, 20)
def tray_icon_clicked(self, reason):
if reason == QSystemTrayIcon.Trigger or reason == QSystemTrayIcon.DoubleClick:
if any(isinstance(widget, ConfigDialog) and widget.isVisible() for widget in self.findChildren(QWidget)):
return
if self.isHidden():
self.show_action()
else:
self.hide_action()
def event(self, event):
if event.type() == QEvent.WindowDeactivate:
if not self.tray_icon.geometry().contains(QCursor.pos()) and not any(isinstance(widget, ConfigDialog) and widget.isVisible() for widget in self.findChildren(QWidget)):
self.hide_action()
return super().event(event)
class ConfigDialog(QDialog):
def __init__(self, parent=None, name="", secret="", prefix="", suffix="", row=None, is_new=False):
super().__init__(parent)
self.parent = parent
self.is_new = is_new
self.row = row
self.is_delete = False
self.setWindowTitle("TOTP Config")
self.setGeometry(400, 400, 300, 200)
self.setWindowIcon(QIcon(icon_path))
self.setWindowOpacity(0.9)
self.layout = QVBoxLayout(self)
self.name_edit = QLineEdit(self)
self.name_edit.setPlaceholderText("Name")
self.name_edit.setText(name)
self.name_edit.setStyleSheet("color: white;")
self.layout.addWidget(self.name_edit)
self.secret_edit = QLineEdit(self)
self.secret_edit.setPlaceholderText("Secret")
self.secret_edit.setText(secret)
self.secret_edit.setStyleSheet("color: white;")
self.layout.addWidget(self.secret_edit)
self.prefix_edit = QLineEdit(self)
self.prefix_edit.setPlaceholderText("Password Prefix")
self.prefix_edit.setText(prefix)
self.prefix_edit.setStyleSheet("color: white;")
self.layout.addWidget(self.prefix_edit)
self.suffix_edit = QLineEdit(self)
self.suffix_edit.setPlaceholderText("Password Suffix")
self.suffix_edit.setText(suffix)
self.suffix_edit.setStyleSheet("color: white;")
self.layout.addWidget(self.suffix_edit)
self.button_layout = QHBoxLayout()
self.save_button = QPushButton("Save", self)
self.save_button.clicked.connect(self.save)
self.button_layout.addWidget(self.save_button)
if not is_new:
self.delete_button = QPushButton("Delete", self)
self.delete_button.clicked.connect(self.delete)
self.button_layout.addWidget(self.delete_button)
self.layout.addLayout(self.button_layout)
def get_data(self):
return (self.name_edit.text(), self.secret_edit.text(), self.prefix_edit.text(), self.suffix_edit.text(), self.is_delete)
def save(self):
secret = correct_secret_padding(self.secret_edit.text())
if not self.validate_secret(secret):
return
self.accept()
def validate_secret(self, secret):
secret = secret.strip().replace(' ', '').upper()
if not secret:
self.parent.show_notification("The secret cannot be empty.")
return False
try:
pyotp.TOTP(secret).now()
return True
except binascii.Error:
self.parent.show_notification("The secret provided is not valid.")
return False
@pyqtSlot()
def delete(self):
reply = QMessageBox.question(self, "Delete", "Are you sure you want to delete this config?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
self.is_delete = True
self.accept()
def main():
app = QApplication(sys.argv)
app.setApplicationName("aidex")
app.setApplicationVersion("1.0")
if sys.platform == "darwin":
from AppKit import NSApp
NSApp.setActivationPolicy_(1)
elif sys.platform == "win32":
from ctypes import windll
windll.shell32.SetCurrentProcessExplicitAppUserModelID('aidex')
apply_stylesheet(app, theme='dark_teal.xml')
window = MainApp()
window.hide()
window.tray_icon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()