-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
558 lines (460 loc) · 22.7 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
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
import better_exceptions
better_exceptions.MAX_LENGTH = None
import signal
import dotenv
import sys
import os
import configparser
import tkinter
import threading
import pathlib
import time
import tkinter as tk # Python 3.x
from tkextrafont import Font
import tkinter.scrolledtext as ScrolledText
import multiprocessing
import logging as pylogger, logging
from loguru import logger as logger
from buy_listener import BuyListener
from ReportGUI import ReportGUI
__version__ = "v2.7.0" # update this when you update the version in setup.py
# ---------------- START CONFIG ---------------- #
global REPORT_WEBHOOK
REPORT_WEBHOOK = None
# garbage variables
global LAST_TIME
LAST_TIME = float(time.time())
global DELAY_RANGE
DELAY_RANGE = 60
# DELAY_RANGE = tk.IntVar()
# DELAY_RANGE.set(45)
global GUI_OBJECTS
GUI_OBJECTS = {}
# Real variables
LOG_COLOR_LEVEL_TO_COLOR = {
'DEBUG': 'black',
'INFO': '#434343',
'RABBIT': '#a7176e',
'SUCCESS': '#006500',
'WARNING': '#c1c100',
'ERROR': 'red',
'CRITICAL': '#700000',
}
# config = None
# pika_host = None
# pika_port = None
# pika_username = None
# pika_password = None
# pika_queue = None
# scrape_url = None
# ---------------- END VARIABLES ---------------- #
# MANAGER = logger.Manager("tf2ez_pybuy_" + __version__)
# MANAGER.getLogger().setFormatter(logger.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
# MANAGER.getLogger().setLevel(logger.DEBUG)
# GUI configurations
# configure a custom font jason what are you doing
class PropagateHandler(pylogger.Handler):
def emit(self, record):
logger.log(record)
#pylogger.getLogger(record.name).handle(record)
class ResizeHandler(threading.Thread):
window = None
aspect_ratio = 1
width = 0
height = 0 # int(self.width / self.aspect_ratio)
dim_lcm = 0
# I'm way too fucking far in now... function to calculate the LCM. Seems reasonable.
def lcm(self, a, b):
if (a == 0 or b == 0):
return 0
if a > b:
greater = a
else:
greater = b
while (True):
if ((greater % a == 0) and (greater % b == 0)):
lcm = greater
break
greater += 1
return lcm
def __init__(self, window, aspect_ratio=1.0, g_width=500, g_height=500):
super().__init__()
self.window = window
# ... this code makes a cool shape
if aspect_ratio is None:
self.aspect_ratio = g_width / g_height
else:
self.aspect_ratio = aspect_ratio
if g_width is None:
if g_height is not None:
self.width = g_height * self.aspect_ratio
self.height = g_height
else:
self.height = g_width / self.aspect_ratio
else:
self.width = g_width
self.dim_lcm = self.lcm(self.width, self.height)
self.start()
def start(self):
self.thread = threading.Thread(target=self.thread_func)
# this is intended for a main tkinter window, not a frame
# that is using grid... NOT ANYTHING ELSE!
def stop(self):
self.thread.join() # wait for it to finish very nicely
def thread_func(self):
# self.dim_lcm = lcm(self.width, self.height)
#
# if self.width * self.height < self.dim_lcm:
# int_width = self.dim_lcm
# int_height = self.aspect_ratio * self.dim_lcm
# else:
# int_width = self.width / self.dim_lcm
# int_height = self.height / self.dim_lcm
# maintain ASPECT RATIO
def on_resize(event):
w, h = event.width, event.height
w1, h1 = self.window.winfo_width(), self.window.winfo_height()
logger.debug(f"on_resize: {w}x{h} | {w1}x{h1}")
w1, h1 # must follow ASPECT_RATIO (w1/h1 = ASPECT_RATIO)
if w > self.aspect_ratio * h:
# self.window.rowconfigure(0, weight=1)
# self.window.rowconfigure(1, weight=0)
self.window.columnconfigure(0, weight=h)
self.window.columnconfigure(1, weight=w - h)
elif w < self.aspect_ratio * h:
self.window.rowconfigure(0, weight=w)
self.window.rowconfigure(1, weight=h - w)
# self.window.columnconfigure(0, weight=1)
# self.window.columnconfigure(1, weight=0)
else:
w_lcm = self.lcm(w, h)
if w * h < w_lcm:
int_width = w_lcm
int_height = self.aspect_ratio * w_lcm
else:
int_width = w / w_lcm
int_height = h / w_lcm
self.window.rowconfigure(0, weight=1)
self.window.rowconfigure(int_width, weight=0)
self.window.rowconfigure(0, weight=1)
self.window.columnconfigure(int_height, weight=0)
# TODO: no idea if this will work with the way mainloop is handled
self.window.bind("<Configure>", self.on_resize)
class TextHandler(pylogger.Handler):
# This class allows you to log to a Tkinter Text or ScrolledText widget
# Adapted from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06
def __init__(self, text):
# run the regular Handler __init__
logger = pylogger.getLogger(__name__)
pylogger.Handler.__init__(self)
# logger.Handler.setFormatter(self, coloredlogs.ColoredFormatter())
# Store a reference to the Text it will log to
self.text = text
def emit(self, record):
msg = self.format(record)
def append():
self.text.configure(state='normal', background="#242424", foreground="#434343", font=("Arial", 10, "bold"))
self.text.insert(tk.END, msg + '\n', record.levelname)
# self.text.tag_config(record.levelname, foreground=f"{LOG_COLOR_LEVEL_TO_COLOR[record.levelname]}")
self.text.tag_config("CRITICAL", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['CRITICAL']}", background="#b0b0b0",
font=("Arial", 10, "bold"))
self.text.tag_config("ERROR", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['ERROR']}", background="black")
self.text.tag_config("WARNING", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['WARNING']}", background="black")
self.text.tag_config("SUCCESS", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['SUCCESS']}", background="black")
self.text.tag_config("RABBIT", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['RABBIT']}", background="#b0b0b0")
self.text.tag_config("INFO", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['INFO']}", background="#b0b0b0",
font=("Arial", 10, "bold"))
self.text.tag_config("DEBUG", foreground=f"{LOG_COLOR_LEVEL_TO_COLOR['DEBUG']}", background="#b0b0b0",
font=("Arial", 10, "italic"))
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(tk.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
# ----------------------------------------------------------- #
class GUI(threading.Thread):
buyListener = None
textHandler = None
def __init__(self, worker):
#super().__init__()
# self.thread = None
self.buyListener = worker
self.build()
def set_worker(self, worker):
self.buyListener = worker
# ---------------- START GUI ---------------- #
def build(self):
self.root = tkinter.Tk()
global SPOOKY_FONT
SPOOKY_FONT = Font(file=pathlib.Path('assets/font/IMFellEnglishSC-Regular.ttf'), family="IM Fell English SC")
# self.root.wm_title("SPOOKYSCRAPE TF2EZ PYBUY" + " " + __version__)
self.root.title("SPOOKYSCRAPE TF2EZ PYBUY" + " " + __version__)
# self.root.option_add("*Font", (SPOOKY_FONT))
self.root.geometry("800x550")
self.root.resizable(False, True)
self.root.minsize(800, 550)
self.root.configure(background="black")
self.root.iconbitmap(pathlib.Path("assets/img/logo/spookyscrape.ico"))
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.root.frame = tkinter.Frame(self.root, highlightcolor="#bfbfbf", bg="#1b1b1b", relief="sunken",
borderwidth=2)
self.root.frame.grid(row=0, column=0, sticky='ewsn')
##self.root.frame.configure(background="#242424")
self.root.frame.t_label = tkinter.Label(self.root.frame, text="PYBUY " + __version__,
font=("IM Fell English SC", 14), fg="orange", bg="black")
self.root.frame.t_label.grid(column=0, row=0, sticky="n", padx=5, pady=5, columnspan=4)
# it was JASON that chose this font
# and I'm not going to change it
# because I'm not a monster
# This was still me, JASON, who chose this font
self.root.frame.label = tkinter.Label(self.root.frame, text="not running", font=("Comics Sans", 12), fg="black")
self.root.frame.label.grid(column=0, row=4, sticky='ewn', padx=5, pady=5, columnspan=1)
self.subtext_str = tkinter.StringVar()
self.subtext_str.set("by Oscar & Jason of SpookyTF")
self.root.frame.ctn_label = tkinter.Label(self.root.frame, textvariable=self.subtext_str,
font=("Comics Sans", 10), fg="orange", bg="black")
self.root.frame.ctn_label.grid(column=0, row=5, sticky='ews', padx=5, pady=5, columnspan=1)
self.root.frame.button = tkinter.Button(self.root.frame, text="start", command=self.start,
font=("Comics Sans", 14), fg="red", bg="#242424", relief="sunken",
borderwidth=2)
self.root.frame.button['state'] = 'disabled'
self.root.frame.button.grid(column=3, row=4, sticky='ewn', padx=5, pady=5, columnspan=2)
# global DELAY_RANGE
# self.root.frame.delay_scale = tkinter.Scale(self.root.frame, from_=0, to=360, orient=tkinter.HORIZONTAL, label="delay range (s)", font=("Comics Sans", 12), fg="orange", bg="black", length=200, variable=DELAY_RANGE, command=self.update_delay_range)
# self.root.frame.delay_scale.grid(column=0, row=6, sticky='ews', padx=5, pady=5, columnspan=4)
self.display_log = tk.StringVar()
self.root.frame.label = tkinter.Label(self.root.frame, textvariable=self.display_log, font=("Comics Sans", 12),
fg="green")
if os.getenv('LOGIN_METHOD') == "cookie" and os.getenv('LOGIN_COOKIE') is not None:
self.display_log.set("cookie found, log in!")
self.root.frame.label.configure(fg="white", bg="green")
self.root.frame.login_button['state'] = 'normal'
self.root.frame.login_button.configure(self.root.frame, text="🟡 login ", font=("Comics Sans", 14),
fg="yellow", bg="black", command=self.login)
# self.root.frame.login_button.grid(column=3, row=5, sticky='ewn', padx=5, pady=5, columnspan=2)
else:
self.root.frame.login_button = tkinter.Button(self.root.frame, text="❌ not logged in", command=self.login,
font=("Arial", 14, "bold"), fg="red")
self.root.frame.login_button['state'] = 'normal'
self.root.frame.login_button.grid(column=3, row=5, sticky='ewn', padx=5, pady=5, columnspan=2)
self.root.option_add('*tearOff', 'FALSE')
self.root.frame.grid(column=0, row=0, sticky='new')
self.root.frame.grid_columnconfigure(0, weight=1, uniform='a')
self.root.frame.grid_columnconfigure(1, weight=1, uniform='a')
self.root.frame.grid_columnconfigure(2, weight=1, uniform='a')
self.root.frame.grid_columnconfigure(3, weight=1, uniform='a')
# Add text widget to display logger info
st = ScrolledText.ScrolledText(self.root.frame, state='disabled', bg="#242424", fg="#434343")
st.configure(font='TkFixedFont')
st.grid(column=0, row=1, sticky='wsen', columnspan=4)
st.grid_columnconfigure(0, weight=1)
st.grid_rowconfigure(0, weight=1)
# Create textLogger
text_handler = TextHandler(st)
self.textHandler = text_handler
pylogger.getLogger(__name__).addHandler(text_handler)
if not os.path.exists("logs/tf2ez_pybuy.log"):
pathlib.Path("logs").mkdir(parents=True, exist_ok=True)
pathlib.Path("logs/tf2ez_pybuy.log").touch()
# clear if log is too big
# if fs := os.path.getsize("logs/tf2ez_pybuy.log.old") > 1000000:
# os.remove("logs/tf2ez_pybuy_ALL.log")
# Add the handler to logger
# MANAGER.getLogger('tf2ez_pybuy_combined').setLevel(gui).addHandler(text_handler);
# logger.addHandler(text_handler)
# logger.addHandler(logger.FileHandler(pathlib.Path("logs/combined_" + str(time.time()) + ".log"), "a", "utf-8", True, "DEBUG"))
# shouldn't ever actually "append"
logger.add(sink=(pathlib.Path("logs/user_0.log")), rotation="1 day", retention="1 week", enqueue=True,
level="DEBUG", format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", encoding="utf-8")
self.root.frame.grid(row=0, column=0, sticky='news', padx=5, pady=5)
self.root.pack_propagate(True)
# self.root.frame.pack(fill="x", expand = True, pady=10, padx=10)
# self.root.frame.pack(fill="both", expand=True)
# self.root.frame.pack(side="bottom", fill="x", expand=True, pady=10, padx=10)
# self.root.frame.pack_propagate(False)
# TODO: Remove this, it was an experiment to understand how these fucking GUIs work
# # ------------- MAKE RESPONSIVE ----------- #
#
# # everything is in a frame
# self.root.frame.grid(row=0, column=0, sticky='ewsn')
#
# # root level buttons & labels
# self.root.frame.t_label.grid(column=0, row=0, sticky="n", padx=5, pady=5, columnspan=4)
#
# self.root.frame.label.grid(column=0, row=4, sticky='ewn', padx=5, pady=5, columnspan=1)
#
# self.root.frame.ctn_label.grid(column=0, row=5, sticky='ews',padx=5, columnspan=1)
#
# self.root.frame.button.grid(column=3, row=4, sticky='ewn', padx=5, pady=5, columnspan=2)
#
# self.root.frame.login_button.grid(column=3, row=5, sticky='sew', padx=5, columnspan=2)
#
# # logs text widget & scrollbar layout
# self.root.frame.grid(column=0, row=0, sticky='new')
# self.root.frame.grid_columnconfigure(0, weight=1, uniform='a')
# self.root.frame.grid_columnconfigure(1, weight=1, uniform='a')
# self.root.frame.grid_columnconfigure(2, weight=1, uniform='a')
# self.root.frame.grid_columnconfigure(3, weight=1, uniform='a')
#
# # Add text widget to display logger info
# st.grid(column=0, row=1, sticky='wsen', columnspan=4)
# Start the ResizeHandler to make the GUI responsive
# AND maintain aspect ratio in grid layout. This is
# EXTREME overkill for a simple GUI, but I wanted it. :)
# ......
# ...... and ACTUALLY, it was a HUGE waste of time!
# lol. I'm keeping it in though, because it's cool.
# resize_handler = ResizeHandler(self.root, 1.6, 8, 5)
# resize_handler.start()
self.root.configure(bg="#F08300")
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_rowconfigure(1, weight=0)
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_columnconfigure(1, weight=0)
self.root.frame.mainloop()
# ---------------- END GUI ---------------- #
def login(self):
logger.debug("login button pressed")
self.login_int()
def login_int(self):
self.root.frame.label["text"] = "logger in..."
self.root.frame.login_button["text"] = "logger in..."
self.root.frame.login_button["fg"] = "black"
self.root.frame.button["state"] = "disabled"
self.root.frame.login_button["state"] = "disabled"
logged_in = False
login_method = os.getenv('LOGIN_METHOD')
try:
self.buyListener.init_selenium_and_login()
logged_in = True
except:
self.root.frame.label["text"] = "login failed"
self.root.frame.label["fg"] = "white"
self.root.frame.login_button["text"] = "❌ not logged in"
self.root.frame.login_button["bg"] = "red"
# self.root.frame.login_button.after(500, lambda: self.root.frame.login_button.configure(bg="#4C4C4C"))
self.root.frame.login_button["state"] = "normal"
self.root.frame.button["state"] = "disabled"
self.root.frame.login_button["bg"] = "red"
# self.root.frame.button["bg"] = "#434343"
# .configure(bg="#242424", relief="sunken", borderwidth=2)
return
if os.getenv('LOGIN_COOKIE') is not None:
self.root.frame.label["text"] = "logged in!"
self.root.frame.login_button["text"] = "✅ logged in"
self.root.frame.login_button["state"] = "disabled"
self.root.frame.login_button["bg"] = "green"
self.root.frame.button["state"] = "normal"
# self.root.frame.button.configure(bg="#4C4C4C", relief="raised", borderwidth=1)
else:
self.root.frame.label["text"] = "try again -- invalid cookie"
self.root.frame.label["fg"] = "white"
self.root.frame.login_button["text"] = "❌ cookie expired"
self.root.frame.login_button["state"] = "normal"
self.root.frame.login_button["bg"] = "red"
# self.root.frame.login_button.after(500, lambda: self.root.frame.login_button.configure(bg="#4C4C4C"))
self.root.attributes('-topmost', True)
def start(self):
self.thread = threading.Thread(target=self.thread_func)
self.run()
# self.thread.start()
def thread_func(self):
# logger.addHandler(self.textHandler)
self.root.frame.button["state"] = "normal"
self.root.frame.label["text"] = "running..."
self.root.frame.button.configure(text="stop", command=self.stop, fg="red", font=("Arial", 14, "bold"))
# Run buyListener to listen for messages
# self.testing_spam_logs(100)
logger.info("starting...")
self.buyListener.start()
# never reached
# ^^ this is a lie, it is reached when the thread is stopped!
# self.label["text"] = "done"
# self.button["state"] = "normal"
def stop(self):
self.buyListener.stop()
self.root.frame.label["text"] = "stopping..."
self.root.frame.label.configure(fg="black", bg="#AF7C04")
self.root.frame.button["state"] = "disabled"
logger.warning("stopped.");
self.root.frame.label.after(500, lambda: self.root.frame.label.configure(fg="black", bg="white"))
self.root.frame.button.after(500, lambda: self.root.frame.button.configure(text="start", command=self.start,
fg="green"))
# self.root.frame.button.configure(text="start", command=self.start, fg="green")
def on_closing(self):
self.root.frame.quit()
for widget in self.root.frame.winfo_children():
widget.destroy()
self.root.destroy()
if self.buyListener is not None:
self.buyListener.stop()
exit(0)
def update_delay_range(self):
global DELAY_RANGE
self.buyListener.delayed_passthrough["delay_range"] = DELAY_RANGE.get()
# ---------------- DEBUG FUNCTION ---------------- #
def testing_spam_logs(self, n=100):
for i in range(n):
if i % 5 == 0:
logger.debug("test")
elif i % 5 == 1:
logger.info("test")
elif i % 5 == 2:
logger.warning("test")
elif i % 5 == 3:
logger.error("test")
elif i % 5 == 4:
logger.critical("test")
def throw_exception(self):
raise IOError("test", "lots of testing")
def main():
# ---------------- Load variables ---------------- #
config = configparser.ConfigParser()
config.read(pathlib.Path('config.ini'))
dotenv.load_dotenv()
# ---------------- Configure RabbitMQ ---------------- #
pika_host = os.getenv("PIKA_HOST")
pika_port = int(os.getenv("PIKA_PORT"))
pika_username = os.getenv("PIKA_USERNAME")
pika_password = os.getenv("PIKA_PASSWORD")
# ---------------- Configure logger ---------------- #
level = os.getenv('log_level')
if level is None:
level = "INFO"
gui_level = os.getenv('gui_log_level') if os.getenv('gui_log_level') is not None else level
term_level = os.getenv('term_log_level') if os.getenv('term_log_level') is not None else level
file_level = os.getenv('file_log_level') if os.getenv('file_log_level') is not None else level
# colored logger configuration
# coloredlogs.install(level)
# def addHandlers(logger, hdlrs):
# for hdlr in hdlrs:
# logger.addHandler(hdlr)
#
# def addAllHandlers(logger):
# addHandlers(logger, [ logger.Handler(),
# logger.FileHandler('logs/tf2ez_pybuy.log', 'a'),
# logger.FileHandler('logs/combined_' + str(time.time_ns()) + '.log', 'w')])
pylogger.basicConfig(level=pylogger.DEBUG,
filename="logs/tf2ez_pybuy.log",
format='%(levelname)s %(asctime)s - %(message)s',
datefmt='%d %m %y %H:%M:%S')
# ---------------- pass data to buyListener ---------------- #
global DELAY_RANGE
DELAY_RANGE = int(config['TIMES']['delay_range'])
global REPORT_WEBHOOK
REPORT_WEBHOOK = config['REPORT']['webhook']
# ---------------- Start GUI && worker ---------------- #
worker = BuyListener(pika_host=pika_host, pika_port=pika_port, pika_username=pika_username, pika_password=pika_password, pika_queue=config['RABBITMQ']['queue'],
delay_range=config['TIMES']['delay_range'], scrape_url=config['SCRAPE']['url'], login_method=config['LOGIN']['method'])
myGUI = GUI(worker)
def handler(signum, frame):
if signal == signal.SIGINT:
logger.warning('Killed by user')
sys.exit(0)
if signal == signal.SIGTERM:
logger.critical('Killed by SIGTERM')
reportgui = ReportGUI()
reportgui.run()
if __name__ == "__main__":
# signal.signal(signal.SIGINT, handler)
main()