Обновление 2.1

This commit is contained in:
Profitroll 2021-04-30 03:25:36 +03:00
parent 2183db0515
commit 6df060142a
9 changed files with 1921 additions and 1372 deletions

1528
daemon.py

File diff suppressed because it is too large Load Diff

642
editor.py Normal file
View File

@ -0,0 +1,642 @@
import rpc
from functions import *
from datetime import datetime, date, timedelta
from daemon import getLessons, getConfig
if getConfig("use_colors"):
from colors import *
appendLog('Colors imported')
else:
RESET = ''
BLACK = RED = GREEN = YELLOW = BLUE = MAGENTA = CYAN = WHITE = ''
BBLACK = BRED = BGREEN = BYELLOW = BBLUE = BMAGENTA = BCYAN = BWHITE = ''
ULINE = REVERSE = ''
appendLog('Loading without colors')
def listLessons(from_where='remove'):
try:
appendLog('Showing list of everything planned')
if from_where == 'editor':
print(f'{RESET}Полный список запланированных конференций:\n')
print(f'{BBLACK}================================================{RESET}')
for les in enumerate(getLessons()):
if les[1]["repeat"]:
repeat = 'Вкл.'
else:
repeat = 'Выкл.'
if les[1]["record"]:
record = 'Вкл.'
else:
record = 'Выкл.'
try:
repeat_day = getDay(les[1]["repeat_day"])
except:
repeat_day = 'Не повторяется'
length = len(str(les[0]))
spacer_all = 6 * ' '
spacer_ind = (5 - length) * ' '
print(f'{spacer_all}Имя: {YELLOW}{les[1]["name"]}{RESET}')
print(f'{spacer_all}Дата: {YELLOW}{les[1]["date"]}{RESET}')
print(f'{spacer_all}Время: {YELLOW}{les[1]["time"]}{RESET}')
print(f' {GREEN}{les[0]}{RESET}{spacer_ind}Ссылка: {YELLOW}{les[1]["link"]}{RESET}')
print(f'{spacer_all}Повтор: {YELLOW}{repeat}{RESET}')
print(f'{spacer_all}День: {YELLOW}{repeat_day}{RESET}')
print(f'{spacer_all}Запись: {YELLOW}{record}{RESET}')
print(f'{BBLACK}================================================{RESET}')
if from_where == 'editor':
none = input('\n\n > ')
except KeyboardInterrupt:
clear()
return
def sortLessons(dictionary):
dictionary.sort(key = lambda x: datetime.strptime(x['time'], '%H:%M'))
dictionary.sort(key = lambda x: datetime.strptime(x['date'], '%d.%m.%Y'))
appendLog('Lessons dictionary sorted')
def getDay(number):
if number == 1:
return 'Понедельник'
if number == 2:
return 'Вторник'
if number == 3:
return 'Среда'
if number == 4:
return 'Четверг'
if number == 5:
return 'Пятница'
if number == 6:
return 'Суббота'
if number == 7:
return 'Воскресенье'
def addLesson():
appendLog('Adding new lesson')
try:
local_lessons = {}
lessons_got = getLessons()
lessname = input(f'{RESET}Введите (своё) имя конференции:\n{BBLACK}Нужно лишь для отображения в Discord и самом AutoZoom{RESET}\n\n > {CYAN}')
local_lessons.update({"name": lessname})
while True:
clear()
today = date.today()
today_1 = date.today() + timedelta(days=1)
today_2 = date.today() + timedelta(days=2)
today_3 = date.today() + timedelta(days=3)
today_4 = date.today() + timedelta(days=4)
today_5 = date.today() + timedelta(days=5)
today_6 = date.today() + timedelta(days=6)
print(f'{RESET}Введите дату конференции или номер дня ({BRED}ДД.ММ.ГГГГ{RESET}):\n')
print(f' {BRED}1.{RESET} {today.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}2.{RESET} {today_1.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_1.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}3.{RESET} {today_2.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_2.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}4.{RESET} {today_3.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_3.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}5.{RESET} {today_4.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_4.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}6.{RESET} {today_5.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_5.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}7.{RESET} {today_6.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_6.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
try:
lessdate = input(f'\n > {BRED}')
if lessdate == '':
finallessdate = lessons_got[edi]["date"]
elif lessdate == '1':
finallessdate = today.strftime("%d.%m.%Y")
elif lessdate == '2':
finallessdate = today_1.strftime("%d.%m.%Y")
elif lessdate == '3':
finallessdate = today_2.strftime("%d.%m.%Y")
elif lessdate == '4':
finallessdate = today_3.strftime("%d.%m.%Y")
elif lessdate == '5':
finallessdate = today_4.strftime("%d.%m.%Y")
elif lessdate == '6':
finallessdate = today_5.strftime("%d.%m.%Y")
elif lessdate == '7':
finallessdate = today_6.strftime("%d.%m.%Y")
else:
try:
test = (datetime.strptime(lessdate, "%d.%m.%Y"))
finallessdate = lessdate
except:
continue
local_lessons.update({"date": finallessdate})
break
except:
continue
while True:
clear()
try:
lesstime = input(f'{RESET}Введите время конференции ({BRED}ЧЧ:ММ{RESET}):\n\n > {BRED}')
finallesstime = (datetime.strptime(lesstime, "%H:%M"))
local_lessons.update({"time": lesstime})
abort = "skip"
conflict = False
conflictles = ''
confstr = 'конференцией'
try:
for lesson in lessons_got:
if lesson["date"] == finallessdate and lesson["time"] == lesstime:
conflict = True
if conflictles == '':
conflictles = f'{CYAN}{lesson["name"]}{RESET}'
confstr = 'конференцией'
else:
conflictles += f', {CYAN}{lesson["name"]}{RESET}'
confstr = 'конференциями'
if conflict:
while True:
clear()
choice = input(f'{RESET}Время и дата конференции совпадают с {confstr} {conflictles}.\nДобавить ещё одну конференцию на то же время? ({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n > ')
if choice.lower() in yes_list:
abort = "bypass"
break
elif choice.lower() in no_list:
abort = "restart"
break
else:
continue
if abort == "restart":
continue
else:
break
except Exception as exp:
none = input(exp)
pass
break
except:
continue
clear()
lesslink = input(f'{RESET}Введите ссылку на конференцию:\n{BBLACK}Формат: {BRED}https://us01web.zoom.us/j/ИДЕНТИФИКАТОР?pwd=ПАРОЛЬ{RESET}\n{BBLACK}Либо введите {YELLOW}1 {BBLACK}для добавления по номеру и паролю{RESET}\n\n > {BRED}').replace(" ", "")
if lesslink.replace(' ', '') == '1':
clear()
lessid = input(f'{RESET}Введите идентификатор конференции:\n{BBLACK}Формат: {BRED}012 3456 7890 {BBLACK} либо {BRED}01234567890{RESET}\n\n > {BRED}')
clear()
lesspasswd = input(f'{RESET}Введите код доступа (пароль) конференции:\n\n > {BRED}')
lesslink = f'https://us01web.zoom.us/j/{lessid.replace(" ", "")}?pwd={lesspasswd.replace(" ", "")}'
local_lessons.update({"link": lesslink})
while True:
clear()
repeat = input(f'{RESET}Повторять эту конференцию ({getDay(getDayNum(finallessdate))})? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n > ')
if repeat.lower() in yes_list:
finalrepeat = True
finalrepeatday = getDayNum(finallessdate)
local_lessons.update({"repeat": finalrepeat})
local_lessons.update({"repeat_day": finalrepeatday})
break
elif repeat.lower() in no_list:
finalrepeat = False
finalrepeatday = None
local_lessons.update({"repeat": finalrepeat})
local_lessons.update({"repeat_day": finalrepeatday})
break
else:
continue
while True:
if getOS() == "windows":
clear()
lessrecord = input(f'Записать эту конференцию? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n > ')
if lessrecord.lower() in yes_list:
finallessrecord = True
local_lessons.update({"record": finallessrecord})
break
elif lessrecord.lower() in no_list:
finallessrecord = False
local_lessons.update({"record": finallessrecord})
break
else:
continue
else:
finallessrecord = False
local_lessons.update({"record": finallessrecord})
break
lessons_got.append(dict(local_lessons))
sortLessons(lessons_got)
saveJson(files_folder+'lessons.json', lessons_got)
clear()
print(f'Добавлена конференция {CYAN}{local_lessons["name"]}{RESET} за {BRED}{local_lessons["date"]}{RESET} на время {BRED}{local_lessons["time"]}{RESET}.')
appendLog(f'Added lesson {local_lessons["name"]} (Date: {local_lessons["date"]}, Time: {local_lessons["time"]}, Link: {local_lessons["link"]})')
none = input('\n > ')
except KeyboardInterrupt:
appendLog('Lesson adding aborted')
clear()
return
def editLesson():
appendLog(f'Editing existing lesson')
try:
local_lessons = {}
lessons_got = getLessons()
while True:
print(f'{RESET}Выберите номер (индекс) для изменения:\n')
listLessons()
lessons_got = getLessons()
print(f'\nДля отмены операции введите {BRED}c{RESET} или {BRED}cancel{RESET}')
edi = input(f'\n > {BGREEN}')
if not isinstance(edi, int):
if edi.lower() == 'c' or edi.lower() == 'cancel':
clear()
return
try:
edi = int(edi)
except:
clear()
continue
try:
probe = lessons_got[edi]["name"]
break
except:
clear()
print(f'{RESET}Выберите {ULINE}правильный{RESET} индекс (номер) для изменения.')
time.sleep(3)
clear()
continue
break
clear()
lessname = input(f'{RESET}Введите (своё) имя конференции:\n{BBLACK}Нужно лишь для отображения в Discord и самом AutoZoom{RESET}\n\nОригинальное имя: {CYAN}{lessons_got[edi]["name"]}{RESET}\n\n > {CYAN}')
if lessname == '':
lessname = lessons_got[edi]["name"]
local_lessons.update({"name": lessname})
while True:
clear()
today = date.today()
today_1 = date.today() + timedelta(days=1)
today_2 = date.today() + timedelta(days=2)
today_3 = date.today() + timedelta(days=3)
today_4 = date.today() + timedelta(days=4)
today_5 = date.today() + timedelta(days=5)
today_6 = date.today() + timedelta(days=6)
print(f'{RESET}Введите дату конференции или номер дня ({BRED}ДД.ММ.ГГГГ{RESET}):\n')
print(f' {BRED}1.{RESET} {today.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}2.{RESET} {today_1.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_1.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}3.{RESET} {today_2.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_2.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}4.{RESET} {today_3.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_3.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}5.{RESET} {today_4.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_4.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}6.{RESET} {today_5.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_5.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f' {BRED}7.{RESET} {today_6.strftime("%d.%m.%Y")} ({BGREEN}{getDay(datetime.strptime(today_6.strftime("%d.%m.%Y"), "%d.%m.%Y").isoweekday())}{RESET})')
print(f'\nОригинальная дата: {BRED}{lessons_got[edi]["date"]}{RESET}')
try:
lessdate = input(f'\n > {BRED}')
if lessdate == '':
finallessdate = lessons_got[edi]["date"]
elif lessdate == '1':
finallessdate = today.strftime("%d.%m.%Y")
elif lessdate == '2':
finallessdate = today_1.strftime("%d.%m.%Y")
elif lessdate == '3':
finallessdate = today_2.strftime("%d.%m.%Y")
elif lessdate == '4':
finallessdate = today_3.strftime("%d.%m.%Y")
elif lessdate == '5':
finallessdate = today_4.strftime("%d.%m.%Y")
elif lessdate == '6':
finallessdate = today_5.strftime("%d.%m.%Y")
elif lessdate == '7':
finallessdate = today_6.strftime("%d.%m.%Y")
else:
try:
test = (datetime.strptime(lessdate, "%d.%m.%Y"))
finallessdate = lessdate
except:
continue
local_lessons.update({"date": finallessdate})
break
except:
continue
while True:
clear()
try:
lesstime = input(f'{RESET}Введите время конференции ({BRED}ЧЧ:ММ{RESET}):\n\nОригинальное время: {BRED}{lessons_got[edi]["time"]}{RESET}\n\n > {BRED}')
finallesstime = (datetime.strptime(lesstime, "%H:%M"))
local_lessons.update({"time": lesstime})
abort = "skip"
conflict = False
conflictles = ''
confstr = 'конференцией'
try:
for lesson in lessons_got:
if lesson["date"] == finallessdate and lesson["time"] == lesstime:
conflict = True
if conflictles == '':
conflictles = f'{CYAN}{lesson["name"]}{RESET}'
confstr = 'конференцией'
else:
conflictles += f', {CYAN}{lesson["name"]}{RESET}'
confstr = 'конференциями'
if conflict:
while True:
clear()
choice = input(f'{RESET}Время и дата конференции совпадают с {confstr} {conflictles}.\nДобавить ещё одну конференцию на то же время? ({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n > ')
if choice.lower() in yes_list:
abort = "bypass"
break
elif choice.lower() in no_list:
abort = "restart"
break
else:
continue
if abort == "restart":
continue
else:
break
except Exception as exp:
none = input(exp)
pass
break
except:
continue
clear()
lesslink = input(f'{RESET}Введите ссылку на конференцию:\n{BBLACK}Формат: {BRED}https://us01web.zoom.us/j/ИДЕНТИФИКАТОР?pwd=ПАРОЛЬ{RESET}\n{BBLACK}Либо введите {YELLOW}1 {BBLACK}для добавления по номеру и паролю{RESET}\n\n > {BRED}').replace(" ", "")
if lesslink.replace(' ', '') == '1':
clear()
lessid = input(f'{RESET}Введите идентификатор конференции:\n{BBLACK}Формат: {BRED}012 3456 7890 {BBLACK} либо {BRED}01234567890{RESET}\n\n > {BRED}')
clear()
lesspasswd = input(f'{RESET}Введите код доступа (пароль) конференции:\n\n > {BRED}')
lesslink = f'https://us01web.zoom.us/j/{lessid.replace(" ", "")}?pwd={lesspasswd.replace(" ", "")}'
if lesslink == '':
lesslink = lessons_got[edi]["link"]
local_lessons.update({"link": lesslink})
while True:
clear()
try:
lessrepeatday = getDay(lessons_got[edi]["repeat_day"])
except:
lessrepeatday = 'Не повторяется'
print(f'{RESET}Повторять эту конференцию ({YELLOW}{getDay(getDayNum(finallessdate))}{RESET})? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})')
print(f'\nОригинальное значение: {BRED}{lessrepeatday}{RESET}')
repeat = input('\n > ')
if repeat.lower() in yes_list:
finalrepeat = True
finalrepeatday = getDayNum(finallessdate)
local_lessons.update({"repeat": finalrepeat})
local_lessons.update({"repeat_day": finalrepeatday})
break
elif repeat.lower() in no_list:
finalrepeat = False
local_lessons.update({"repeat": finalrepeat})
break
elif repeat == '':
finalrepeat = lessons_got[edi]["repeat"]
local_lessons.update({"repeat": finalrepeat})
try:
finalrepeatday = lessons_got[edi]["repeat_day"]
local_lessons.update({"repeat_day": finalrepeatday})
except:
pass
break
else:
continue
while True:
if getOS() == "windows":
clear()
print(f'Записать эту конференцию? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})')
print(f'\nОригинальное значение: {BRED}{lessons_got[edi]["record"]}{RESET}')
lessrecord = input('\n > ')
if lessrecord.lower() in yes_list:
finallessrecord = True
local_lessons.update({"record": finallessrecord})
break
elif lessrecord.lower() in no_list:
finallessrecord = False
local_lessons.update({"record": finallessrecord})
break
elif lessrecord == '':
finallessrecord = lessons_got[edi]["record"]
local_lessons.update({"record": finallessrecord})
break
else:
continue
else:
finallessrecord = False
local_lessons.update({"record": finallessrecord})
break
del lessons_got[edi]
lessons_got.append(dict(local_lessons))
sortLessons(lessons_got)
saveJson(files_folder+'lessons.json', lessons_got)
clear()
print(f'Изменена конференция {CYAN}{lessname}{RESET} за {BRED}{finallessdate}{RESET} на время {BRED}{finallesstime}{RESET}.')
appendLog(f'Edited lesson {lessname} (Date: {finallessdate}, Time: {finallesstime}, Link: {local_lessons["link"]})')
none = input('\n > ')
except KeyboardInterrupt:
appendLog('Editing existing lesson aborted')
clear()
return
def removeLesson():
appendLog(f'Removing existing lesson')
try:
while True:
print(f'{RESET}Выберите номер (индекс) для удаления:\n')
listLessons()
lessons_local = getLessons()
print(f'\n{BBLACK}Для отмены операции введите {BRED}c{BBLACK} или {BRED}cancel{RESET}')
rem = input(f'\n > {BRED}')
if rem.lower() == 'c' or rem.lower() == 'cancel':
clear()
break
else:
try:
rem = int(rem)
except:
clear()
continue
try:
del_name = lessons_local[rem]["name"]
del_date = lessons_local[rem]["date"]
del_time = lessons_local[rem]["time"]
del lessons_local[rem]
except:
clear()
print(f'{RESET}Выберите {ULINE}правильный{RESET} индекс (номер) для удаления.')
time.sleep(3)
clear()
continue
sortLessons(lessons_local)
saveJson(files_folder+'lessons.json', lessons_local)
clear()
print(f'{RESET}Удалена конференция {CYAN}{del_name}{RESET} за {BRED}{del_date}{RESET} на время {BRED}{del_time}{RESET}.')
appendLog(f'Removed lesson {del_name} (Date: {del_date}, Time: {del_time})')
none = input('\n > ')
break
except KeyboardInterrupt:
appendLog('Lesson removal aborted')
clear()
return
def removeAllLessons():
appendLog('Removing all lessons')
try:
while True:
clear()
removeall = input(f'{RESET}Вы уверены что хотите удалить все конференции? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n{BRED}Внимание!{RESET} Это действие нельзя обратить!\nВаши настройки затронуты НЕ будут.\n\n > ')
if removeall.lower() in yes_list:
with open(files_folder+'lessons.json', 'w', encoding="utf-8") as f:
f.write("[]")
f.close()
appendLog('All lessons removed')
clear()
none = input('Все конференции были удалены.\n\n > ')
clear()
break
elif removeall.lower() in no_list:
appendLog('All lessons removal aborted')
clear()
break
else:
continue
except KeyboardInterrupt:
appendLog('All lessons removal aborted')
clear()
return
def editor():
try:
setTitle("AutoZoom (Редактор)", getOS())
appendLog('Editor menu opened')
from main import mainMenu
while True:
clear()
print(f'{BBLACK}»{RESET} Меню редактора\n')
print(f' {BRED}1.{RESET} Добавить конференцию')
print(f' {BRED}2.{RESET} Изменить конференцию')
print(f' {BRED}3.{RESET} Удалить конференцию')
print(f' {BRED}4.{RESET} Посмотреть конференции')
print(f' {BRED}5.{RESET} Удалить все конференции')
print(f' {BRED}6.{RESET} В главное меню')
editor_choose = input(f'\n > {BRED}')
if editor_choose == '1':
appendLog('Went to lesson adding')
clear()
addLesson()
elif editor_choose == '2':
appendLog('Went to lesson editing')
clear()
editLesson()
elif editor_choose == '3':
appendLog('Went to lesson removal')
clear()
removeLesson()
elif editor_choose == '4':
appendLog('Went to lesson lising')
clear()
listLessons(from_where = 'editor')
elif editor_choose == '5':
appendLog('Went to all lessons removal')
clear()
removeAllLessons()
elif editor_choose == '6':
appendLog('Exiting back to main menu')
rpc.inMenu()
clear()
setTitle("AutoZoom (Главная)", getOS())
mainMenu()
else:
continue
except KeyboardInterrupt:
appendLog('Exiting back to main menu')
rpc.inMenu()
clear()
return

View File

@ -6,19 +6,24 @@ import json
import os
import shutil
import gzip
import getpass
from datetime import datetime
from pathlib import Path
from subprocess import check_output
path = Path(__file__).resolve().parent
sounds_folder = str(Path(str(path)+"/sounds/")) + os.sep
files_folder = str(Path(str(path)+"/files/")) + os.sep
logs_folder = str(Path(str(path)+"/logs/")) + os.sep
yes_list = ['y', 'yes', 'д', 'да']
no_list = ['n', 'no', 'н', 'нет']
default_config = {
"firstboot": True,
"debug": False,
"shutdown_timeout": 30,
"shutdown_enabled": True,
"shutdown_enabled": False,
"start": "shift+f7",
"stop": "shift+f8",
"telegram_enabled": False,
@ -35,6 +40,51 @@ default_config = {
}
# Функция возвращающая надпись Windows Only
def winOnly(color, reset, system, start='', end=''):
if system != 'windows':
return f"{start}{color}Только для Windows!{reset}{end}"
else:
return ""
# Функция возвращающая тип ОС
def getOS():
if os.name == 'nt':
return "windows"
elif 'android' in str(check_output('uname -a', shell=True).lower()):
return "android"
else:
return "unix"
# Функция отвечает за очищение командной строки
if getOS() == "windows":
clear = lambda: os.system('cls')
else:
clear = lambda: os.system('clear')
# Установка заголовка окна cmd.exe
def setTitle(title, system):
if system == "windows":
try:
os.system(f"title {title}")
except:
pass
# Получить номер дня недели
def getDayNum(day):
output = datetime.strptime(day, "%d.%m.%Y").isoweekday()
return output
# Функция проверки размера файла
def checkSize():
global logs_folder
@ -79,7 +129,7 @@ def checkSize():
# Функция добавления в лог
def appendLog(message):
def appendLog(message, startup=False, shutdown=False):
if getConfig("write_logs"):
@ -99,42 +149,188 @@ def appendLog(message):
time.sleep(2)
print('Log file could not be created')
log.write(f'[{datetime.now().strftime("%H:%M:%S | %d.%m.%Y")}] {message}\n')
if startup:
log.write(f'[{datetime.now().strftime("%H:%M:%S | %d.%m.%Y")}] [STARTUP] {message}\n')
elif shutdown:
log.write(f'[{datetime.now().strftime("%H:%M:%S | %d.%m.%Y")}] [SHUTDOWN] {message}\n')
else:
log.write(f'[{datetime.now().strftime("%H:%M:%S | %d.%m.%Y")}] {message}\n')
log.close()
# Функция проигрывания звука
def playSound(soundname, timing=''):
global sysname
if getConfig("sounds"):
if getOS() == "windows":
try:
winsound.PlaySound(sounds_folder+soundname+".wav", winsound.SND_FILENAME)
except Exception as exp:
appendLog(f'Could not play winsound: {exp}')
if getConfig("debug"):
print(f'{timing} Не удалось проиграть winsound звук "{soundname}" (Ошибка: {exp})')
try:
playsound(sounds_folder+soundname+".wav")
except Exception as exp:
appendLog(f'Could not play playsound: {exp}')
if getConfig("debug"):
print(f'{timing} Не удалось проиграть playsound звук "{soundname}" (Ошибка: {exp})')
elif getOS() == "android":
try:
os.system(f'play-audio {sounds_folder}{soundname}.wav')
except Exception as exp:
appendLog(f'Could not play play-audio: {exp}')
else:
try:
playsound(sounds_folder+soundname+".wav")
except Exception as exp:
appendLog(f'Could not play playsound: {exp}')
if getConfig("debug"):
print(f'{timing} Не удалось проиграть playsound звук "{soundname}" (Ошибка: {exp})')
# Функция добавления переменных, если их нет
def repairConfig(some_dic):
global files_folder
global default_config
for key in some_dic:
for key in default_config:
try:
some_dic[key]
except NameError:
some_dic[key] = default_config[key]
except KeyError:
some_dic[key] = default_config[key]
saveJson(files_folder+'config.json', some_dic)
def getConfig(some_var):
# Функция изменения переменной конфигурации
def setConfig(some_var, some_val):
global files_folder
global default_config
if os.path.exists(files_folder):
if not os.path.exists(files_folder+'config.json'):
temp_config_list = default_config
temp_config_list[some_var] = some_val
saveJson(files_folder+'config.json', temp_config_list)
else:
try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file)
json_file.close()
try:
config_list[some_var] = some_val
saveJson(files_folder+'config.json', config_list)
appendLog(f'Changed variable "{somevar}" to {some_val}')
except:
try:
repairConfig(config_list)
config_list = json.load(json_file)
json_file.close()
config_list[some_var] = some_val
saveJson(files_folder+'config.json', config_list)
appendLog(f'Changed variable "{somevar}" to {some_val}')
except:
pass
except:
return "Error"
else:
os.mkdir(files_folder)
if not os.path.exists(files_folder+'config.json'):
temp_config_list = default_config
temp_config_list[some_var] = some_val
saveJson(files_folder+'config.json', temp_config_list)
else:
try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file)
json_file.close()
try:
config_list[some_var] = some_val
saveJson(files_folder+'config.json', config_list)
except:
try:
repairConfig(config_list)
config_list = json.load(json_file)
json_file.close()
config_list[some_var] = some_val
saveJson(files_folder+'config.json', config_list)
appendLog(f'Changed variable "{somevar}" to {some_val}')
except:
config_list[some_var] = some_val
saveJson(files_folder+'config.json', config_list)
appendLog(f'Changed variable "{somevar}" to {some_val}')
except:
return "Error"
# Функция получения переменной конфигурации
def getConfig(some_var):
global files_folder
global default_config
if os.path.exists(files_folder):
if not os.path.exists(files_folder+'config.json'):
temp_config_list = default_config
saveJson(files_folder+'config.json', temp_config_list)
return temp_config_list[some_var]
else:
try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file)
json_file.close()
try:
return config_list[some_var]
except:
try:
repairConfig(config_list)
@ -153,6 +349,7 @@ def getConfig(some_var):
saveJson(files_folder+'config.json', temp_config_list)
return temp_config_list[some_var]
else:
try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file)
@ -160,19 +357,45 @@ def getConfig(some_var):
try:
return config_list[some_var]
except:
try:
repairConfig(config_list)
config_list = json.load(json_file)
json_file.close()
return config_list[some_var]
except:
return default_config[some_var]
except:
return default_config[some_var]
except:
return "Error"
# Получить статус процесса
def getState(process="CptHost.exe"):
if getOS() == 'windows':
try:
output = os.popen(f'tasklist /fi "IMAGENAME eq {process}" /fi "USERNAME ne NT AUTHORITY\{getpass.getuser()}"').read()
if process in output:
return True
else:
return False
except Exception as exp:
appendLog(f'Failed to get state using tasklist: {exp}')
output = os.popen('wmic process get description, processid').read()
if "CptHost.exe" in output:
return True
else:
return False
# Функция сохранения информации в json файл
def saveJson(filename, value):
with open(filename, 'w', encoding="utf-8") as f:
json.dump(value, f, indent=4, ensure_ascii=False)

