-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitlockerTimer.py
More file actions
603 lines (533 loc) · 19.6 KB
/
BitlockerTimer.py
File metadata and controls
603 lines (533 loc) · 19.6 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
# Small always-on-top bar: polls `manage-bde -status` for BitLocker %.
# Right-click → Settings / Exit. Drag to move.
from __future__ import annotations
import json
import locale
import re
import subprocess
import sys
import threading
import time
import tkinter as tk
from pathlib import Path
from typing import Any
CONFIG_NAME = "config.json"
EXAMPLE_CONFIG = "config.example.json"
UI_FONT = ("Segoe UI", 9)
UI_FONT_BOLD = ("Segoe UI", 10, "bold")
DEFAULTS: dict[str, Any] = {
"drive": "C",
"poll_interval_seconds": 10,
"always_on_top": True,
"opacity": 1.0,
"window_width": 260,
"window_height": 44,
"window_x": 10,
"window_y": 10,
"language": "en",
"progress_mode": "inverse",
"exit_when_complete": False,
}
STRINGS: dict[str, dict[str, str]] = {
"en": {
"starting": "Starting…",
"unavailable": "Status unavailable",
"complete": "BitLocker: complete",
"progress": "BitLocker: {pct:.1f}%",
"settings": "Settings",
"exit": "Exit",
"save": "Save",
"cancel": "Cancel",
"drive": "Drive letter",
"interval": "Refresh (seconds)",
"always_top": "Always on top",
"opacity": "Opacity",
"language": "Language",
"mode": "Progress mode",
"mode_inverse": "Decrypt / wait (inverse %)",
"mode_direct": "Encryption (direct %)",
"exit_done": "Exit when complete",
"need_admin": "Open PowerShell as admin",
"bde_failed": "manage-bde error — see console",
},
"tr": {
"starting": "Başlatılıyor…",
"unavailable": "Durum alınamadı",
"complete": "BitLocker: tamamlandı",
"progress": "BitLocker: %{pct:.1f}",
"settings": "Ayarlar",
"exit": "Çıkış",
"save": "Kaydet",
"cancel": "İptal",
"drive": "Sürücü harfi",
"interval": "Yenileme (saniye)",
"always_top": "Her zaman üstte",
"opacity": "Opaklık",
"language": "Dil",
"mode": "İlerleme modu",
"mode_inverse": "Şifre çöz / bekle (ters %)",
"mode_direct": "Şifreleme (doğrudan %)",
"exit_done": "Bitince çık",
"need_admin": "PowerShell'ı yönetici açın",
"bde_failed": "manage-bde hatası",
},
}
PCT_PATTERN = re.compile(
r"(?:Percentage Encrypted|Percent Encrypted|Şifrelenme yüzdesi|"
r"Prozent verschlüsselt|Verschlüsselungsgrad|Pourcentage chiffr[ée]|"
r"Porcentaje cifrado|Percentage versleuteld)\s*:\s*([\d,.]+)\s*%?",
re.IGNORECASE,
)
PCT_FALLBACK = re.compile(r"(?m)^\s*.+?\s*:\s*([\d,.]+)\s*%")
# manage-bde whines without elevation — match a few locales
_ADMIN_HINTS = (
"administrative rights",
"administrator rights",
"administrative privileges",
"elevated command",
"zugriff verweigert",
"administratorrechten",
"accès refusé",
"droits d'administrateur",
)
_ERR_DENY = (
"denied",
"administrator",
"administrative",
"verweigert",
"refusé",
"reddedildi",
"erişim",
"yönetici",
)
def app_dir() -> Path:
# PyInstaller onefile: config must live next to the .exe, not in the temp extract dir
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
def config_path() -> Path:
return app_dir() / CONFIG_NAME
def load_config() -> dict[str, Any]:
data = dict(DEFAULTS)
path = config_path()
if not path.is_file():
return data
try:
blob = json.loads(path.read_text(encoding="utf-8"))
if isinstance(blob, dict):
data.update(blob)
except (json.JSONDecodeError, OSError):
pass
return data
def save_config(cfg: dict[str, Any]) -> None:
out = {k: cfg[k] for k in DEFAULTS if k in cfg}
config_path().write_text(
json.dumps(out, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def tr(cfg: dict[str, Any], key: str, **fmt: Any) -> str:
lang = cfg.get("language") or "en"
if lang not in STRINGS:
lang = "en"
s = STRINGS[lang].get(key) or STRINGS["en"].get(key) or key
return s.format(**fmt) if fmt else s
def decode_cmd_output(raw: bytes) -> str:
preferred = locale.getpreferredencoding(False) or ""
for enc in ("utf-8", preferred, "cp1252", "cp850", "mbcs"):
if not enc:
continue
try:
return raw.decode(enc)
except UnicodeDecodeError:
continue
return raw.decode("utf-8", errors="replace")
def looks_like_access_denied(text: str) -> bool:
u = text.casefold()
if any(h in u for h in _ADMIN_HINTS):
return True
if not re.search(r"(?:error|hata|fehler)\s*:", u):
return False
return any(h in u for h in _ERR_DENY)
def run_manage_bde_status(drive: str) -> tuple[str | None, int]:
letter = (drive or "C").strip().rstrip(":").upper()[:1] or "C"
try:
proc = subprocess.run(
["manage-bde", "-status", f"{letter}:"],
capture_output=True,
timeout=60,
)
except (OSError, subprocess.TimeoutExpired):
return None, -1
raw = (proc.stdout or b"") + b"\n" + (proc.stderr or b"")
return decode_cmd_output(raw), int(proc.returncode)
def parse_bitlocker(output: str | None, progress_mode: str) -> float | None:
if not output:
return None
low = output.casefold()
if re.search(r"fully\s+decrypted", output, re.I) or (
"tamamen" in low and "çözülmüş" in low
):
return 100.0 if progress_mode == "inverse" else 0.0
if re.search(r"fully\s+encrypted", output, re.I) or (
"tamamen" in low and "şifrelenmiş" in low
):
return 100.0 if progress_mode == "direct" else 0.0
m = PCT_PATTERN.search(output)
if not m:
for line in output.splitlines():
if "%" not in line:
continue
if not re.search(
r"encrypt|şifre|chiffr|cifr|verschlüsselt|versleutel",
line,
re.I,
):
continue
hit = re.search(r"([\d,.]+)\s*%", line)
if hit:
m = hit
break
if not m:
m = PCT_FALLBACK.search(output)
if not m:
return None
try:
n = float(m.group(1).replace(",", "."))
except ValueError:
return None
return n if progress_mode == "direct" else 100.0 - n
class BitlockerTimerApp:
def __init__(self) -> None:
self.cfg = load_config()
self.stop = threading.Event()
self.worker: threading.Thread | None = None
self.root = tk.Tk()
self.root.title("BitLocker")
# colors — same family as VS Code-ish dark
self.bg = "#1e1e1e"
self.fg = "#e8e8e8"
self.accent = "#3d9a58"
self.surface = "#2a2a2a"
self.entry_bg = "#252526"
self.btn_bg = "#333333"
self.btn_hover = "#404040"
self.menu_hi = "#3a3a3a"
self.outline = "#464647"
self._install_dark_defaults()
self._place_window()
self.root.configure(bg=self.bg)
self.label = tk.Label(
self.root,
text=tr(self.cfg, "starting"),
font=UI_FONT_BOLD,
fg=self.fg,
bg=self.bg,
cursor="hand2",
)
self.label.pack(expand=True, fill="both", padx=8, pady=6)
self.label.bind("<B1-Motion>", self._drag)
self.label.bind("<Button-3>", self._popup_menu)
self.root.bind("<Button-3>", self._popup_menu)
self._spawn_worker()
def _install_dark_defaults(self) -> None:
# Tk on Win10 loves flashing white widgets unless you stomp the option db
r = self.root
pairs = (
("*Menu.background", self.surface),
("*Menu.foreground", self.fg),
("*Menu.activeBackground", self.menu_hi),
("*Menu.activeForeground", self.fg),
("*Menu.relief", "flat"),
("*Menubutton.background", self.btn_bg),
("*Menubutton.foreground", self.fg),
("*Menubutton.activeBackground", self.btn_hover),
("*Menubutton.activeForeground", self.fg),
("*Menubutton.relief", "flat"),
("*Button.background", self.btn_bg),
("*Button.foreground", self.fg),
("*Button.activeBackground", self.btn_hover),
("*Button.activeForeground", self.fg),
("*Button.relief", "flat"),
("*Button.borderWidth", "0"),
("*Entry.background", self.entry_bg),
("*Entry.foreground", self.fg),
("*Entry.insertBackground", self.fg),
("*Entry.relief", "flat"),
("*Spinbox.background", self.entry_bg),
("*Spinbox.foreground", self.fg),
("*Spinbox.insertBackground", self.fg),
("*Spinbox.buttonBackground", self.btn_bg),
("*Spinbox.relief", "flat"),
("*Toplevel.background", self.bg),
)
for pat, val in pairs:
r.option_add(pat, val)
def _paint_menu(self, menu: tk.Menu) -> None:
menu.configure(
tearoff=0,
bg=self.surface,
fg=self.fg,
activebackground=self.menu_hi,
activeforeground=self.fg,
bd=0,
relief="flat",
font=UI_FONT,
)
def _place_window(self) -> None:
w = int(self.cfg.get("window_width") or DEFAULTS["window_width"])
h = int(self.cfg.get("window_height") or DEFAULTS["window_height"])
x = int(self.cfg.get("window_x") or DEFAULTS["window_x"])
y = int(self.cfg.get("window_y") or DEFAULTS["window_y"])
self.root.geometry(f"{w}x{h}+{x}+{y}")
self.root.attributes("-topmost", bool(self.cfg.get("always_on_top", True)))
try:
a = float(self.cfg.get("opacity") or 1.0)
self.root.attributes("-alpha", max(0.35, min(1.0, a)))
except (TypeError, ValueError):
self.root.attributes("-alpha", 1.0)
self.root.overrideredirect(True)
def _drag(self, e: tk.Event) -> None:
self.root.geometry(f"+{e.x_root}+{e.y_root}")
def _popup_menu(self, e: tk.Event) -> None:
m = tk.Menu(self.root, tearoff=0)
self._paint_menu(m)
m.add_command(label=tr(self.cfg, "settings"), command=self._settings)
m.add_command(label=tr(self.cfg, "exit"), command=self._exit)
try:
m.tk_popup(e.x_root, e.y_root)
finally:
m.grab_release()
def _exit(self) -> None:
self.stop.set()
self.root.destroy()
def _remember_geometry(self) -> None:
g = self.root.geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", g)
if not m:
return
self.cfg["window_width"] = int(m.group(1))
self.cfg["window_height"] = int(m.group(2))
self.cfg["window_x"] = int(m.group(3))
self.cfg["window_y"] = int(m.group(4))
def _settings(self) -> None:
top = tk.Toplevel(self.root)
top.title("BitLocker")
top.configure(bg=self.bg)
top.attributes("-topmost", True)
top.resizable(False, False)
lang = tk.StringVar(value=str(self.cfg.get("language", "en")))
mode = tk.StringVar(value=str(self.cfg.get("progress_mode", "inverse")))
drive = tk.StringVar(value=str(self.cfg.get("drive", "C")))
interval = tk.StringVar(value=str(int(self.cfg.get("poll_interval_seconds", 10))))
on_top = tk.BooleanVar(value=bool(self.cfg.get("always_on_top", True)))
opacity = tk.StringVar(value=str(float(self.cfg.get("opacity", 1.0))))
quit_when_done = tk.BooleanVar(value=bool(self.cfg.get("exit_when_complete", False)))
def label(text: str) -> tk.Label:
return tk.Label(
top, text=text, fg=self.fg, bg=self.bg, anchor="w", font=UI_FONT
)
def skin_entry(w: tk.Entry | tk.Spinbox) -> None:
w.configure(
bg=self.entry_bg,
fg=self.fg,
insertbackground=self.fg,
relief="flat",
borderwidth=1,
highlightthickness=1,
highlightbackground=self.outline,
highlightcolor=self.outline,
font=UI_FONT,
)
def skin_btn(b: tk.Button) -> None:
b.configure(
bg=self.btn_bg,
fg=self.fg,
activebackground=self.btn_hover,
activeforeground=self.fg,
relief="flat",
borderwidth=0,
padx=14,
pady=6,
cursor="hand2",
font=UI_FONT,
highlightthickness=1,
highlightbackground=self.outline,
highlightcolor=self.accent,
)
r = 0
label(tr(self.cfg, "drive")).grid(row=r, column=0, sticky="w", padx=10, pady=(10, 2))
e = tk.Entry(top, textvariable=drive, width=8)
skin_entry(e)
e.grid(row=r, column=1, sticky="e", padx=10, pady=(10, 2))
r += 1
label(tr(self.cfg, "interval")).grid(row=r, column=0, sticky="w", padx=10, pady=2)
sp = tk.Spinbox(top, from_=5, to=600, textvariable=interval, width=8)
skin_entry(sp)
sp.grid(row=r, column=1, sticky="e", padx=10, pady=2)
r += 1
label(tr(self.cfg, "opacity")).grid(row=r, column=0, sticky="w", padx=10, pady=2)
sp_o = tk.Spinbox(
top,
from_=0.35,
to=1.0,
increment=0.05,
format="%.2f",
textvariable=opacity,
width=8,
)
skin_entry(sp_o)
sp_o.grid(row=r, column=1, sticky="e", padx=10, pady=2)
r += 1
chk_opts = dict(
fg=self.fg,
bg=self.bg,
selectcolor=self.surface,
activebackground=self.bg,
activeforeground=self.fg,
highlightthickness=0,
font=UI_FONT,
)
tk.Checkbutton(
top, text=tr(self.cfg, "always_top"), variable=on_top, **chk_opts
).grid(row=r, column=0, columnspan=2, sticky="w", padx=10, pady=2)
r += 1
tk.Checkbutton(
top, text=tr(self.cfg, "exit_done"), variable=quit_when_done, **chk_opts
).grid(row=r, column=0, columnspan=2, sticky="w", padx=10, pady=2)
r += 1
label(tr(self.cfg, "language")).grid(row=r, column=0, sticky="w", padx=10, pady=2)
om = tk.OptionMenu(top, lang, *sorted(STRINGS.keys()))
om.configure(
bg=self.btn_bg,
fg=self.fg,
activebackground=self.btn_hover,
activeforeground=self.fg,
relief="flat",
borderwidth=0,
highlightthickness=1,
highlightbackground=self.outline,
highlightcolor=self.outline,
font=UI_FONT,
padx=6,
pady=2,
)
path = om.cget("menu")
if path:
try:
self._paint_menu(self.root.nametowidget(path))
except tk.TclError:
pass
om.grid(row=r, column=1, sticky="e", padx=10, pady=2)
r += 1
label(tr(self.cfg, "mode")).grid(row=r, column=0, sticky="w", padx=10, pady=2)
f = tk.Frame(top, bg=self.bg)
f.grid(row=r, column=1, sticky="e", padx=10, pady=2)
rb = dict(
fg=self.fg,
bg=self.bg,
selectcolor=self.surface,
activebackground=self.bg,
activeforeground=self.fg,
highlightthickness=0,
font=UI_FONT,
)
tk.Radiobutton(
f, text=tr(self.cfg, "mode_inverse"), variable=mode, value="inverse", **rb
).pack(anchor="e")
tk.Radiobutton(
f, text=tr(self.cfg, "mode_direct"), variable=mode, value="direct", **rb
).pack(anchor="e")
r += 1
row_btns = tk.Frame(top, bg=self.bg)
row_btns.grid(row=r, column=0, columnspan=2, pady=(8, 10))
def save() -> None:
self._remember_geometry()
self.cfg["drive"] = (drive.get() or "C").strip().upper()[:1] or "C"
try:
self.cfg["poll_interval_seconds"] = max(
5, min(600, int(float(interval.get())))
)
except ValueError:
self.cfg["poll_interval_seconds"] = 10
try:
self.cfg["opacity"] = max(
0.35, min(1.0, float(opacity.get().replace(",", ".")))
)
except ValueError:
self.cfg["opacity"] = 1.0
self.cfg["always_on_top"] = on_top.get()
self.cfg["exit_when_complete"] = quit_when_done.get()
self.cfg["language"] = lang.get() if lang.get() in STRINGS else "en"
self.cfg["progress_mode"] = (
mode.get() if mode.get() in ("inverse", "direct") else "inverse"
)
save_config(self.cfg)
self.stop.set()
if self.worker:
self.worker.join(timeout=2.0)
self.stop.clear()
self._place_window()
self.label.config(fg=self.fg)
self._spawn_worker()
top.destroy()
b1 = tk.Button(row_btns, text=tr(self.cfg, "save"), command=save, width=10)
skin_btn(b1)
b1.pack(side="left", padx=4)
b2 = tk.Button(row_btns, text=tr(self.cfg, "cancel"), command=top.destroy, width=10)
skin_btn(b2)
b2.pack(side="left", padx=4)
def _spawn_worker(self) -> None:
self.worker = threading.Thread(target=self._poll, daemon=True)
self.worker.start()
def _poll(self) -> None:
while not self.stop.is_set():
cfg = dict(self.cfg)
drive = str(cfg.get("drive", "C"))
progress_mode = str(cfg.get("progress_mode", "inverse"))
raw, code = run_manage_bde_status(drive)
msg: str | None = None
pct: float | None = None
if raw is None:
msg = "unavailable"
elif looks_like_access_denied(raw):
msg = "need_admin"
else:
pct = parse_bitlocker(raw, progress_mode)
if pct is None:
if code != 0 and re.search(r"ERROR\s*:", raw, re.I):
msg = "bde_failed"
else:
msg = "unavailable"
def refresh() -> None:
if msg:
self.label.config(text=tr(cfg, msg), fg=self.fg)
elif pct is not None and pct >= 99.95:
self.label.config(text=tr(cfg, "complete"), fg=self.accent)
if cfg.get("exit_when_complete"):
self._exit()
elif pct is not None:
self.label.config(text=tr(cfg, "progress", pct=pct), fg=self.fg)
try:
self.root.after(0, refresh)
except tk.TclError:
break
try:
sec = int(cfg.get("poll_interval_seconds", 10))
except (TypeError, ValueError):
sec = 10
sec = max(5, min(600, sec))
if self.stop.wait(timeout=sec):
break
def run(self) -> None:
self.root.mainloop()
def main() -> None:
here = app_dir()
example = here / EXAMPLE_CONFIG
if not config_path().is_file() and example.is_file():
try:
config_path().write_text(example.read_text(encoding="utf-8"), encoding="utf-8")
except OSError:
pass
BitlockerTimerApp().run()
if __name__ == "__main__":
main()