forked from Lenochxd/WebDeck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
287 lines (237 loc) · 9.41 KB
/
main.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
import ctypes
import sys
if not ctypes.windll.shell32.IsUserAnAdmin():
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
sys.exit()
exit()
import pystray
from pystray import MenuItem as item
from PIL import Image, ImageTk
import os
import win32gui, win32con
import win32com.client
import time
import subprocess
import socket
import webbrowser
import json
import qrcode
import tkinter as tk
from io import BytesIO
import webview
def reload_config():
port = 5000
black_theme = "true"
open_in_integrated_browser = "true"
language = "en_US"
if os.path.exists("config.json"):
with open('config.json', encoding="utf-8") as f:
config = json.load(f)
settings = config.get('settings', {})
integrated_browser_key = 'open-settings-in-integrated-browser'
browser_key = 'open-settings-in-browser'
if browser_key in config['settings']:
settings[integrated_browser_key] = 'false' if open_in_integrated_browser else 'true'
settings.pop(browser_key, None)
open_in_integrated_browser = settings.get(integrated_browser_key, 'false') == 'true'
print(open_in_integrated_browser)
with open('config.json', 'w', encoding="utf-8") as json_file:
json.dump(config, json_file, indent=4)
port = config['url']['port']
black_theme = config['front']['black-theme']
language = config['settings']['language']
return port, black_theme, language, open_in_integrated_browser
port, black_theme, language, open_in_integrated_browser = reload_config()
wmi = win32com.client.GetObject("winmgmts:")
processes = wmi.InstancesOf("Win32_Process")
if_webdeck = False
if getattr(sys, 'frozen', False):
wd_count = 0
for process in processes:
if 'webdeck' in process.Properties_('Name').Value.lower().strip() or \
'wd_' in process.Properties_('Name').Value.lower().strip():
wd_count += 1
if wd_count > 1:
time.sleep(1)
wmi = win32com.client.GetObject("winmgmts:")
processes = wmi.InstancesOf("Win32_Process")
if_webdeck = False
wd_count = 0
for process in processes:
if 'webdeck' in process.Properties_('Name').Value.lower().strip():
wd_count += 1
if wd_count > 1:
if_webdeck = True
wmi = win32com.client.GetObject("winmgmts:")
processes = wmi.InstancesOf("Win32_Process")
wd_count = 0
for process in processes:
if 'wd_' in process.Properties_('Name').Value.lower().strip():
wd_count += 1
if wd_count == 0:
subprocess.Popen(['WD_main.exe'])
if if_webdeck == False:
icon = None
window = None
if getattr(sys, 'frozen', False):
#subprocess.Popen(['WD_start.exe'])
wmi = win32com.client.GetObject("winmgmts:")
processes = wmi.InstancesOf("Win32_Process")
if_webdeck = False
wd_count = 0
for process in processes:
if 'wd_' in process.Properties_('Name').Value.lower().strip():
wd_count += 1
if wd_count == 0:
subprocess.Popen(['WD_main.exe'])
else:
subprocess.Popen('python main_server.py', shell=True)
def load_lang_file(lang):
lang_dictionary = {}
lang_path = f"static/files/langs/{lang}.lang"
if not os.path.isfile(f"static/files/langs/{lang}.lang"):
for root, dirs, files in os.walk('static/files/langs'):
for file in files:
if file.endswith('.lang') and file.startswith(lang):
lang_path = f"static/files/langs/{file}"
with open(lang_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
if line.replace(' ', '').replace('\n','') != '' and not line.startswith('//') and not line.startswith('#'):
try:
key, value = line.strip().split('=')
lang_dictionary[key] = value.strip()
except:
print(line)
return lang_dictionary
text = load_lang_file(language)
def exit_program():
global icon, window
wmi = win32com.client.GetObject("winmgmts:")
processes = wmi.InstancesOf("Win32_Process")
processes_to_kill = [
"WD_main.exe",
"WD_start.exe",
"nircmd.exe",
"WebDeck.exe"
]
for process_name in processes_to_kill:
try:
subprocess.Popen(f"taskkill /f /IM {process_name}", shell=True)
except Exception as e:
print(f"Failed to terminate process {process_name}: {e}")
for process in processes:
if process.Properties_('Name').Value.replace('.exe','').lower().strip() in ["wd_main","wd_start","nircmd","webdeck"]:
print(f"Stopping process: {process.Properties_('Name').Value}")
try:
result = process.Terminate()
except TypeError:
pass
if result == 0:
print("Process terminated successfully.")
else:
print("Failed to terminate process.")
if not getattr(sys, 'frozen', False):
try:
subprocess.Popen("taskkill /f /IM python.exe", shell=True)
except Exception as e:
print(f"Failed to terminate process {process_name}: {e}")
close_window()
icon.stop() # Stop Tray Icon
sys.exit()
exit()
def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Any address and port, here we use Google DNS
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
finally:
s.close()
return local_ip
local_ip = get_local_ip()
def fix_firewall_permission():
command = [
"powershell",
"-NoProfile",
"New-NetFirewallRule",
"-DisplayName",
'"WebDeck"',
"-Direction",
"Inbound",
"-Program",
f'"{sys.executable}"',
"-Action",
"Allow",
]
subprocess.run(command)
def open_config():
port, black_theme, language, open_in_integrated_browser = reload_config()
if open_in_integrated_browser == True:
webview.create_window('WebDeck Config', url=f'http://{local_ip}:{port}?config=show', background_color='#141414')
webview.start()
foreground_window = win32gui.GetForegroundWindow()
window_title = win32gui.GetWindowText(foreground_window)
if "webdeck" in window_title.lower():
win32gui.ShowWindow(foreground_window, win32con.SW_MAXIMIZE)
else:
webbrowser.open(f"http://{local_ip}:{port}?config=show")
def close_window(event=None):
global window
if window:
window.destroy()
window = None
url = f"http://{local_ip}:{port}"
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(url)
qr.make(fit=True)
# Creation of the QR code image in bytes
img_stream = BytesIO()
# if black_theme.lower() == "true":
# qr.make_image(fill_color="white", back_color="black").save(img_stream, format='PNG')
# else:
qr.make_image(fill_color="black", back_color="white").save(img_stream, format='PNG')
img_stream.seek(0)
# Convert image to PIL format for EasyGUI
qr_pil_image = Image.open(img_stream)
def show_qrcode():
global window
if window is None:
window = tk.Tk()
window.title(text['qr_code'])
image_tk = ImageTk.PhotoImage(image=qr_pil_image)
label = tk.Label(window, image=image_tk)
label.pack()
text_label = tk.Label(window, text=f"http://{local_ip}:{port}/", font=("Helvetica", 13))
text_label.pack()
window.iconbitmap("static/files/icon.ico")
window.lift()
window.focus_force()
window.bind("<Escape>", close_window)
window.bind("<Return>", close_window)
window.bind("<space>", close_window)
window.resizable(width=False, height=False)
window.protocol("WM_DELETE_WINDOW", close_window)
window.mainloop()
def create_tray_icon():
global icon
image = Image.open("static/files/icon.ico")
menu = (
item(text['qr_code'], lambda: show_qrcode(), default=True),
item(text['open_config'], lambda: open_config()),
item(text['fix_firewall'], lambda: fix_firewall_permission()),
item(text['exit'], lambda: exit_program()),
)
# Create the Tray Icon
if getattr(sys, 'frozen', False):
icon = pystray.Icon("name", image, "WebDeck", menu)
else:
icon = pystray.Icon("name", image, "WebDeck DEV", menu)
return icon
create_tray_icon()
icon.run()