View File

@ -2,37 +2,75 @@
import os, sys
from colors import *
from functions import getConfig
from functions import getConfig, setConfig, getOS, yes_list, no_list
from functions import appendLog
from subprocess import check_output
# Работает не очень стабильно при отсутствии интернета
# try:
# if getConfig("debug"):
# updatepip = os.system('"{}" -m pip install -U '.format(sys.executable) + '--upgrade pip')
# print(f"{RESET}[{BGREEN}OK{RESET}] Обновлён {YELLOW}PIP{RESET}.")
# else:
# updatepip = os.system('"{}" -m pip install -U '.format(sys.executable) + '--upgrade pip' + " -q --no-warn-script-location")
# print(f"{RESET}[{BGREEN}OK{RESET}] Обновлён {YELLOW}PIP{RESET}.")
# except:
# updatepip = os.system('"{}" -m pip install -U '.format(sys.executable) + '--upgrade pip' + " -q --no-warn-script-location")
# if updatepip != 0:
# sys.exit(f"{RESET}[{BRED}ERR{RESET}] Обновление {YELLOW}PIP {RESET}провалилось.")
if getConfig("firstboot"):
if getOS() == "android":
while True:
os.system('clear')
confirmation = input(f'{BRED}Внимание! {RESET}AutoZoom практически не оптимизирован под {CYAN}Android{RESET}.\nПродолжая использовать программу на ОС кроме {CYAN}Windows {RESET}вы действуете на свой страх и риск.\nПолноценная поддержка операционной системы Android не планируется.\nДля хоть какой-то работы нужно установить Zoom\nи заранее его настроить.\n\nВведите {BGREEN}Да {RESET}если вас не пугает указанное выше.\nВведите {BRED}Нет {RESET}если вас это не устраивает, программа сама закроется.\n\n > ')
if confirmation.lower() in yes_list:
setConfig("firstboot", False)
setConfig("obs_core", "Disabled")
setConfig("obs_exe", "Disabled")
setConfig("use_rpc", False)
break
elif confirmation.lower() in no_list:
setConfig("firstboot", True)
sys.exit()
break
else:
continue
elif getOS() == "unix":
while True:
os.system('clear')
confirmation = input(f'{BRED}Внимание! {RESET}AutoZoom плохо оптимизирован под {CYAN}Linux {RESET}и {CYAN}MacOS{RESET}.\nПродолжая использовать программу на ОС кроме {CYAN}Windows {RESET}вы действуете на свой страх и риск.\nПолноценная поддержка UNIX систем реализована не будет.\nДля хоть какой-то работы нужно установить Zoom\nи заранее его настроить.\n\nВведите {BGREEN}Да {RESET}если вас не пугает указанное выше.\nВведите {BRED}Нет {RESET}если вас это не устраивает, программа сама закроется.\n\n > ')
if confirmation.lower() in yes_list:
setConfig("firstboot", False)
setConfig("obs_core", "Disabled")
setConfig("obs_exe", "Disabled")
break
elif confirmation.lower() in no_list:
setConfig("firstboot", True)
sys.exit()
break
else:
continue
elif getOS() == "windows":
setConfig("firstboot", False)
#########################################################
libs = []
###################################
try:
import easygui
except ModuleNotFoundError:
appendLog("No module easygui")
libs.append("easygui")
###################################
try:
import tkinter
except ModuleNotFoundError:
appendLog("No module tkinter")
libs.append("tkinter")
if getOS() == "windows":
try:
import easygui
except ModuleNotFoundError:
appendLog("No module easygui")
libs.append("easygui")
###################################
try:
import tkinter
except ModuleNotFoundError:
appendLog("No module tkinter")
libs.append("tkinter")
###################################
try:
from swinlnk.swinlnk import SWinLnk
except ModuleNotFoundError:
appendLog("No module swinlnk")
libs.append("swinlnk")
###################################
try:
import keyboard
@ -70,11 +108,17 @@ except ModuleNotFoundError:
appendLog("No module requests")
libs.append("requests")
###################################
try:
import playsound
except ModuleNotFoundError:
appendLog("No module playsound")
libs.append("playsound")
if getOS() != "android":
try:
from playsound import playsound
except ModuleNotFoundError:
appendLog("No module playsound")
libs.append("playsound")
else:
try:
os.system('pkg install play-audio')
except:
appendLog("Could not install play-audio")
###################################
try:
from zipfile import ZipFile
@ -100,6 +144,7 @@ except ModuleNotFoundError:
appendLog("No module pypresence")
libs.append("pypresence")
###################################
if len(libs) > 0:
print("Не хватает нужных модулей, пробуем установить...\nЭто может занять некоторое время. Пожалуйста, не закрывайте программу.")
appendLog('Missing some modules, trying to install them')
@ -125,19 +170,26 @@ if len(libs) > 0:
print(f"{RESET}[{BGREEN}OK{RESET}] Все модули были успешно установлены.")
try:
import easygui
import tkinter
if getOS() == "windows":
import easygui
import tkinter
from swinlnk.swinlnk import SWinLnk
import keyboard
import ast
import inputimeout
import telegram_send
import wget
import requests
import playsound
import asyncio
import getpass
if getOS() != "android":
from playsound import playsound
from zipfile import ZipFile
from pypresence import Presence
except ModuleNotFoundError:
sys.exit(f"\n#############################################################################\n{BGREEN} Пожалуйста, перезапустите программу для продолжения!{RESET}\n Если это сообщение видно не впервые - напишите {BRED}@profitroll {RESET}в {CYAN}Telegram {RESET}или\n включите {BRED}debug {RESET}в {BRED}files/config.json {RESET}и решите проблему самостоятельно.\n#############################################################################")
#########################################################

180
main.py
View File

@ -11,9 +11,13 @@ from pathlib import Path
from functions import *
os.system("title")
appendLog('main.py start initialized', startup=True)
from daemon import main, editor, settings, clear
setTitle("", getOS())
from daemon import main
import settings
import editor
import rpc
if getConfig("use_colors"):
@ -32,12 +36,12 @@ import keyboard
import getpass
from zipfile import ZipFile
version = 2.0
version = 2.1
path = Path(__file__).resolve().parent
def mainMenu():
try:
os.system("title AutoZoom (Главная)")
setTitle("AutoZoom (Главная)", getOS())
global version
global path
@ -50,29 +54,41 @@ def mainMenu():
print(f'{RESET}Загрузка данных о последней версии...')
try:
os.system("title Загрузка данных...")
setTitle("Загрузка данных...", getOS())
serv_ver = requests.get("https://www.end-play.xyz/AutoZoomVersion.txt").text
os.system("title AutoZoom (Главная)")
setTitle("AutoZoom (Главная)", getOS())
ignore = False
clear()
except Exception as exp:
appendLog(f'Version number load failed {exp}')
os.system("title Ошибка загрузки данных")
setTitle("Ошибка загрузки данных", getOS())
print(f'Не удалось загрузить данные о последней версии.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://status.end-play.xyz/786373747{RESET}')
none = input('\n > ')
rpc.disconnect()
sys.exit()
todo = input(f'\nВведите {BRED}ignore {RESET}чтобы выключить проверку обновлений и продолжить\nлибо введите что угодно иное чтобы закрыть программу.\n\n > {BRED}')
if todo.lower() == 'ignore':
setConfig("update_check", False)
serv_ver = ''
appendLog('Skipping update check')
setTitle("AutoZoom (Главная)", getOS())
ignore = True
clear()
else:
rpc.disconnect()
sys.exit()
if float(serv_ver) > float(version):
if ignore == False and float(serv_ver) > float(version):
show_version = f' ({BRED}!{RESET})'
else:
show_version = ''
else:
os.system("title AutoZoom (Главная)")
show_version = ''
show_version = f' ({BRED}!{RESET})'
setTitle("AutoZoom (Главная)", getOS())
serv_ver = 'disabled'
appendLog('Skipping update check')
clear()
print(f'{BBLACK}»{RESET} Главное меню\n')
print(f' {BRED}1.{RESET} Запуск')
@ -81,7 +97,11 @@ def mainMenu():
print(f' {BRED}4.{RESET} Обновление{show_version}')
print(f' {BRED}5.{RESET} Помощь и связь')
print(f' {BRED}6.{RESET} Закрыть приложение')
menu_choose = input(f'\n > {BRED}')
if getConfig("debug"):
print(f' {BRED}10.{RESET} Меню разработчика')
menu_choose = input(f'\n {RESET}> {BRED}')
print(RESET)
if menu_choose == '1':
@ -90,11 +110,11 @@ def mainMenu():
elif menu_choose == '2':
appendLog('Went to editor')
rpc.inEditor()
editor()
editor.editor()
elif menu_choose == '3':
appendLog('Went to settings')
rpc.inSettings()
settings()
settings.settings()
elif menu_choose == '4':
appendLog('Went to updater')
rpc.inUpdater()
@ -104,10 +124,17 @@ def mainMenu():
rpc.inHelp()
helpMenu()
elif menu_choose == '6':
appendLog('Exited AutoZoom')
appendLog('Exited AutoZoom from main menu', shutdown=True)
rpc.disconnect()
clear()
sys.exit()
elif menu_choose == '10':
if getConfig("debug"):
appendLog('Went to help')
rpc.inDebug()
devMenu()
else:
clear()
else:
clear()
continue
@ -128,7 +155,7 @@ def os_arch():
def helpMenu():
try:
while True:
os.system("title AutoZoom (Помощь)")
setTitle("AutoZoom (Помощь)", getOS())
appendLog('Help menu opened')
clear()
global version
@ -142,6 +169,7 @@ def helpMenu():
print(f' {BRED}5.{RESET} Связаться с автором')
print(f' {BRED}6.{RESET} Сводка информации')
print(f' {BRED}7.{RESET} В главное меню')
help_choose = input(f'\n > {BRED}')
if help_choose == '1':
@ -196,7 +224,18 @@ def helpMenu():
clear()
if help_choose == '6':
clear()
appendLog(f'Showing system information:\n=============================================\nHelpful data for fault search:\n\nOS: {platform.system()}\nRelease: {platform.release()}\nArch: {os_arch()}\nPy Ver: {platform.python_version()}\nPIP Ver: {pip.__version__}\nImpl: {platform.python_implementation()}\nRev: {platform.python_revision()}\nPy Path: {sys.path[4]}\nAZ Ver: {version}\nAZ User: {getpass.getuser()}\nAZ Path: {path}\n=============================================')
if getState("RBTray.exe"):
rbtray = f'{BGREEN}Активен{RESET}'
else:
rbtray = f'{BRED}Неактивен{RESET}'
if rpc.connected:
dsrpc = f'{BGREEN}Активен{RESET}'
else:
dsrpc = f'{BRED}Неактивен{RESET}'
appendLog(f'Showing system information:\n=============================================\nHelpful data for fault search:\n\nOS: {platform.system()}\nRelease: {platform.release()}\nArch: {os_arch()}\nPy Ver: {platform.python_version()}\nPIP Ver: {pip.__version__}\nImpl: {platform.python_implementation()}\nRev: {platform.python_revision()}\nPy Path: {sys.path[4]}\nAZ Ver: {version}\nAZ User: {getpass.getuser()}\nAZ User Home: {Path.home()}\nAZ Path: {path}\nRBTray: {str(getState("RBTray.exe"))}\nRPC: {str(rpc.connected)}\n=============================================')
print(f'{BBLACK}»{RESET} Информация о системе\n')
print(' Система:')
print(f' {BBLACK}{RESET} ОС: {YELLOW}{platform.system()}{RESET}')
@ -211,13 +250,17 @@ def helpMenu():
print('\n AutoZoom:')
print(f' {BBLACK}{RESET} Версия: {YELLOW}{version}{RESET}')
print(f' {BBLACK}{RESET} Пользователь: {YELLOW}{getpass.getuser()}{RESET}')
print(f' {BBLACK}{RESET} Папка пользователя: {BRED}{Path.home()}{RESET}')
print(f' {BBLACK}{RESET} Расположение: {BRED}{path}{RESET}')
print('\n Интеграции:')
print(f' {BBLACK}{RESET} RBTray: {rbtray}')
print(f' {BBLACK}{RESET} Discord RPC: {dsrpc}')
none = input('\n > ')
clear()
elif help_choose == '7':
rpc.inMenu()
clear()
os.