-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.py
More file actions
1293 lines (1113 loc) · 53.2 KB
/
Copy pathtracker.py
File metadata and controls
1293 lines (1113 loc) · 53.2 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
"""
TrueHour — Core tracking engine.
Monitors the active foreground window and records app usage durations.
Includes tamper-resistant time tracking with monotonic clocks and hash chaining.
"""
import logging
import os
import platform as _platform
import sys
import threading
import time
import ctypes as _ctypes
import json
from datetime import datetime, timedelta
from typing import Optional
from appinfo import get_foreground_app_info
from config import get_app_data_dir, DynamicPath
from secure_time import get_detector, reset_detector
def _get_idle_seconds():
"""Return seconds since last mouse/keyboard input (cross-platform)."""
if sys.platform == "win32":
try:
class _LASTINPUTINFO(_ctypes.Structure):
_fields_ = [("cbSize", _ctypes.c_uint), ("dwTime", _ctypes.c_uint)]
lii = _LASTINPUTINFO()
lii.cbSize = _ctypes.sizeof(_LASTINPUTINFO)
_ctypes.windll.user32.GetLastInputInfo(_ctypes.byref(lii))
millis = (_ctypes.windll.kernel32.GetTickCount() - lii.dwTime) & 0xFFFFFFFF
return millis / 1000.0
except Exception:
return 0.0
elif sys.platform == "darwin":
try:
# Load CoreGraphics library via ctypes (requires no extra python packages)
import ctypes.util
lib_path = ctypes.util.find_library("CoreGraphics")
if not lib_path:
lib_path = "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics"
cg = _ctypes.CDLL(lib_path)
# CGEventSourceSecondsSinceLastEventType is double CGEventSourceSecondsSinceLastEventType(int, int)
cg.CGEventSourceSecondsSinceLastEventType.restype = _ctypes.c_double
cg.CGEventSourceSecondsSinceLastEventType.argtypes = [_ctypes.c_int32, _ctypes.c_uint32]
# kCGEventSourceStateCombinedSessionState = 0
# kCGAnyInputEventType = ~0 (0xFFFFFFFF)
idle_seconds = cg.CGEventSourceSecondsSinceLastEventType(0, 0xFFFFFFFF)
return float(idle_seconds)
except Exception:
# Fallback to Quartz (PyObjC) if ctypes CoreGraphics load failed
try:
from Quartz import CGEventSourceSecondsSinceLastEventType, kCGEventSourceStateCombinedSessionState, kCGAnyInputEventType
return float(CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateCombinedSessionState, kCGAnyInputEventType))
except Exception:
return 0.0
return 0.0
# Configure logging for security events
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
if not logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))
logger.addHandler(handler)
# ── Auto-Exclusion Setup ──────────────────────────────────────────────
# Default auto-excluded apps written on first launch only.
# User edits to the file are never overwritten.
_SYSTEM = _platform.system()
if _SYSTEM == "Darwin":
_DEFAULT_AUTO_EXCLUDED = """\
# ══════════════════════════════════════════════════════════════════
# TrueHour — Auto-Excluded Apps (macOS)
# ══════════════════════════════════════════════════════════════════
# Apps listed here are completely invisible to TrueHour.
# They will not appear in the app list, report, timeline, or CSV.
#
# Rules:
# - One application name or process name per line (e.g. Finder)
# - Lines starting with # are comments and are ignored
# - Names are case-insensitive
#
# To stop excluding an app, delete its line or add # in front.
# To exclude a new app, add its name on a new line.
# Changes take effect on the next session start.
# ══════════════════════════════════════════════════════════════════
# ── TrueHour Self-Exclusion ───────────────────────────────────────
TrueHour
# ── macOS Core System UI & Desktop ─────────────────────────────────
Finder
Dock
SystemUIServer
loginwindow
NotificationCenter
ControlCenter
Spotlight
WindowManager
# ── macOS Utilities (brief use, not real work) ────────────────────
Activity Monitor
Terminal
Console
System Settings
System Preferences
Keychain Access
Screen Sharing
# ── Audio & Core services ─────────────────────────────────────────
coreaudiod
screencapture
"""
else:
_DEFAULT_AUTO_EXCLUDED = """\
# ══════════════════════════════════════════════════════════════════
# TrueHour — Auto-Excluded Apps
# ══════════════════════════════════════════════════════════════════
# Apps listed here are completely invisible to TrueHour.
# They will not appear in the app list, report, timeline, or CSV.
#
# Rules:
# - One executable name per line (e.g. explorer.exe)
# - Lines starting with # are comments and are ignored
# - Names are case-insensitive
# - .exe extension is optional
#
# To stop excluding an app, delete its line or add # in front.
# To exclude a new app, add its .exe name on a new line.
# Changes take effect on the next session start.
# ══════════════════════════════════════════════════════════════════
# ── TrueHour Self-Exclusion ───────────────────────────────────────
truehour.exe
truehour
# ── Windows Shell & Desktop ────────────────────────────────────────
explorer.exe
dwm.exe
shellexperiencehost.exe
applicationframehost.exe
startmenuexperiencehost.exe
searchhost.exe
searchindexer.exe
searchapp.exe
widgets.exe
textinputhost.exe
# ── Snipping & Screenshot Tools ───────────────────────────────────
snipping.exe
snippingtool.exe
screensketch.exe
# ── System Services & Background ──────────────────────────────────
svchost.exe
csrss.exe
wininit.exe
winlogon.exe
lsass.exe
services.exe
rundll32.exe
taskhostw.exe
spoolsv.exe
fontdriverhost.exe
sihost.exe
ctfmon.exe
# ── Windows Updates & Maintenance ─────────────────────────────────
tiworker.exe
trustedinstaller.exe
mrt.exe
wuauclt.exe
usoclient.exe
# ── Windows Defender & Security ───────────────────────────────────
msmpeng.exe
nissrv.exe
securityhealthsystray.exe
securityhealthservice.exe
smartscreen.exe
# ── Audio & Volume ────────────────────────────────────────────────
sndvol.exe
audiodg.exe
realtek.exe
# ── Input & Language ──────────────────────────────────────────────
TabTip.exe
InputMethod.exe
# ── System Utilities (brief use, not real work) ───────────────────
taskmgr.exe
dxdiag.exe
msinfo32.exe
msiexec.exe
consent.exe
# ── Quick Calculators & Clocks (optional) ─────────────────────────
# Uncomment below if you want to exclude these:
# calculator.exe
# calc.exe
# clock.exe
# ── Terminal / Command Line ───────────────────────────────────────
# These are commented out by default because developers may use them.
# Uncomment to exclude:
# cmd.exe
# powershell.exe
# pwsh.exe
# windowsterminal.exe
# conhost.exe
# ── Development Runtimes ──────────────────────────────────────────
# Commented out — uncomment if these run silently in background for you:
# python.exe
# pythonw.exe
# node.exe
# docker.exe
"""
AUTO_EXCLUDE_FILE = DynamicPath(lambda: os.path.join(get_app_data_dir(), "auto_excluded_apps.txt"))
ACTIVE_SESSION_FILE = DynamicPath(lambda: os.path.join(get_app_data_dir(), "active_session.json"))
_AUTO_EXCLUDED_EXES = set() # must be declared before any function references it
_AUTO_EXCLUDED_LOCK = threading.Lock() # thread-safe access to _AUTO_EXCLUDED_EXES
def create_auto_excluded_if_missing():
"""Generate default auto_excluded_apps.txt on first launch only.
If file already exists, make sure all default system apps are present, but don't overwrite user edits."""
if os.path.exists(AUTO_EXCLUDE_FILE):
try:
with open(AUTO_EXCLUDE_FILE, "r", encoding="utf-8") as f:
content = f.read()
content_lower = content.lower()
# Extract all default active executables/apps from _DEFAULT_AUTO_EXCLUDED
default_apps = []
is_windows = _platform.system() == "Windows"
for line in _DEFAULT_AUTO_EXCLUDED.splitlines():
line = line.strip()
if line and not line.startswith("#"):
exe = line.lower()
if is_windows and not exe.endswith(".exe"):
exe += ".exe"
default_apps.append((line, exe))
missing_additions = []
for raw_name, exe_name in default_apps:
base_name = exe_name[:-4] if (is_windows and exe_name.endswith(".exe")) else exe_name
# Check if this app/process is present in the file
if base_name not in content_lower:
missing_additions.append(raw_name)
if missing_additions:
with open(AUTO_EXCLUDE_FILE, "a", encoding="utf-8") as f:
f.write("\n# ── Automatically Excluded Apps (Added via update) ──\n")
for app in missing_additions:
f.write(f"{app}\n")
except Exception as e:
logger.warning(f"Failed to check/update existing auto-exclude file: {e}")
return
try:
dirpath = os.path.dirname(AUTO_EXCLUDE_FILE)
if dirpath:
# Validate directory path to prevent path traversal
abs_dir = os.path.abspath(dirpath)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_dir.startswith(app_data_dir):
logger.error(f"Invalid auto-exclude directory path: {dirpath}")
return
os.makedirs(dirpath, exist_ok=True)
with open(AUTO_EXCLUDE_FILE, "w", encoding="utf-8") as f:
f.write(_DEFAULT_AUTO_EXCLUDED)
except OSError as e:
logger.warning(f"Failed to create auto-exclude file: {e}")
def _load_auto_excluded():
"""Load auto_excluded_apps.txt into _AUTO_EXCLUDED_EXES set."""
global _AUTO_EXCLUDED_EXES
_AUTO_EXCLUDED_EXES = set() # reset before loading
if not os.path.exists(AUTO_EXCLUDE_FILE):
return
try:
# Validate file path to prevent path traversal
abs_file = os.path.abspath(AUTO_EXCLUDE_FILE)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_file.startswith(app_data_dir):
logger.error(f"Invalid auto-exclude file path: {AUTO_EXCLUDE_FILE}")
return
with open(AUTO_EXCLUDE_FILE, "r", encoding="utf-8") as f:
for line in f:
line = line.strip().lower()
if line and not line.startswith("#") and line[0].isalnum():
if _SYSTEM == "Windows" and not line.endswith(".exe"):
line += ".exe"
_AUTO_EXCLUDED_EXES.add(line)
except (OSError, IOError) as e:
logger.warning(f"Failed to load auto-exclude file: {e}")
def reload_auto_excluded():
"""
Reload auto_excluded_apps.txt into _AUTO_EXCLUDED_EXES.
Changes take effect on the next app switch in _poll_loop.
The currently tracked app is never interrupted.
"""
global _AUTO_EXCLUDED_EXES, _auto_excluded_loaded
new_set = set()
if os.path.exists(AUTO_EXCLUDE_FILE):
try:
# Validate file path to prevent path traversal
abs_file = os.path.abspath(AUTO_EXCLUDE_FILE)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_file.startswith(app_data_dir):
logger.error(f"Invalid auto-exclude file path during reload: {AUTO_EXCLUDE_FILE}")
return False
with open(AUTO_EXCLUDE_FILE, "r", encoding="utf-8") as f:
for line in f:
line = line.strip().lower()
if line and not line.startswith("#") and line[0].isalnum():
if _SYSTEM == "Windows" and not line.endswith(".exe"):
line += ".exe"
new_set.add(line)
except (OSError, IOError) as e:
logger.warning(f"Failed to reload auto-exclude file: {e}")
return False # File read failed — keep existing exclusions
# Swap atomically using module-level lock
with _AUTO_EXCLUDED_LOCK:
_AUTO_EXCLUDED_EXES = new_set
_auto_excluded_loaded = True
return True # Success
_auto_excluded_loaded = False
def _is_auto_excluded(exe_path):
"""Return True if this exe should be completely ignored by the tracker."""
global _auto_excluded_loaded
if not _auto_excluded_loaded:
try:
create_auto_excluded_if_missing()
_load_auto_excluded()
except Exception as e:
logger.warning(f"Failed lazy load auto excluded: {e}")
_auto_excluded_loaded = True
if exe_path:
exe_name = os.path.basename(exe_path).lower()
if exe_name in ("truehour.exe", "truehour"):
return True
# Fast path: check set membership without lock (set lookups are thread-safe for reads)
return exe_name in _AUTO_EXCLUDED_EXES
return False
# Deferred from module load to lazy execution inside _is_auto_excluded
SETTINGS_FILE = DynamicPath(lambda: os.path.join(get_app_data_dir(), "settings.json"))
TAGS_FILE = DynamicPath(lambda: os.path.join(get_app_data_dir(), "tags.json"))
class TagManager:
"""Manages application project/category tags locally and thread-safely."""
DEFAULT_PROJECTS = ["Development", "Design", "Research", "Documentation", "Communication", "Management", "Unassigned"]
# Offline keyword lists
KEYWORDS = {
"Development": ["code", "studio", "compiler", "ide", "git", "docker", "sublime", "debugger", "terminal", "powershell", "python", "node", "npm", "cargo", "msbuild", "visual studio", "pycharm", "intellij", "vscode"],
"Design": ["photoshop", "illustrator", "design", "draw", "cad", "paint", "premiere", "blend", "creative", "maya", "blender", "canvas", "figma", "sketch", "invision", "rendering", "image editor"],
"Documentation": ["word", "excel", "pdf", "document", "notion", "obsidian", "writer", "spreadsheet", "powerpoint", "slides", "notes", "acrobat", "typora", "logseq"],
"Communication": ["slack", "teams", "discord", "zoom", "outlook", "whatsapp", "messenger", "skype", "telegram", "thunderbird", "mail", "chat", "meeting"],
"Research": ["chrome", "firefox", "edge", "safari", "browser", "google", "search", "wikipedia", "navigator", "opera", "brave"],
"Management": ["project", "jira", "trello", "asana", "clickup", "monday.com", "board", "gantt", "backlog"]
}
def __init__(self):
self.lock = threading.Lock()
self.projects = list(self.DEFAULT_PROJECTS)
self.mappings = {}
self.dirty = False
self._load_tags()
def _load_tags(self):
if not os.path.exists(TAGS_FILE):
self._save_tags(force=True)
return
try:
with open(TAGS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
self.projects = data.get("projects", list(self.DEFAULT_PROJECTS))
# Ensure "Unassigned" is always present
if "Unassigned" not in self.projects:
self.projects.append("Unassigned")
self.mappings = data.get("mappings", {})
except Exception as e:
logger.warning(f"Failed to load tags config: {e}")
self.projects = list(self.DEFAULT_PROJECTS)
self.mappings = {}
def _save_tags(self, force=False):
if not force:
self.dirty = True
return
try:
dirpath = os.path.dirname(TAGS_FILE)
if dirpath:
os.makedirs(dirpath, exist_ok=True)
temp_file = TAGS_FILE + ".tmp"
with open(temp_file, "w", encoding="utf-8") as f:
json.dump({
"projects": self.projects,
"mappings": self.mappings
}, f, indent=2, ensure_ascii=False)
os.replace(temp_file, TAGS_FILE)
self.dirty = False
except Exception as e:
logger.warning(f"Failed to save tags config: {e}")
def save_if_dirty(self):
with self.lock:
if self.dirty:
self._save_tags(force=True)
def get_tag(self, app_name: str, exe_path: str = "") -> str:
"""Get tag for app. If not mapped, runs offline heuristics + asynchronous online fallback in background."""
key = app_name.lower().strip()
with self.lock:
if key in self.mappings:
return self.mappings[key]
# Temporary placeholder to prevent spawning multiple threads
self.mappings[key] = "Unassigned"
self.dirty = True
def run_matching_bg():
matched_tag = self._match_offline(app_name, exe_path)
if matched_tag:
with self.lock:
self.mappings[key] = matched_tag
self.dirty = True
self.save_if_dirty()
logger.info(f"Offline categorization succeeded for '{app_name}' -> '{matched_tag}'")
return
self._fetch_and_update_tag_online(app_name, exe_path)
threading.Thread(target=run_matching_bg, daemon=True).start()
return "Unassigned"
def set_tag(self, app_name: str, tag: str):
key = app_name.lower().strip()
with self.lock:
if tag in self.projects or tag == "Unassigned":
self.mappings[key] = tag
self._save_tags(force=True)
def add_project(self, project: str) -> bool:
project = project.strip()
if not project:
return False
with self.lock:
if project not in self.projects:
self.projects.append(project)
self._save_tags(force=True)
return True
return False
def remove_project(self, project: str) -> bool:
if project == "Unassigned":
return False # Protect Unassigned
with self.lock:
if project in self.projects:
self.projects.remove(project)
# Remap apps that were in this project to "Unassigned"
for k, v in list(self.mappings.items()):
if v == project:
self.mappings[k] = "Unassigned"
self._save_tags(force=True)
return True
return False
def _match_offline(self, app_name: str, exe_path: str) -> Optional[str]:
"""Offline token-based scoring heuristic matching."""
app_name_lower = app_name.lower().strip()
exe_name = ""
desc_lower = ""
company_lower = ""
product_lower = ""
if exe_path:
exe_name = os.path.basename(exe_path).lower()
if exe_name.endswith(".exe"):
exe_name = exe_name[:-4]
# Local imports to prevent circular dependency
from appinfo import _get_file_description, get_company_name, get_product_name
desc = _get_file_description(exe_path)
if desc:
desc_lower = desc.lower().strip()
comp = get_company_name(exe_path)
if comp:
company_lower = comp.lower().strip()
prod = get_product_name(exe_path)
if prod:
product_lower = prod.lower().strip()
scores = {cat: 0.0 for cat in self.KEYWORDS}
# 1. High priority company/brand mappings
if "adobe" in company_lower or "adobe" in product_lower or "photoshop" in app_name_lower or "illustrator" in app_name_lower:
scores["Design"] += 5.0
if "jetbrains" in company_lower or "intellij" in product_lower or "pycharm" in product_lower or "webstorm" in product_lower:
scores["Development"] += 5.0
if "autodesk" in company_lower or "autocad" in product_lower:
scores["Design"] += 5.0
if "slack" in app_name_lower or "slack" in exe_name:
scores["Communication"] += 5.0
if "discord" in app_name_lower or "discord" in exe_name:
scores["Communication"] += 5.0
if "zoom" in app_name_lower or "zoom" in exe_name:
scores["Communication"] += 5.0
if "figma" in app_name_lower or "figma" in exe_name:
scores["Design"] += 5.0
if "github" in company_lower or "github" in product_lower or "git" in exe_name:
scores["Development"] += 5.0
# 2. Tokenize all input strings
all_texts = [app_name_lower, exe_name, desc_lower, product_lower, company_lower]
all_tokens = set()
for text in all_texts:
if text:
clean_text = "".join(c if c.isalnum() else " " for c in text)
all_tokens.update(clean_text.split())
# 3. Check tokens against KEYWORDS
for category, words in self.KEYWORDS.items():
for word in words:
# Exact token match
if word in all_tokens:
scores[category] += 3.0
else:
# Substring match within individual tokens
for token in all_tokens:
if len(token) > len(word) and word in token:
scores[category] += 1.0
break
# 4. Find category with the maximum score using tie-breaker priority order
max_score = 0.0
best_category = None
priority = ["Development", "Design", "Documentation", "Communication", "Research", "Management"]
for category in priority:
if scores.get(category, 0.0) > max_score:
max_score = scores[category]
best_category = category
if max_score > 0.0:
return best_category
return None
def _fetch_and_update_tag_online(self, app_name: str, exe_path: str):
"""Asynchronously query DuckDuckGo and update mapping on success."""
try:
import urllib.request
import urllib.parse
import ssl
# Use app name or file description for better search accuracy
search_query = app_name
if exe_path:
from appinfo import _get_file_description
desc = _get_file_description(exe_path)
if desc and len(desc) > 3:
search_query = desc
url = f"https://api.duckduckgo.com/?q={urllib.parse.quote(search_query)}&format=json&no_html=1&skip_disambig=1"
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) TrueHour/1.0'})
# Create SSL context with certificate verification (matches secure_time.py)
ssl_context = ssl.create_default_context()
# Query DuckDuckGo API with SSL verification and 3.0s timeout
with urllib.request.urlopen(req, timeout=3.0, context=ssl_context) as response:
if response.status == 200:
data = json.loads(response.read().decode('utf-8'))
abstract = data.get("AbstractText", "") or data.get("Abstract", "")
if abstract:
abstract_lower = abstract.lower()
# Run our keyword matcher against the online description
matched_tag = None
for category, words in self.KEYWORDS.items():
for word in words:
if word in abstract_lower:
matched_tag = category
break
if matched_tag:
break
if matched_tag:
key = app_name.lower().strip()
with self.lock:
self.mappings[key] = matched_tag
self._save_tags(force=True)
logger.info(f"Online categorization succeeded for '{app_name}' -> '{matched_tag}'")
except ssl.SSLCertVerificationError as e:
logger.warning(f"SSL certificate verification failed for DuckDuckGo API: {e}")
except Exception as e:
logger.debug(f"Online categorization background query failed for {app_name}: {e}")
class SessionStorage:
"""Handles serialization and persistence of tracking sessions."""
@staticmethod
def save_state(tracker: 'AppTracker', filepath: str):
try:
with tracker._lock:
state = {
"session_start": tracker.session_start.timestamp() if tracker.session_start else None,
"session_name": tracker.session_name,
"app_times": tracker.app_times.copy(),
"app_included": tracker.app_included.copy(),
"app_exe_paths": tracker.app_exe_paths.copy(),
"timeline": [
{"app": t["app"], "start": t["start"].timestamp(), "end": t["end"].timestamp()}
for t in tracker.timeline
],
"paused": tracker.paused,
"_pause_start": tracker._pause_start,
"_total_paused_time": tracker._total_paused_time,
"_current_app": tracker._current_app,
"_current_start": tracker._current_start,
"_current_block_start": tracker._current_block_start,
"_current_block_active": tracker._current_block_active
}
# Atomic file swap
temp_file = filepath + ".tmp"
with open(temp_file, "w", encoding="utf-8") as f:
json.dump(state, f)
os.replace(temp_file, filepath)
except Exception as e:
logger.warning(f"Failed to save active state: {e}")
class AppTracker:
"""Tracks which application is in the foreground and for how long."""
def __init__(self, poll_interval=1.0, min_track_seconds=2):
self.poll_interval = poll_interval
self.min_track_seconds = min_track_seconds
# Session state
self.running = False
self.paused = False
self.session_start = None
self.session_end = None
self._pause_start = None
self._total_paused_time = 0
self._last_save_time = 0
self.is_recovered = False
self.session_name = ""
self.save_interval = 10 # Default backup interval
# {app_name: total_seconds}
self.app_times = {}
# {app_name: bool} — True = included
self.app_included = {}
# {app_name: exe_path} — for icon extraction
self.app_exe_paths = {}
# Timeline: list of {"app", "start", "end"}
self.timeline = []
# Current tracking
self._current_app = None
self._current_start = None
self._current_block_start = None
self._current_block_active = 0
self._thread = None
self._lock = threading.Lock()
# Callbacks
self.on_update = None # called each poll tick
# Persistent Exclusions
self.persistent_excluded = set()
self._load_settings()
self.tag_manager = TagManager()
# Idle auto-pause
self.idle_threshold_seconds = 0 # 0 = disabled
self._idle_paused = False
# Distraction auto-pause
self.enable_distraction_auto_pause = False
self.distraction_apps = []
self._distraction_paused = False
# Security: Time tamper detection
self.security_detector = None
self.integrity_warnings = []
# Resume tracking: snapshot of app_times at the moment a past session was resumed.
# None = fresh start or crash recovery. dict = resumed from Session Manager.
self.resume_snapshot = None
def _load_settings(self):
if os.path.exists(SETTINGS_FILE):
try:
# Validate file path to prevent path traversal
abs_file = os.path.abspath(SETTINGS_FILE)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_file.startswith(app_data_dir):
logger.error(f"Invalid settings file path: {SETTINGS_FILE}")
return
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
self.persistent_excluded = set(data.get("excluded_apps", []))
except (OSError, IOError, json.JSONDecodeError) as e:
logger.warning(f"Failed to load settings: {e}")
def _save_settings(self):
try:
dirpath = os.path.dirname(SETTINGS_FILE)
if dirpath:
# Validate directory path to prevent path traversal
abs_dir = os.path.abspath(dirpath)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_dir.startswith(app_data_dir):
logger.error(f"Invalid settings directory path: {dirpath}")
return
os.makedirs(dirpath, exist_ok=True)
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump({"excluded_apps": list(self.persistent_excluded)}, f, indent=2)
except (OSError, IOError) as e:
logger.warning(f"Failed to save settings: {e}")
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def start(self, session_name=""):
"""Begin a tracking session."""
if self.running:
return
# Initialize security detector for this session
reset_detector()
self.security_detector = get_detector()
self.security_detector.start_session()
self.running = True
self.paused = False
self.session_start = datetime.now()
self.session_end = None
self._pause_start = None
self._total_paused_time = 0
self._last_save_time = time.time()
self.is_recovered = False
self.session_name = session_name
self.app_times.clear()
self.app_included.clear()
self.app_exe_paths.clear()
self.timeline.clear()
self._current_app = None
self._current_start = None
self._current_block_start = None
self._current_block_active = 0
self.integrity_warnings.clear()
self.resume_snapshot = None # Fresh start — no previous session
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
self._thread.start()
def stop(self):
"""End the tracking session and finalize data."""
if not self.running:
return
self.running = False
self.session_end = datetime.now()
# Flush current app
self._flush_current()
if self.paused and self._pause_start:
self._total_paused_time += (time.time() - self._pause_start)
self._pause_start = None
if self._thread:
self._thread.join(timeout=0.1) # Non-blocking: thread exits via running flag
self._thread = None
# Finalize security detector
if self.security_detector:
security_report = self.security_detector.end_session()
if security_report["trust_score"] < 70:
self.integrity_warnings.append({
"type": "LOW_TRUST_SCORE",
"score": security_report["trust_score"],
"events_count": security_report.get("tamper_events_count", len(security_report.get("tamper_events", [])))
})
self.tag_manager.save_if_dirty()
if os.path.exists(ACTIVE_SESSION_FILE):
try:
# Validate file path before deletion
abs_file = os.path.abspath(ACTIVE_SESSION_FILE)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_file.startswith(app_data_dir):
logger.error(f"Invalid active session file path: {ACTIVE_SESSION_FILE}")
else:
os.remove(ACTIVE_SESSION_FILE)
except OSError as e:
logger.warning(f"Failed to remove active session file: {e}")
def get_security_status(self):
"""Return current security/integrity status of the session."""
if not self.security_detector:
return {"status": "NOT_STARTED", "trust_level": "UNKNOWN"}
report = self.security_detector.get_session_report()
return {
"status": "ACTIVE" if self.running else "ENDED",
"trust_score": report["trust_score"],
"trust_level": report["trust_level"],
"chain_valid": report["chain_valid"],
"tamper_events": report["tamper_events_count"],
"warnings": self.integrity_warnings
}
def recover_session(self):
if not os.path.exists(ACTIVE_SESSION_FILE):
return False
try:
# Validate file path to prevent path traversal
abs_file = os.path.abspath(ACTIVE_SESSION_FILE)
app_data_dir = os.path.abspath(get_app_data_dir())
if not abs_file.startswith(app_data_dir):
logger.error(f"Invalid active session file path: {ACTIVE_SESSION_FILE}")
return False
with open(ACTIVE_SESSION_FILE, "r", encoding="utf-8") as f:
state = json.load(f)
self.session_start = datetime.fromtimestamp(state["session_start"])
self.app_times = state["app_times"]
self.app_included = state.get("app_included", {})
self.app_exe_paths = state.get("app_exe_paths", {})
self.timeline = []
for t in state["timeline"]:
self.timeline.append({
"app": t["app"],
"start": datetime.fromtimestamp(t["start"]),
"end": datetime.fromtimestamp(t["end"])
})
self.paused = state.get("paused", False)
self._pause_start = state.get("_pause_start")
self._total_paused_time = state.get("_total_paused_time", 0)
c_app = state.get("_current_app")
c_start = state.get("_current_start")
c_block_start = state.get("_current_block_start")
c_block_active = state.get("_current_block_active", 0)
if c_app and c_block_start:
crash_time = os.path.getmtime(ACTIVE_SESSION_FILE)
if c_start:
elapsed = crash_time - c_start
if elapsed > 0:
if elapsed > self.poll_interval + 2.0:
elapsed = self.poll_interval
if self.app_included.get(c_app, True):
self.app_times[c_app] = self.app_times.get(c_app, 0) + elapsed
c_block_active += elapsed
if c_block_active >= self.min_track_seconds:
self.timeline.append({
"app": c_app,
"start": datetime.fromtimestamp(c_block_start),
"end": datetime.fromtimestamp(c_block_start + c_block_active)
})
self._current_app = None
self._current_start = None
self.running = True
self.session_end = None
self.is_recovered = True
# Adjust paused time to account for the gap while the app was closed
now = datetime.now()
tracked_duration = sum(self.app_times.values())
self._total_paused_time = max(0, (now - self.session_start).total_seconds() - tracked_duration)
if self.paused:
self._pause_start = time.time() # reset so UI shows correct paused state
self.resume_snapshot = None # Crash recovery — not a user-initiated resume
self._last_save_time = time.time()
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
self._thread.start()
return True
except (OSError, IOError, json.JSONDecodeError, KeyError, TypeError, ValueError) as e:
logger.warning(f"Failed to recover session: {e}")
return False
def load_from_report(self, filepath):
from report import load_session_json
try:
rep = load_session_json(filepath)
self.session_name = rep.get("session_name", "")
self.session_start = datetime.strptime(rep['date'] + " " + rep['start'], "%Y-%m-%d %H:%M:%S")
self.session_end = None
self.app_exe_paths = rep.get("app_exe_paths", {})
# Load app_times but strip any auto-excluded apps from old sessions
self.app_times = {}
self.app_included = {}
for a in rep['apps']:
name = a['name']
secs = a['seconds']
included = not a['excluded']
exe_path = self.app_exe_paths.get(name, "")
if not _is_auto_excluded(exe_path) and name != "[Idle]":
self.app_times[name] = secs
self.app_included[name] = included
self.timeline.clear()
for t in rep['timeline']:
# load_session_json returns datetime objects; handle both formats
if isinstance(t['start'], datetime):
t_start = t['start']
t_end = t['end']
else:
t_start = datetime.strptime(rep['date'] + " " + t['start'], "%Y-%m-%d %H:%M:%S")
t_end = datetime.strptime(rep['date'] + " " + t['end'], "%Y-%m-%d %H:%M:%S")
# Midnight crossover guard
if t_end <= t_start:
t_end += timedelta(days=1)
self.timeline.append({
"app": t['app'],
"start": t_start,
"end": t_end
})
self._current_app = None
self._current_start = None
self._current_block_start = None
self._current_block_active = 0
self.integrity_warnings = []
# Initialize security detector for resumed session
reset_detector()
self.security_detector = get_detector()
self.security_detector.start_session()
# Important: Adjust paused time so the timer respects the saved duration
# (Now - Start) - Paused = Saved_Duration
now = datetime.now()
self._total_paused_time = (now - self.session_start).total_seconds() - rep['total_seconds']
self.paused = False
self._pause_start = None
self.running = True
self.is_recovered = False
# Snapshot current app_times BEFORE the poll thread starts adding new time.
# Anything beyond these values at stop time = new activity from this resume.
self.resume_snapshot = dict(self.app_times)
self._last_save_time = time.time()
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
self._thread.start()
return True
except (OSError, IOError, json.JSONDecodeError, KeyError, TypeError, ValueError) as e:
logger.warning(f"Failed to load from report: {e}")
return False
def toggle_pause(self, is_idle=False):
with self._lock:
if not self.running: