Compare commits

...

17 Commits
v1.8 ... master

Author SHA1 Message Date
Profitroll c0076bf5aa Updated to v2.6
Внесены различные изменения в RPC и конфигурацию
2022-02-01 17:38:27 +02:00
Profitroll 09a3d66656 Updated to v2.6 2022-02-01 17:34:08 +02:00
Profitroll 504b748789 Updated to v2.6
Temporary fix for Python 3.10 RPC issue. (https://github.com/profitrollgame/AutoZoom/issues/1)
2022-02-01 17:32:46 +02:00
Profitroll fe0a1a5202 Removed GitBook
Returned back to normal GitHub Wiki
2022-01-23 00:09:03 +02:00
Profitroll 4aa988f236
GitBook: [#4] Added other pages 2021-11-29 13:19:33 +00:00
Profitroll 3cb46f2b26
GitBook: [#3] Icons 2021-11-29 13:11:03 +00:00
Profitroll 0cdf5d8ce1
GitBook: [#1] Вики начала разбиваться на странички 2021-11-29 12:28:32 +00:00
Profitroll 25bf0064b7 Updated to v2.5 2021-11-05 18:47:43 +02:00
Profitroll 363de17c08 Update 2.4 2021-11-03 09:20:15 +02:00
Profitroll 66ec64fa30 Обновление v2.3 2021-08-01 11:14:33 +03:00
Profitroll a573edc03a Merge branch 'master' of https://github.com/profitrollgame/AutoZoom 2021-05-08 01:28:45 +03:00
Profitroll 5d2da989d6 Обновление v2.2 2021-05-08 01:28:41 +03:00
Profitroll 461729fa9e
Обновление 2.1 2021-04-30 03:30:20 +03:00
Profitroll 34fe5f0063 Обновление 2.1 2021-04-30 03:28:26 +03:00
Profitroll 6df060142a Обновление 2.1 2021-04-30 03:25:36 +03:00
Profitroll 2183db0515 Обновление 2.0 2021-04-24 03:08:43 +03:00
Profitroll 310faaf79b
Мелкие изменения
Добавлен центр поддержки.
2021-04-23 02:39:12 +03:00
11 changed files with 2516 additions and 1384 deletions

View File

@ -1,5 +1,6 @@
## Добро пожаловать в AutoZoom! ## Добро пожаловать в AutoZoom!
Contact me [directly](https://t.me/profitroll) or via [Support Center](https://www.tidio.com/talk/ydqcvfvgkud3jjk2482uaesvjpeohlh3) if you need English translation.
В этом файле описаны все шаги которые нужно выполнить для работы с программой. В этом файле описаны все шаги которые нужно выполнить для работы с программой.
### Содержание ### Содержание
@ -12,6 +13,7 @@
* [GitHub вики проекта](https://github.com/profitrollgame/autozoom/wiki) * [GitHub вики проекта](https://github.com/profitrollgame/autozoom/wiki)
* [Обратная связь и предложения](https://t.me/profitroll) * [Обратная связь и предложения](https://t.me/profitroll)
* [Сообщить об ошибке/баге](https://github.com/profitrollgame/autozoom/issues) * [Сообщить об ошибке/баге](https://github.com/profitrollgame/autozoom/issues)
* [Центр поддержки](https://www.tidio.com/talk/ydqcvfvgkud3jjk2482uaesvjpeohlh3)
### 1. Информация и описание программы ### 1. Информация и описание программы
@ -37,9 +39,15 @@ AutoZoom создан для автоматизации присоединени
2. Попробуйте запустить ваш `start.bat` в папке `AutoZoom`. Возможно, он сам отправит вас на страницу загрузки Python. 2. Попробуйте запустить ваш `start.bat` в папке `AutoZoom`. Возможно, он сам отправит вас на страницу загрузки Python.
Если же этого не произошло - сделать это можно вручную с официального сайта или из магазина приложений Если же этого не произошло - сделать это можно вручную с официального сайта или из магазина приложений
Microsoft Store (https://www.microsoft.com/ru-ru/p/python-37/9nj46sx7x90p?activetab=pivot:overviewtab&source=lp). Microsoft Store (https://www.microsoft.com/ru-ru/p/python-37/9nj46sx7x90p?activetab=pivot:overviewtab&source=lp).
В случае установки без MS Store - достаточно скачать инсталлер с оф. сайта Python (https://www.python.org/downloads/).
Для установки на Linux необходимо использовать стандартный менеджер пакетов (apt, yum, rpm и т.д.)
Инструкции по установке версий Python3 на Linux вы можете самостоятельно в зависимости от дистрибутива
и желаемой к установке версии Python3.
Для установки на Android (в данном случае - внутри Termux) нужно ввести `pkg install python`.
3. Дважды нажмите на `start.bat` и выберите пункт "Редактор" чтобы редактировать ваши уроки на любой 3. Дважды нажмите на `start.bat` и выберите пункт "Редактор" чтобы редактировать ваши уроки на любой
удобный день. Введите все нужные данные. Название конференции, дату, время, ссылку на приглашение. удобный день. Введите все нужные данные. Название конференции, дату, время, ссылку на приглашение.
В случае установки на Linux/Android - скрипт запуска будет `start.sh` и его можно запустить через `bash ./start.sh`
4. Теперь самая важная часть. Установите Zoom (https://zoom.us/download) на свой ПК. 4. Теперь самая важная часть. Установите Zoom (https://zoom.us/download) на свой ПК.
Запустите его и зарегистрируйтесь/войдите в аккаунт. При входе ОБЯЗАТЕЛЬНО Запустите его и зарегистрируйтесь/войдите в аккаунт. При входе ОБЯЗАТЕЛЬНО
@ -141,4 +149,4 @@ AutoZoom и выбрать пункт "Настройки". Затем выбе
Приятного использования! Приятного использования!
P.S.: Отдельное спасибо Kusyaka за помощь в создании сего творения. P.S.: Отдельное спасибо Kusyaka за помощь в создании сего творения.
Без тебя, если честно, у меня бы ничего не вышло, дружище <3 Без тебя, если честно, у меня бы ничего не вышло, дружище <3

1402
daemon.py

File diff suppressed because it is too large Load Diff

692
editor.py Normal file
View File

@ -0,0 +1,692 @@
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):
if getConfig("debug"):
print(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}')
lessname = strCleaner(lessname)
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(" ", "")
lesslink = strCleaner(lesslink)
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}')
lessname = strCleaner(lessname)
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}')
if lesstime == '':
finallesstime = lessons_got[edi]["time"]
lesstime = lessons_got[edi]["time"]
local_lessons.update({"time": lesstime})
else:
try:
finallesstime = (datetime.strptime(lesstime, "%H:%M"))
finallesstime = lesstime
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
except:
continue
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(" ", "")
lesslink = strCleaner(lesslink)
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 debugLesson():
try:
from profile import debuglink, name
appendLog('Debug link added to the list')
local_lessons = {}
lessons_got = getLessons()
local_lessons.update({"name": "Debug Lesson"})
local_lessons.update({"date": date.today().strftime("%d.%m.%Y")})
local_lessons.update({"time": "00:00"})
local_lessons.update({"link": debuglink})
local_lessons.update({"repeat": False})
local_lessons.update({"repeat_day": None})
local_lessons.update({"record": True})
lessons_got.append(dict(local_lessons))
sortLessons(lessons_got)
saveJson(files_folder+'lessons.json', lessons_got)
return f"{RESET}Конференция для отладки профиля {CYAN}{name} {RESET}была добавлена."
except:
return f"{RESET}Для отладки нужен профиль {BRED}profile.py {RESET}со ссылкой на конференцию {BRED}debuglink {RESET}и именем {BRED}name{RESET}."
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

@ -1,15 +0,0 @@
{
"debug": false,
"shutdown_timeout": 30,
"shutdown_enabled": true,
"start": "shift+f7",
"stop": "shift+f8",
"telegram_enabled": false,
"use_colors": true,
"run_fullscreen": false,
"use_rpc": true,
"sounds": true,
"end_mode": "shutdown",
"obs_exe": null,
"obs_core": null
}

View File

@ -1,73 +1,435 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pip import pip
import time
import json import json
import os import os
import shutil
import gzip
import getpass
from datetime import datetime
from pathlib import Path from pathlib import Path
from subprocess import check_output
path = Path(__file__).resolve().parent path = Path(__file__).resolve().parent
sounds_folder = str(Path(str(path)+"/sounds/")) + os.sep sounds_folder = str(Path(str(path)+"/sounds/")) + os.sep
files_folder = str(Path(str(path)+"/files/")) + 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": False,
"start": "shift+f7",
"stop": "shift+f8",
"telegram_enabled": False,
"use_colors": True,
"run_fullscreen": False,
"rpc_use": True,
"rpc_id": "800049969960058882",
"sounds": True,
"remove_old": True,
"end_mode": "shutdown",
"obs_exe": None,
"obs_core": None,
"obs_delay": 10,
"update_check": True,
"write_logs": True,
"log_size": 512,
"sound_ended": "ended",
"sound_recordstart": "recordstart",
"sound_recordstop": "recordstop",
"sound_shutdown": "shutdown",
"sound_started": "started",
"sound_warning": "warning"
}
# Функция возвращающая надпись 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')
# Импортирование игралки звуков
try:
if getOS() == "windows":
import winsound
from playsound import playsound
elif getOS() == "unix":
from playsound import playsound
except:
pass
# Установка заголовка окна 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
i = 0
while i < 2:
try:
log = os.stat(logs_folder + 'latest.log')
if (log.st_size / 1024) > getConfig("log_size"):
with open(logs_folder + 'latest.log', 'rb') as f_in:
with gzip.open(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if getConfig("debug"):
print(f'Copied {logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip')
open(logs_folder + 'latest.log', 'w').close()
i = 2
except FileNotFoundError:
if getConfig("debug"):
print('Log file not found')
time.sleep(2)
try:
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
try:
os.mkdir(logs_folder)
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
if getConfig("debug"):
time.sleep(2)
print('Log file could not be created')
i += 1
# Функция добавления в лог
def appendLog(message, startup=False, shutdown=False):
if getConfig("write_logs"):
global logs_folder
checkSize()
try:
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
try:
os.mkdir(logs_folder)
log = open(logs_folder + 'latest.log', 'a')
open(logs_folder + 'latest.log', 'a').close()
except:
time.sleep(2)
print('Log file could not be created')
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 strCleaner(string):
output = string.replace('"', '\"').replace('\n', '')
appendLog(f"String cleaned: {output}")
return output
# Функция добавления переменных, если их нет
def repairConfig(some_dic):
def getConfig(some_var):
global files_folder global files_folder
global default_config
for key in default_config:
try:
some_dic[key]
except KeyError:
some_dic[key] = default_config[key]
saveJson(files_folder+'config.json', some_dic)
# Функция изменения переменной конфигурации
def setConfig(some_var, some_val):
global files_folder
global default_config
if os.path.exists(files_folder): if os.path.exists(files_folder):
if not os.path.exists(files_folder+'config.json'): if not os.path.exists(files_folder+'config.json'):
temp_config_list = {}
temp_config_list["debug"] = False temp_config_list = default_config
temp_config_list["shutdown_timeout"] = 30 temp_config_list[some_var] = some_val
temp_config_list["shutdown_enabled"] = True
temp_config_list["start"] = "shift+f7" saveJson(files_folder+'config.json', temp_config_list)
temp_config_list["stop"] = "shift+f8"
temp_config_list["telegram_enabled"] = False else:
temp_config_list["use_colors"] = True
temp_config_list["run_fullscreen"] = False try:
temp_config_list["use_rpc"] = True
temp_config_list["sounds"] = True with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
temp_config_list["end_mode"] = "shutdown"
temp_config_list["obs_exe"] = None config_list = json.load(json_file)
temp_config_list["obs_core"] = None 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) saveJson(files_folder+'config.json', temp_config_list)
return temp_config_list[some_var] return temp_config_list[some_var]
else: else:
try: try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file: with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file) config_list = json.load(json_file)
json_file.close() json_file.close()
return config_list[some_var]
try:
return config_list[some_var]
except:
try:
try:
setConfig(some_var, default_config[some_var])
return default_config[some_var]
except:
repairConfig(config_list)
config_list = json.load(json_file)
json_file.close()
return config_list[some_var]
except:
return default_config[some_var]
except: except:
return "Error" return "Error"
else: else:
os.mkdir(files_folder) os.mkdir(files_folder)
if not os.path.exists(files_folder+'config.json'): if not os.path.exists(files_folder+'config.json'):
temp_config_list = {} temp_config_list = default_config
temp_config_list["debug"] = False
temp_config_list["shutdown_timeout"] = 30
temp_config_list["shutdown_enabled"] = True
temp_config_list["start"] = "shift+f7"
temp_config_list["stop"] = "shift+f8"
temp_config_list["telegram_enabled"] = False
temp_config_list["use_colors"] = True
temp_config_list["run_fullscreen"] = False
temp_config_list["use_rpc"] = True
temp_config_list["sounds"] = True
temp_config_list["end_mode"] = "shutdown"
temp_config_list["obs_exe"] = None
temp_config_list["obs_core"] = None
saveJson(files_folder+'config.json', temp_config_list) saveJson(files_folder+'config.json', temp_config_list)
return temp_config_list[some_var] return temp_config_list[some_var]
else: else:
try: try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file: with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file) config_list = json.load(json_file)
json_file.close() json_file.close()
return config_list[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: except:
return "Error" 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): def saveJson(filename, value):
with open(filename, 'w', encoding="utf-8") as f: with open(filename, 'w', encoding="utf-8") as f:
json.dump(value, f, indent=4, ensure_ascii=False) json.dump(value, f, indent=4, ensure_ascii=False)

View File

@ -2,87 +2,153 @@
import os, sys import os, sys
from colors import * 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
# Работает не очень стабильно при отсутствии интернета if getConfig("firstboot"):
# try:
# if getConfig("debug"): if getOS() == "android":
# updatepip = os.system('"{}" -m pip install -U '.format(sys.executable) + '--upgrade pip') while True:
# print(f"{RESET}[{BGREEN}OK{RESET}] Обновлён {YELLOW}PIP{RESET}.") os.system('clear')
# else: 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 > ')
# 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}.") if confirmation.lower() in yes_list:
# except: setConfig("firstboot", False)
# updatepip = os.system('"{}" -m pip install -U '.format(sys.executable) + '--upgrade pip' + " -q --no-warn-script-location") setConfig("obs_core", "Disabled")
setConfig("obs_exe", "Disabled")
# if updatepip != 0: setConfig("use_rpc", False)
# sys.exit(f"{RESET}[{BRED}ERR{RESET}] Обновление {YELLOW}PIP {RESET}провалилось.") 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 = [] libs = []
################################### ###################################
try: if getOS() == "windows":
import easygui try:
except ModuleNotFoundError: import easygui
libs.append("easygui") except ModuleNotFoundError:
################################### appendLog("No module easygui")
try: libs.append("easygui")
import tkinter ###################################
except ModuleNotFoundError: try:
libs.append("tkinter") 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: try:
import keyboard import keyboard
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module keyboard")
libs.append("keyboard") libs.append("keyboard")
################################### ###################################
try: try:
import ast import ast
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module ast")
libs.append("ast") libs.append("ast")
################################### ###################################
try: try:
import inputimeout import inputimeout
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module inputimeout")
libs.append("inputimeout") libs.append("inputimeout")
################################### ###################################
try: try:
import telegram_send import telegram_send
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module telegram_send")
libs.append("telegram_send") libs.append("telegram_send")
################################### ###################################
try: try:
import wget import wget
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module wget")
libs.append("wget") libs.append("wget")
################################### ###################################
try: try:
import requests import requests
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module requests")
libs.append("requests") libs.append("requests")
################################### ###################################
try: if getOS() != "android":
import playsound try:
except ModuleNotFoundError: from playsound import playsound
libs.append("playsound") except ModuleNotFoundError:
appendLog("No module playsound")
libs.append("playsound")
else:
try:
if not "play-audio" in os.popen('pkg list-all').read():
os.system('pkg install play-audio')
except:
appendLog("Could not install play-audio")
################################### ###################################
try: try:
from zipfile import ZipFile from zipfile import ZipFile
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module zipfile")
libs.append("zipfile") libs.append("zipfile")
################################### ###################################
try: try:
import asyncio import asyncio
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module asyncio")
libs.append("asyncio") libs.append("asyncio")
################################### ###################################
try:
import getpass
except ModuleNotFoundError:
appendLog("No module getpass")
libs.append("getpass")
###################################
try: try:
from pypresence import Presence from pypresence import Presence
except ModuleNotFoundError: except ModuleNotFoundError:
appendLog("No module pypresence")
libs.append("pypresence") libs.append("pypresence")
################################### ###################################
if len(libs) > 0: if len(libs) > 0:
print("Не хватает нужных модулей, пробуем установить...") print("Не хватает нужных модулей, пробуем установить...\nЭто может занять некоторое время. Пожалуйста, не закрывайте программу.")
appendLog('Missing some modules, trying to install them')
for each in libs: for each in libs:
try: try:
@ -94,23 +160,37 @@ if len(libs) > 0:
response = os.system('"{}" -m pip install -U '.format(sys.executable) + each + " -q --no-warn-script-location") response = os.system('"{}" -m pip install -U '.format(sys.executable) + each + " -q --no-warn-script-location")
print(f"{RESET}[{BGREEN}OK{RESET}] Установлен модуль {YELLOW}{each}{RESET}.") print(f"{RESET}[{BGREEN}OK{RESET}] Установлен модуль {YELLOW}{each}{RESET}.")
appendLog(f'Module {each} installed')
if response != 0: if response != 0:
appendLog(f'Failed to install {each}')
sys.exit(f"{RESET}[{BRED}ERR{RESET}] Установка {YELLOW}{each} {RESET}провалилась.") sys.exit(f"{RESET}[{BRED}ERR{RESET}] Установка {YELLOW}{each} {RESET}провалилась.")
appendLog('Everything seems to be installed')
print(f"{RESET}[{BGREEN}OK{RESET}] Все модули были успешно установлены.") print(f"{RESET}[{BGREEN}OK{RESET}] Все модули были успешно установлены.")
try: try:
import easygui if getOS() == "windows":
import tkinter import easygui
import tkinter
from swinlnk.swinlnk import SWinLnk
import keyboard import keyboard
import ast import ast
import inputimeout import inputimeout
import telegram_send import telegram_send
import wget import wget
import requests import requests
import playsound
import asyncio import asyncio
import getpass
if getOS() != "android":
from playsound import playsound
from zipfile import ZipFile from zipfile import ZipFile
from pypresence import Presence from pypresence import Presence
except ModuleNotFoundError: 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#############################################################################") sys.exit(f"\n#############################################################################\n{BGREEN} Пожалуйста, перезапустите программу для продолжения!{RESET}\n Если это сообщение видно не впервые - напишите {BRED}@profitroll {RESET}в {CYAN}Telegram {RESET}или\n включите {BRED}debug {RESET}в {BRED}files/config.json {RESET}и решите проблему самостоятельно.\n#############################################################################")
######################################################### #########################################################

339
main.py
View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys import sys
import pip
import webbrowser import webbrowser
import os import os
import time import time
@ -8,11 +9,17 @@ import platform
import subprocess import subprocess
from pathlib import Path from pathlib import Path
import libinstaller
from functions import * 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 import rpc
if getConfig("use_colors"): if getConfig("use_colors"):
@ -23,43 +30,66 @@ else:
BBLACK = BRED = BGREEN = BYELLOW = BBLUE = BMAGENTA = BCYAN = BWHITE = '' BBLACK = BRED = BGREEN = BYELLOW = BBLUE = BMAGENTA = BCYAN = BWHITE = ''
ULINE = REVERSE = '' ULINE = REVERSE = ''
import libinstaller
import wget import wget
import requests import requests
import keyboard import keyboard
import getpass
from zipfile import ZipFile from zipfile import ZipFile
version = 1.8 version = 2.6
path = Path(__file__).resolve().parent path = Path(__file__).resolve().parent
def mainMenu(): def mainMenu():
try: try:
os.system("title AutoZoom (Главная)") setTitle("AutoZoom (Главная)", getOS())
global version global version
global path global path
appendLog('Main menu opened')
rpc.inMenu() rpc.inMenu()
while True: while True:
print(f'{RESET}Загрузка данных о последней версии...') if getConfig("update_check"):
try: print(f'{RESET}Загрузка данных о последней версии...')
os.system("title Загрузка данных...")
serv_ver = requests.get("https://www.end-play.xyz/AutoZoomVersion.txt").text
os.system("title AutoZoom (Главная)")
clear()
except:
os.system("title Ошибка загрузки данных")
print(f'Не удалось загрузить данные о последней версии.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://status.end-play.xyz/786373747{RESET}')
none = input('\n > ')
rpc.disconnect()
sys.exit()
if float(serv_ver) > float(version):
show_version = f' ({BRED}!{RESET})'
else:
show_version = ''
try:
setTitle("Загрузка данных...", getOS())
serv_ver = requests.get("https://www.end-play.xyz/AutoZoomVersion.txt").text
setTitle("AutoZoom (Главная)", getOS())
ignore = False
clear()
except Exception as exp:
appendLog(f'Version number load failed {exp}')
setTitle("Ошибка загрузки данных", getOS())
print(f'Не удалось загрузить данные о последней версии.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://stats.uptimerobot.com/OqwR9iAqBg{RESET}')
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 ignore == False and float(serv_ver) > float(version):
show_version = f' ({BRED}!{RESET})'
else:
show_version = ''
else:
show_version = f' ({BRED}!{RESET})'
setTitle("AutoZoom (Главная)", getOS())
serv_ver = 'disabled'
appendLog('Skipping update check')
clear()
print(f'{BBLACK}»{RESET} Главное меню\n') print(f'{BBLACK}»{RESET} Главное меню\n')
print(f' {BRED}1.{RESET} Запуск') print(f' {BRED}1.{RESET} Запуск')
print(f' {BRED}2.{RESET} Редактор') print(f' {BRED}2.{RESET} Редактор')
@ -67,27 +97,44 @@ def mainMenu():
print(f' {BRED}4.{RESET} Обновление{show_version}') print(f' {BRED}4.{RESET} Обновление{show_version}')
print(f' {BRED}5.{RESET} Помощь и связь') print(f' {BRED}5.{RESET} Помощь и связь')
print(f' {BRED}6.{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) print(RESET)
if menu_choose == '1': if menu_choose == '1':
appendLog('Went to daemon')
main('menu') main('menu')
elif menu_choose == '2': elif menu_choose == '2':
appendLog('Went to editor')
rpc.inEditor() rpc.inEditor()
editor() editor.editor()
elif menu_choose == '3': elif menu_choose == '3':
appendLog('Went to settings')
rpc.inSettings() rpc.inSettings()
settings() settings.settings()
elif menu_choose == '4': elif menu_choose == '4':
appendLog('Went to updater')
rpc.inUpdater() rpc.inUpdater()
updater(serv_ver, version) updater(serv_ver, version)
elif menu_choose == '5': elif menu_choose == '5':
appendLog('Went to help')
rpc.inHelp() rpc.inHelp()
helpMenu() helpMenu()
elif menu_choose == '6': elif menu_choose == '6':
appendLog('Exited AutoZoom from main menu', shutdown=True)
rpc.disconnect() rpc.disconnect()
clear() clear()
sys.exit() sys.exit()
elif menu_choose == '10':
if getConfig("debug"):
appendLog('Went to help')
rpc.inDebug()
devMenu()
else:
clear()
else: else:
clear() clear()
continue continue
@ -108,45 +155,109 @@ def os_arch():
def helpMenu(): def helpMenu():
try: try:
while True: while True:
os.system("title AutoZoom (Помощь)") setTitle("AutoZoom (Помощь)", getOS())
appendLog('Help menu opened')
clear() clear()
global version global version
global path global path
print(f'{BBLACK}»{RESET} Меню помощи\n') print(f'{BBLACK}»{RESET} Меню помощи\n')
print(f' {BRED}1.{RESET} Документация') print(f' {BRED}1.{RESET} Документация')
print(f' {BRED}2.{RESET} Telegram проекта') print(f' {BRED}2.{RESET} Сайт проекта')
print(f' {BRED}3.{RESET} Связаться с автором') print(f' {BRED}3.{RESET} Центр поддержки')
print(f' {BRED}4.{RESET} Сводка информации') print(f' {BRED}4.{RESET} Telegram проекта')
print(f' {BRED}5.{RESET} В главное меню') print(f' {BRED}5.{RESET} Связаться с автором')
print(f' {BRED}6.{RESET} Поддержать проект')
print(f' {BRED}7.{RESET} Список поддержавших')
print(f' {BRED}8.{RESET} Сводка информации')
print(f' {BRED}9.{RESET} В главное меню')
help_choose = input(f'\n > {BRED}') help_choose = input(f'\n > {BRED}')
if help_choose == '1': if help_choose == '1':
try: try:
clear() clear()
appendLog('Opened AutoZoom wiki')
webbrowser.open("https://github.com/profitrollgame/autozoom/wiki") webbrowser.open("https://github.com/profitrollgame/autozoom/wiki")
except: except Exception as exp:
clear() clear()
appendLog(f'Failed to open AutoZoom wiki: {exp}')
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://github.com/profitrollgame/autozoom/wiki{RESET}\n\n > ') none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://github.com/profitrollgame/autozoom/wiki{RESET}\n\n > ')
clear() clear()
elif help_choose == '2': elif help_choose == '2':
try: try:
clear() clear()
webbrowser.open("https://t.me/auto_zoom") appendLog('Opened AutoZoom website')
except: webbrowser.open("https://www.end-play.xyz/autozoom")
except Exception as exp:
clear() clear()
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://t.me/auto_zoom{RESET}\n\n > ') appendLog(f'Failed to open AutoZoom website: {exp}')
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://www.end-play.xyz/autozoom{RESET}\n\n > ')
clear() clear()
elif help_choose == '3': elif help_choose == '3':
try: try:
clear() clear()
webbrowser.open("https://t.me/profitroll") appendLog('Opened AutoZoom support center')
except: webbrowser.open("https://www.tidio.com/talk/ydqcvfvgkud3jjk2482uaesvjpeohlh3")
except Exception as exp:
clear() clear()
appendLog(f'Failed to open AutoZoom support center: {exp}')
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://www.tidio.com/talk/ydqcvfvgkud3jjk2482uaesvjpeohlh3{RESET}\n\n > ')
clear()
elif help_choose == '4':
try:
clear()
appendLog('Opened AutoZoom Telegram group')
webbrowser.open("https://t.me/auto_zoom")
except Exception as exp:
clear()
appendLog(f'Failed to open AutoZoom Telegram group: {exp}')
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://t.me/auto_zoom{RESET}\n\n > ')
clear()
elif help_choose == '5':
try:
clear()
appendLog('Opened AutoZoom\'s developer Telegram')
webbrowser.open("https://t.me/profitroll")
except Exception as exp:
clear()
appendLog(f'Failed to open AutoZoom\'s developer Telegram: {exp}')
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://t.me/profitroll{RESET}\n\n > ') none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://t.me/profitroll{RESET}\n\n > ')
clear() clear()
if help_choose == '4': elif help_choose == '6':
try:
clear()
appendLog('Opened AutoZoom\'s donation page')
webbrowser.open("https://www.end-play.xyz/autozoom/donate")
except Exception as exp:
clear()
appendLog(f'Failed to open AutoZoom\'s donation page: {exp}')
none = input(f'{RESET}Не удалось открыть страницу вашего браузера.\nВы можете открыть адрес самостоятельно: {BRED}https://www.end-play.xyz/autozoom/donate{RESET}\n\n > ')
clear() clear()
elif help_choose == '7':
try:
clear()
print(f'{BBLACK}»{RESET} Список поддержавших проект:\n\n{(requests.get("https://www.end-play.xyz/AutoZoomDonors.txt").content.decode("utf-8")).replace("-", RESET+""+BRED)}{RESET}')
except Exception as exp:
clear()
appendLog(f'Failed to load donation list {exp}')
print(f'{RESET}Не удалось загрузить данные о списке поддержавших проект.\nВы можете посмотреть его самостоятельно: {BRED}https://www.end-play.xyz/AutoZoomDonors.txt')
none = input('\n > ')
clear()
if help_choose == '8':
clear()
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(f'{BBLACK}»{RESET} Информация о системе\n')
print(' Система:') print(' Система:')
print(f' {BBLACK}{RESET} ОС: {YELLOW}{platform.system()}{RESET}') print(f' {BBLACK}{RESET} ОС: {YELLOW}{platform.system()}{RESET}')
@ -154,18 +265,24 @@ def helpMenu():
print(f' {BBLACK}{RESET} Разрядность: {YELLOW}{os_arch()}{RESET}') print(f' {BBLACK}{RESET} Разрядность: {YELLOW}{os_arch()}{RESET}')
print('\n Python:') print('\n Python:')
print(f' {BBLACK}{RESET} Версия: {YELLOW}{platform.python_version()}{RESET}') print(f' {BBLACK}{RESET} Версия: {YELLOW}{platform.python_version()}{RESET}')
print(f' {BBLACK}{RESET} Версия PIP: {YELLOW}{pip.__version__}{RESET}')
print(f' {BBLACK}{RESET} Вариант: {YELLOW}{platform.python_implementation()}{RESET}') print(f' {BBLACK}{RESET} Вариант: {YELLOW}{platform.python_implementation()}{RESET}')
print(f' {BBLACK}{RESET} Ревизия: {YELLOW}{platform.python_revision()}{RESET}') print(f' {BBLACK}{RESET} Ревизия: {YELLOW}{platform.python_revision()}{RESET}')
print(f' {BBLACK}{RESET} Расположение: {BRED}{sys.path[4]}{RESET}') print(f' {BBLACK}{RESET} Расположение: {BRED}{sys.path[4]}{RESET}')
print('\n AutoZoom:') print('\n AutoZoom:')
print(f' {BBLACK}{RESET} Версия: {YELLOW}{version}{RESET}') 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(f' {BBLACK}{RESET} Расположение: {BRED}{path}{RESET}')
print('\n Интеграции:')
print(f' {BBLACK}{RESET} RBTray: {rbtray}')
print(f' {BBLACK}{RESET} Discord RPC: {dsrpc}')
none = input('\n > ') none = input('\n > ')
clear() clear()
elif help_choose == '5': elif help_choose == '9':
rpc.inMenu() rpc.inMenu()
clear() clear()
os.system("title AutoZoom (Главная)") setTitle("AutoZoom (Главная)", getOS())
return return
else: else:
clear() clear()
@ -175,17 +292,106 @@ def helpMenu():
clear() clear()
return return
def devMenu():
try:
while True:
setTitle("AutoZoom (Отладка)", getOS())
appendLog('Help menu opened')
clear()
print(f'{BBLACK}»{RESET} Меню отладки\n')
print(f' {BRED}1.{RESET} PlaySound test')
print(f' {BRED}2.{RESET} WinSound test')
print(f' {BRED}3.{RESET} Play-audio test')
print(f' {BRED}4.{RESET} playSound function test')
print(f' {BRED}5.{RESET} OS check test')
print(f' {BRED}6.{RESET} Telegram test')
print(f' {BRED}7.{RESET} Zoom meeting test')
print(f' {BRED}8.{RESET} Color test')
print(f' {BRED}9.{RESET} Exit to menu')
choose = input(f'\n > {BRED}')
if choose == '1':
from playsound import playsound
playsound(sounds_folder+"debug.wav")
continue
elif choose == '2':
import winsound
winsound.PlaySound(sounds_folder+"debug.wav", winsound.SND_FILENAME)
continue
elif choose == '3':
os.system(f'play-audio {sounds_folder}debug.wav')
continue
elif choose == '4':
playSound("debug")
continue
elif choose == '5':
clear()
none = input(f'{RESET}{getOS()}\n\n > ')
continue
elif choose == '6':
clear()
import telegram_send
telegram_send.send(messages=["Telegram message test"], parse_mode="markdown", conf=files_folder+"telegram.conf")
continue
elif choose == '7':
clear()
print(editor.debugLesson())
none = input(f'{RESET}\n > ')
continue
elif choose == '8':
clear()
print(f'{BLACK}███{RED}███{GREEN}███{YELLOW}███{BLUE}███{MAGENTA}███{CYAN}███{WHITE}███')
print(f'{BBLACK}███{BRED}███{BGREEN}███{BYELLOW}███{BBLUE}███{BMAGENTA}███{BCYAN}███{BWHITE}███')
print(f'{RESET}RESET')
print(f'{REVERSE}REVERSE{RESET}')
print(f'{ULINE}UNDERLINE{RESET}')
none = input(RESET+'\n > ')
continue
elif choose == '9':
rpc.inMenu()
clear()
setTitle("AutoZoom (Главная)", getOS())
return
else:
clear()
continue
except KeyboardInterrupt:
rpc.inMenu()
clear()
return
def updater(serv_ver, version): def updater(serv_ver, version):
try: try:
while True: while True:
os.system("title AutoZoom (Обновления)") setTitle("AutoZoom (Обновления)", getOS())
appendLog('Updater menu opened')
clear() clear()
if float(serv_ver) > float(version):
if getConfig("update_check") and float(serv_ver) > float(version):
show_version = f' ({BRED}!{RESET})' show_version = f' ({BRED}!{RESET})'
serv_ver = serv_ver.rstrip('\n') serv_ver = serv_ver.rstrip('\n')
show_action = f'Обновить до {BGREEN}{serv_ver}{RESET}' show_action = f'Обновить до {BGREEN}{serv_ver}{RESET}'
changelog_text = f'Изменения в версии {BGREEN}{serv_ver}{RESET}:' changelog_text = f'Изменения в версии {BGREEN}{serv_ver}{RESET}:'
changelog_footer = '\nОбновитесь чтобы вышеуказанное работало.' changelog_footer = '\nОбновитесь чтобы вышеуказанное работало.'
elif serv_ver == 'disabled':
show_version = ''
show_action = f'Переустановить'
changelog_text = f'Изменения в вашей версии:'
changelog_footer = ''
else: else:
show_version = '' show_version = ''
show_action = f'Переустановить' show_action = f'Переустановить'
@ -197,80 +403,103 @@ def updater(serv_ver, version):
print(f' {BRED}1.{RESET} {show_action}') print(f' {BRED}1.{RESET} {show_action}')
print(f' {BRED}2.{RESET} Список изменений') print(f' {BRED}2.{RESET} Список изменений')
print(f' {BRED}3.{RESET} В главное меню') print(f' {BRED}3.{RESET} В главное меню')
if not getConfig("update_check"):
print(f'\n{BRED}Внимание!{RESET} У вас выключена проверка обновлений.\nЕсли это было сделанно временно - включите её в настройках.')
updater_choose = input(f'\n > {BRED}') updater_choose = input(f'\n > {BRED}')
if updater_choose == '1': if updater_choose == '1':
appendLog('Choosed to update')
while True: while True:
clear() clear()
print(f'{RESET}Подтвердите действие:\n') print(f'{RESET}Подтвердите действие:\n')
print(f' {BRED}1.{RESET} Установить') print(f' {BRED}1.{RESET} Установить')
print(f' {BRED}2.{RESET} Отменить') print(f' {BRED}2.{RESET} Отменить')
updater_decide = input('\n > ') updater_decide = input(f'\n > {BRED}')
print(RESET)
if updater_decide == '1': if updater_decide == '1':
appendLog('Trying to update AutoZoom')
clear() clear()
try: try:
wget.download('https://www.end-play.xyz/AutoZoomLatest.zip', out='AutoZoomLatest.zip') wget.download('https://www.end-play.xyz/AutoZoomLatest.zip', out='AutoZoomLatest.zip')
except: appendLog('Latest zip downloaded')
print(f'Не удалось загрузить архив с последней версией.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://status.end-play.xyz/786373747{RESET}') except Exception as exp:
none = input('\n > ') print(f'{RESET}Не удалось загрузить архив с последней версией.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://status.end-play.xyz/786373747{RESET}')
appendLog(f'Failed to download zip: {exp}')
none = input(f'\n > {BRED}')
continue continue
with ZipFile('AutoZoomLatest.zip', 'r') as zipObj: with ZipFile('AutoZoomLatest.zip', 'r') as zipObj:
zipObj.extractall() zipObj.extractall()
print('Все файлы были успешно загружены') print(f'{RESET}Все файлы были успешно загружены')
appendLog('Latest zip extracted')
if os.path.exists("AutoZoomLatest.zip"): if os.path.exists("AutoZoomLatest.zip"):
os.remove("AutoZoomLatest.zip") os.remove("AutoZoomLatest.zip")
appendLog('Latest used zip deleted')
clear() clear()
none = input('Обновление завершено, перезапустите AutoZoom.\n\n > ') none = input(f'{RESET}Обновление завершено, перезапустите AutoZoom.\n\n > ')
rpc.disconnect() rpc.disconnect()
clear() clear()
print(f'Закрываем приложение {BGREEN}AutoZoom{RESET}...') print(f'{RESET}Закрываем приложение {BGREEN}AutoZoom{RESET}...')
appendLog('Exiting AutoZoom after an update')
sys.exit() sys.exit()
elif updater_decide == '2': elif updater_decide == '2':
clear() clear()
appendLog('Aborted update')
break break
else: else:
continue continue
elif updater_choose == '2': elif updater_choose == '2':
appendLog('Choosed to check changelog')
try: try:
changelog = requests.get("https://www.end-play.xyz/AutoZoomChangelog.txt") changelog = requests.get("https://www.end-play.xyz/AutoZoomChangelog.txt")
changelog.encoding = None changelog.encoding = None
appendLog('Changelog loaded')
clear() clear()
print(f'{RESET}{changelog_text}\n') print(f'{RESET}{changelog_text}\n')
print(changelog.text) print(changelog.content.decode('utf-8'))
print(changelog_footer) print(changelog_footer)
none = input('\n > ') none = input('\n > ')
continue continue
except: except Exception as exp:
clear()
print(f'{RESET}Не удалось загрузить чейнджлог.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://status.end-play.xyz/786373747{RESET}') print(f'{RESET}Не удалось загрузить чейнджлог.\nПроверьте подключение к сети и повторите попытку.\n\nСтатус сервера центра обновлений:\n{BRED}https://status.end-play.xyz/786373747{RESET}')
appendLog(f'Failed to check changelog: {exp}')
none = input('\n > ') none = input('\n > ')
continue continue
elif updater_choose == '3': elif updater_choose == '3':
rpc.inMenu() rpc.inMenu()
clear() clear()
os.system("title AutoZoom (Главная)") appendLog('Returning to main menu')
setTitle("AutoZoom (Главная)", getOS())
return return
else: else:
continue continue
except KeyboardInterrupt: except KeyboardInterrupt:
rpc.inMenu() rpc.inMenu()
clear() clear()
return return
if __name__ == '__main__': if __name__ == '__main__':
os.system("title Загрузка main...")
from functions import getConfig from functions import getConfig
from daemon import clear from daemon import clear, getOS, setTitle
import time import time
setTitle("Загрузка main...", getOS())
clear() clear()
if getConfig("run_fullscreen"): if getConfig("run_fullscreen"):
keyboard.press('alt, enter') keyboard.press('alt, enter')
time.sleep(.25) time.sleep(.25)
keyboard.release('alt, enter') keyboard.release('alt, enter')
os.system("title AutoZoom (Главная)")
setTitle("AutoZoom (Главная)", getOS())
mainMenu() mainMenu()
sys.exit() sys.exit()

297
rpc.py
View File

@ -6,18 +6,40 @@ import sys
from colors import * from colors import *
from functions import * from functions import *
version = '1.8' version = '2.6'
import libinstaller import libinstaller
from pypresence import Presence from pypresence import Presence
client_id = '800049969960058882' client_id = getConfig("rpc_id")
RPC = Presence(client_id,pipe=0) try:
RPC = Presence(client_id,pipe=0)
except Exception as exp:
appendLog(f'Discord RPC failed to initialize status due to {exp}')
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.\nОшибка: {BRED}{exp}{RESET}')
time.sleep(1)
connected = False connected = False
if getConfig("use_rpc"): rpc_dict = {
"large_image": "1024_cover",
"small_image": {
"waiting": "status_waiting",
"conference": "status_lesson",
"menu": "status_menu",
"shutdown": "status_shutdown",
"settings": "status_settings",
"debug": "status_debug",
"editor": "status_editing",
"updating": "status_updating",
"support": "status_support"
},
"large_text": "AutoZoom • v%version%\nhttp://bit.ly/auto_zoom"
}
if getConfig("rpc_use") and getOS != "android":
try: try:
RPC.connect() RPC.connect()
connected = True connected = True
@ -29,12 +51,13 @@ else:
def disconnect(): def disconnect():
global connected global connected
if getConfig("use_rpc"): if getConfig("rpc_use") and getOS != "android":
try: try:
RPC.close() RPC.close()
connected = False connected = False
appendLog('Discord RPC disconnected')
except: except:
pass appendLog('Discord RPC failed to disconnect')
def connect(): def connect():
global connected global connected
@ -42,254 +65,82 @@ def connect():
try: try:
RPC.connect() RPC.connect()
connected = True connected = True
appendLog('Discord RPC connected')
except: except:
pass appendLog('Discord RPC failed to connect')
def reset(): def reset():
if getConfig("use_rpc"): if getConfig("rpc_use") and getOS != "android":
RPC.clear() RPC.clear()
appendLog('Discord RPC status cleared')
def changePresence(sml_img, sml_txt, stt, dtls, start=None, end=None):
def waitLesson(lesson, start):
try: try:
if getConfig("use_rpc"): if getConfig("rpc_use") and getOS != "android":
if connected == False: if connected == False:
connect() connect()
RPC.update(large_image='1024_cover', small_image='status_waiting', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Ожидание', state=f'Ждём начала «{lesson}»', details='Урок не начался', start=start) RPC.update(
large_image=rpc_dict["large_image"],
small_image=rpc_dict["small_image"][sml_img],
large_text=rpc_dict["large_text"].replace("%version%", str(version)),
small_text=sml_txt,
state=stt,
details=dtls,
start=start,
end=end
)
appendLog(f'Discord RPC changed: (Small image: {sml_img}, Small text: {sml_txt}, State: {stt}, Details: {dtls}, Start: {str(start)}, End: {str(end)})')
except AttributeError: except AttributeError:
appendLog('Discord RPC failed to change status')
if getConfig("debug"): if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.') print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1) time.sleep(1)
except AssertionError: except AssertionError:
appendLog('Discord RPC failed to change status')
if getConfig("debug"): if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.') print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1) time.sleep(1)
except Exception as exp:
appendLog(f'Discord RPC failed to change status due to {exp}')
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.\nОшибка: {BRED}{exp}{RESET}')
time.sleep(1)
def onLesson(lesson, start):
try: def waitLesson(conference, start):
if getConfig("use_rpc"): changePresence("waiting", "Ожидание", f"Ждём начала «{conference}»", "Конференция не началась", start=start)
if connected == False:
connect() def onLesson(conference, start):
RPC.update(large_image='1024_cover', small_image='status_lesson', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Урок', state=f'Слушаем «{lesson}»', details='Идёт урок', start=start) changePresence("conference", "Конференция", f"Слушаем «{conference}»", "Идёт конференция", start=start)
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def inMenu(): def inMenu():
try: changePresence("menu", "Главное меню", "Открыт список опций", "В главном меню")
if getConfig("use_rpc"):
if connected == False:
connect()
RPC.update(large_image='1024_cover', small_image='status_menu', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Главное меню', state='Открыт список опций', details='В главном меню')
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def shutdown(end): def shutdown(end):
try: changePresence("shutdown", "Выключение", "Отсчёт до авто-выключения", "Выключение ПК", end=end)
if getConfig("use_rpc"):
if connected == False: def sleepmode(end):
connect() changePresence("shutdown", "Спящий режим", "Отсчёт до авто-засыпания", "Спящий режим ПК", end=end)
RPC.update(large_image='1024_cover', small_image='status_shutdown', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Выключение', state='Отсчёт до авто-выключения', details='Выключение ПК', end=end)
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def inSettings(): def inSettings():
try: changePresence("settings", "Настройки", "Открыты настройки", "В главном меню")
if getConfig("use_rpc"):
if connected == False: def inDebug():
connect() changePresence("debug", "Отладка", "Открыто меню отладки", "В меню разработчика")
RPC.update(large_image='1024_cover', small_image='status_settings', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Настройки', state='Открыты настройки', details='В главном меню')
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def inEditor(): def inEditor():
try: changePresence("editor", "Редактор", "Открыт редактор", "В главном меню")
if getConfig("use_rpc"):
if connected == False:
connect()
RPC.update(large_image='1024_cover', small_image='status_editing', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Редактор', state='Открыт редактор', details='В главном меню')
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def inUpdater(): def inUpdater():
try: changePresence("updating", "Обновление", "Открыт центр обновлений", "В главном меню")
if getConfig("use_rpc"):
if connected == False:
connect()
RPC.update(large_image='1024_cover', small_image='status_updating', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Обновление', state='Открыт центр обновлений', details='В главном меню')
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def inHelp(): def inHelp():
try: changePresence("support", "Помощь", "Открыта помощь", "В главном меню")
if getConfig("use_rpc"):
if connected == False:
connect()
RPC.update(large_image='1024_cover', small_image='status_support', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Помощь', state='Открыта помощь', details='В главном меню')
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
except AssertionError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
def lessonEnded():
changePresence("waiting", "Ожидание", "Ждём указаний", "Все конференции закончились")
if __name__ == "__main__": if __name__ == "__main__":
try: changePresence("settings", "Отладка", "Модуль Discord RPC запущен в режиме тестирования", "Режим отладки")
RPC.connect()
RPC.update(large_image='1024_cover', small_image='status_settings', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Отладка', state='Модуль Discord RPC запущен в режиме тестирования', details='Режим отладки')
except AttributeError:
if getConfig("debug"):
print(f'{RESET}Модуль {BRED}Discord RPC {RESET}не смог подключиться.\nВозможно, ваш {CYAN}Discord {RESET}не открыт.')
time.sleep(1)
################################################################################
# Неудачная попытка работы с discord_rpc. Потом, быть может, попробую ещё раз. #
################################################################################
# import discord_rpc
# import time
# if __name__ == "__main__":
# def readyCallback(current_user):
# print('Our user: {}'.format(current_user))
# def disconnectedCallback(codeno, codemsg):
# print('Disconnected from Discord rich presence RPC. Code {}: {}'.format(
# codeno, codemsg
# ))
# def errorCallback(errno, errmsg):
# print('An error occurred! Error {}: {}'.format(
# errno, errmsg
# ))
# # Note: 'event_name': callback
# callbacks = {
# 'ready': readyCallback,
# 'disconnected': disconnectedCallback,
# 'error': errorCallback,
# }
# # if __name__ != "__main__":
# discord_rpc.initialize('800049969960058882', callbacks=callbacks, log=False)
# none = input('init')
# i = 0
# while i < 10:
# discord_rpc.update_presence(
# **{
# 'state': f'Загрузка...',
# 'details': 'Загрузка...',
# #'start_timestamp': start,
# 'large_image_key': '1024_cover',
# 'small_image_key': 'status_waiting',
# 'large_image_text': f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom',
# 'small_image_text': 'Ожидание',
# }
# )
# discord_rpc.update_connection()
# time.sleep(3)
# discord_rpc.run_callbacks()
# i += 1
# i = 0
# start = time.time()
# while i < 10:
# i += 1
#large_image='1024_cover', small_image='status_waiting', large_text=f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', small_text='Ожидание', state=f'Ждём начала «{lesson}»', details='Урок не начался', start=start
# discord_rpc.update_presence(
# **{
# 'state': f'Ждём начала «lesson»',
# 'details': 'Урок не начался',
# 'start_timestamp': start,
# 'large_image_key': '1024_cover',
# 'small_image_key': 'status_waiting',
# 'large_image_text': f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom',
# 'small_image_text': 'Ожидание',
# }
# )
# discord_rpc.update_connection()
# time.sleep(1)
# discord_rpc.run_callbacks()
# discord_rpc.shutdown()
# def disconnect():
# if getConfig("use_rpc"):
# discord_rpc.shutdown()
# def inMenu():
# if getConfig("use_rpc"):
# discord_rpc.update_presence(
# **{
# 'state': f'Ждём начала «lesson»',
# 'details': 'Урок не начался',
# #'start_timestamp': start,
# 'large_image_key': '1024_cover',
# 'small_image_key': 'status_waiting',
# 'large_image_text': f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom',
# 'small_image_text': 'Ожидание',
# }
# )
# discord_rpc.update_connection()
# def waitLesson(lesson, start):
# if getConfig("use_rpc"):
# discord_rpc.update_presence(
# **{
# 'state': f'Ждём начала «lesson»',
# 'details': 'Урок не начался',
# 'start_timestamp': start,
# 'large_image_key': '1024_cover',
# 'small_image_key': 'status_waiting',
# 'large_image_text': f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom',
# 'small_image_text': 'Ожидание',
# }
# )

579
settings.py Normal file
View File

@ -0,0 +1,579 @@
import rpc
import pathlib
import shutil
from functions import *
#from daemon import
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')
sysname = getOS()
if sysname == "windows":
from swinlnk.swinlnk import SWinLnk
swl = SWinLnk()
def settings():
appendLog('Settings page 1 opened')
global sysname
try:
while True:
setTitle("AutoZoom (Настройки)", sysname)
clear()
if getConfig("debug"):
debug_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("debug"):
debug_val = f'{BRED}Выкл.{RESET}'
else:
debug_val = f'{BRED}ERROR{RESET}'
if getConfig("run_fullscreen"):
fullscreen_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("run_fullscreen"):
fullscreen_val = f'{BRED}Выкл.{RESET}'
else:
fullscreen_val = f'{BRED}ERROR{RESET}'
if getConfig("sounds"):
sounds_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("sounds"):
sounds_val = f'{BRED}Выкл.{RESET}'
else:
sounds_val = f'{BRED}ERROR{RESET}'
if getConfig("obs_exe") and getConfig("obs_core") not in [None, 'Disabled']:
obs_val = f'{BGREEN}Вкл.{RESET}'
else:
obs_val = f'{BRED}Выкл.{RESET}'
if getConfig("use_colors"):
color_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("use_colors"):
color_val = f'{BRED}Выкл.{RESET}'
else:
color_val = f'{BRED}ERROR{RESET}'
if getConfig("shutdown_enabled"):
shutdown_en_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("shutdown_enabled"):
shutdown_en_val = f'{BRED}Выкл.{RESET}'
else:
shutdown_en_val = f'{BRED}ERROR{RESET}'
shutdown_time_val = getConfig("shutdown_timeout")
start_val = getConfig("start")
stop_val = getConfig("stop")
print(f'{RESET}{BBLACK}»{RESET} Настройки (1 стр.)\n')
print(f' {BRED}1.{RESET} Режим отладки ({debug_val})')
print(f' {BBLACK}Не рекомендуем включать его без необходимости\n')
print(f' {BRED}2.{RESET} Цветной вывод ({color_val})')
print(f' {BBLACK}Отображение цветных текстов в меню и выводе (нужен перезапуск)\n')
print(f' {BRED}3.{RESET} Полный экран ({fullscreen_val})')
print(f' {BBLACK}{winOnly(BRED, BBLACK, sysname, end=" ")}Эмулировать вызов полного экрана при запуске (окно должно быть в фокусе)\n')
print(f' {BRED}4.{RESET} Звуковые сигналы ({sounds_val})')
print(f' {BBLACK}Воспроизводить звуки при начале/конце конференций и записи видео\n')
print(f' {BRED}5.{RESET} Запись через OBS ({obs_val})')
print(f' {BBLACK}{winOnly(BRED, BBLACK, sysname, end=" ")}Возможность записи конференций через OBS\n')
print(f' {BRED}6.{RESET} Автовыключение ({shutdown_en_val})')
print(f' {BBLACK}Когда конференции закончатся компьютер выключится\n')
print(f' {BRED}7.{RESET} Следующая страница')
print(f' {BBLACK}Перейти на вторую страницу настроек\n')
print(f' {BRED}8.{RESET} В главное меню')
print(f' {BBLACK}Вернуться в основное меню{RESET}\n')
print(f' {BBLACK}Для переключения параметров Вкл/Выкл просто введите номер{RESET}') #\n Если окно приложения слишком мелкое - увеличьте его или листайте это меню{RESET}')
settings_choose = input(f'\n > {BRED}')
if settings_choose == '1':
setConfig("debug", not getConfig("debug"))
appendLog(f'Changed option "debug" to {getConfig("debug")}')
clear()
continue
elif settings_choose == '2':
setConfig("use_colors", not getConfig("use_colors"))
appendLog(f'Changed option "use_colors" to {getConfig("use_colors")}')
clear()
continue
elif settings_choose == '3':
if sysname == 'windows':
setConfig("run_fullscreen", not getConfig("run_fullscreen"))
appendLog(f'Changed option "run_fullscreen" to {getConfig("run_fullscreen")}')
clear()
continue
elif settings_choose == '4':
setConfig("sounds", not getConfig("sounds"))
appendLog(f'Changed option "sounds" to {getConfig("sounds")}')
clear()
continue
elif settings_choose == '5':
if sysname == 'windows':
if getConfig("obs_core") and getConfig("obs_exe") not in [None, 'Disabled']:
setConfig("obs_core", "Disabled")
setConfig("obs_exe", "Disabled")
else:
clear()
obs_choice = input(f'{RESET}Хотите использовать запись через OBS? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET}): ')
if obs_choice.lower() in yes_list:
while True:
try:
filename = easygui.fileopenbox('Выберите путь до obs32.exe или obs64.exe')
if filename.find("obs64.exe") != -1:
setConfig("obs_exe", filename)
setConfig("obs_core", filename[:-9])
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-9]}{RESET}')
time.sleep(3)
break
elif filename.find("obs32.exe") != -1:
setConfig("obs_exe", filename)
setConfig("obs_core", filename[:-9])
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-9]}{RESET}')
time.sleep(3)
break
elif filename.find("obs.exe") != -1:
setConfig("obs_exe", filename)
setConfig("obs_core", filename[:-7])
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-7]}{RESET}')
time.sleep(3)
break
else:
easygui.msgbox("Неверный путь")
break
except Exception as exp:
appendLog(f'Could not select OBS path: {exp}')
none = input('Вы не выбрали верный путь для OBS.\n\n > ')
clear()
break
appendLog(f'Changed option "obs_exe" to {getConfig("obs_exe")}')
appendLog(f'Changed option "obs_core" to {getConfig("obs_core")}')
clear()
continue
elif settings_choose == '6':
setConfig("shutdown_enabled", not getConfig("shutdown_enabled"))
appendLog(f'Changed option "shutdown_enabled" to {getConfig("shutdown_enabled")}')
clear()
continue
elif settings_choose == '7':
clear()
settings2()
elif settings_choose == '8':
rpc.inMenu()
clear()
setTitle("AutoZoom (Главная)", sysname)
return
except KeyboardInterrupt:
rpc.inMenu()
clear()
return
def settings2():
appendLog('Settings page 2 opened')
global sysname
try:
while True:
setTitle("AutoZoom (Настройки)", sysname)
clear()
if getConfig("use_colors"):
color_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("use_colors"):
color_val = f'{BRED}Выкл.{RESET}'
else:
color_val = f'{BRED}ERROR{RESET}'
if os.path.exists(files_folder+'telegram.conf'):
tg_file = open(files_folder+'telegram.conf', 'r', encoding="utf-8")
tg_text = tg_file.read()
if tg_text != 'Not Configured':
tg_var = f'{BGREEN}Настроен{RESET}'
else:
tg_var = f'{BRED}Не настроен{RESET}'
else:
tg_var = f'{BRED}Не настроен{RESET}'
if getConfig("telegram_enabled"):
telegram_en_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("telegram_enabled"):
telegram_en_val = f'{BRED}Выкл.{RESET}'
else:
telegram_en_val = f'{BRED}ERROR{RESET}'
if getConfig("update_check"):
update_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("update_check"):
update_val = f'{BRED}Выкл.{RESET}'
else:
update_val = f'{BRED}ERROR{RESET}'
shutdown_time_val = getConfig("shutdown_timeout")
start_val = getConfig("start")
stop_val = getConfig("stop")
print(f'{RESET}{BBLACK}»{RESET} Настройки (2 стр.)\n')
print(f' {BRED}1.{RESET} Таймаут выключения ({YELLOW}{shutdown_time_val} мин.{RESET})')
print(f' {BBLACK}Время в минутах после которого ПК будет выключен\n')
print(f' {BRED}2.{RESET} Начать запись ({YELLOW}{start_val}{RESET})')
print(f' {BBLACK}{winOnly(BRED, BBLACK, sysname, end=" ")}Комбинация клавиш для начала записи через OBS (см. документацию)\n')
print(f' {BRED}3.{RESET} Остановить запись ({YELLOW}{stop_val}{RESET})')
print(f' {BBLACK}{winOnly(BRED, BBLACK, sysname, end=" ")}Комбинация клавиш для остановки записи через OBS (см. документацию)\n')
print(f' {BRED}4.{RESET} Отправлять уведомления ({telegram_en_val})')
print(f' {BBLACK}Ваш бот отправит сообщениия о начале/конце конференции и выключении ПК\n')
print(f' {BRED}5.{RESET} Настроить Telegram бота ({tg_var})')
print(f' {BBLACK}Настроить на вашем ПК бота для ЛС (см. документацию)\n')
print(f' {BRED}6.{RESET} Проверка обновлений ({update_val})')
print(f' {BBLACK}Ускоряет загрузку меню, но не рекомендуем выключать без необходимости\n')
print(f' {BRED}7.{RESET} Следующая страница')
print(f' {BBLACK}Перейти на третью страницу настроек\n')
print(f' {BRED}8.{RESET} Назад')
print(f' {BBLACK}Вернуться на предыдущую страницу{RESET}\n')
print(f' {BBLACK}Для переключения параметров Вкл/Выкл просто введите номер{RESET}') #\n Если окно приложения слишком мелкое - увеличьте его или листайте это меню{RESET}')
settings_choose = input(f'\n > {BRED}')
if settings_choose == '1':
try:
clear()
shutdown_timeout_val = int(input(f'{RESET}Введите через сколько минут после конференции выключать ПК:\n\n > {BRED}'))
setConfig("shutdown_timeout", shutdown_timeout_val)
appendLog(f'Changed option "shutdown_timeout" to {getConfig("shutdown_timeout")}')
continue
except:
clear()
print(f'{RESET}Нужно использовать целое число.')
time.sleep(2)
continue
continue
elif settings_choose == '2':
if sysname == 'windows':
try:
clear()
start_value = input(f'{RESET}Введите комбинацию клавиш для начала записи OBS:\nЭта комбинация должна быть идентична оной в самом OBS!\n\n > {YELLOW}')
setConfig("start", start_value)
appendLog(f'Changed option "start" to {getConfig("start")}')
continue
except:
clear()
print(f'{RESET}Нужно использовать комбинацию клавиш в виде текста.')
time.sleep(2)
continue
clear()
continue
elif settings_choose == '3':
if sysname == 'windows':
try:
clear()
stop_value = input(f'{RESET}Введите комбинацию клавиш для остановки записи OBS:\nЭта комбинация должна быть идентична оной в самом OBS!\n\n > {YELLOW}')
setConfig("stop", stop_value)
appendLog(f'Changed option "stop" to {getConfig("stop")}')
continue
except:
clear()
print(f'{RESET}Нужно использовать комбинацию клавиш в виде текста.')
time.sleep(2)
continue
clear()
continue
elif settings_choose == '4':
setConfig("telegram_enabled", not getConfig("telegram_enabled"))
appendLog(f'Changed option "telegram_enabled" to {getConfig("telegram_enabled")}')
clear()
continue
elif settings_choose == '5':
clear()
print(f'{RESET}Пожалуйста, прочтите инструкцию по установке Telegram бота в {BRED}README.txt{RESET}')
print(f'или в документации/инструкции что в разделе {CYAN}Помощь{RESET} главного меню')
print(f'чтобы хорошо понимать что сейчас от вас нужно.')
none = input('\n > ')
while True:
clear()
try:
telegram_send.configure(files_folder+'telegram.conf', channel=False, group=False, fm_integration=False)
break
except:
clear()
continue
telegram_send.send(messages=[f"🎊 Конфигурация правильна, всё работает!"], parse_mode="markdown", conf=f"{files_folder}telegram.conf")
appendLog('Telegram Send successfully configured')
clear()
continue
elif settings_choose == '6':
setConfig("update_check", not getConfig("update_check"))
appendLog(f'Changed option "update_check" to {getConfig("update_check")}')
clear()
continue
elif settings_choose == '7':
appendLog('Going to settings page 3')
clear()
settings3()
elif settings_choose == '8':
appendLog('Returned to settings page 1')
clear()
return
except KeyboardInterrupt:
rpc.inMenu()
clear()
return
def settings3():
appendLog('Settings page 3 opened')
try:
while True:
setTitle("AutoZoom (Настройки)", sysname)
clear()
if getConfig("write_logs"):
logs_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("write_logs"):
logs_val = f'{BRED}Выкл.{RESET}'
else:
logs_val = f'{BRED}ERROR{RESET}'
if getConfig("remove_old"):
remove_val = f'{BGREEN}Вкл.{RESET}'
elif not getConfig("remove_old"):
remove_val = f'{BRED}Выкл.{RESET}'
else:
remove_val = f'{BRED}ERROR{RESET}'
shutdown_time_val = getConfig("shutdown_timeout")
start_val = getConfig("start")
stop_val = getConfig("stop")
print(f'{RESET}{BBLACK}»{RESET} Настройки (3 стр.)\n')
print(f' {BRED}1.{RESET} Запись действий в лог ({logs_val})')
print(f' {BBLACK}Запись каждого действия в файл для отладки (не выключайте без причин)\n')
print(f' {BRED}2.{RESET} Размер лога действий ({YELLOW}{str(getConfig("log_size"))} Кб{RESET})')
print(f' {BBLACK}Размер файла лога превышая который он будет упакован в архив\n')
print(f' {BRED}3.{RESET} Задержка до записи OBS ({YELLOW}{str(getConfig("obs_delay"))} сек.{RESET})')
print(f' {BBLACK}Через сколько секунд будет отправлен сигнал записи экрана\n')
print(f' {BRED}4.{RESET} Добавить в автозапуск')
print(f' {BBLACK}{winOnly(BRED, BBLACK, sysname, end=" ")}Автоматически запускать демона при входе в систему\n')
print(f' {BRED}5.{RESET} Удалять старые конференции ({remove_val})')
print(f' {BBLACK}Автоматически удалять одноразовые конференции которые были до дня запуска\n')
print(f' {BRED}6.{RESET} Кастомизация звуков и RPC')
print(f' {BBLACK}Изменить звуковые файлы и APPLICATION ID используемого Discord RPC\n')
print(f' {BRED}7.{RESET} Сбросить все настройки')
print(f' {BBLACK}Восстановить настройки по умолчанию\n')
print(f' {BRED}8.{RESET} Назад')
print(f' {BBLACK}Вернуться на предыдущую страницу{RESET}\n')
print(f' {BBLACK}Для переключения параметров Вкл/Выкл просто введите номер{RESET}') #\n Если окно приложения слишком мелкое - увеличьте его или листайте это меню{RESET}')
settings_choose = input(f'\n > {BRED}')
if settings_choose == '1':
setConfig("write_logs", not getConfig("write_logs"))
appendLog(f'Changed option "write_logs" to {getConfig("write_logs")}')
if settings_choose == '2':
try:
clear()
log_size_value = int(input(f'{RESET}Введите после скольки килобайт архивировать лог:\n\n > {BRED}'))
setConfig("log_size", log_size_value)
continue
except:
clear()
print(f'{RESET}Нужно использовать целое число.')
time.sleep(2)
continue
appendLog(f'Changed option "log_size" to {getConfig["log_size"]}')
continue
if settings_choose == '3':
try:
clear()
log_size_value = int(input(f'{RESET}Введите через сколько секунд отправлять сигнал записи:\n\n > {BRED}'))
setConfig("obs_delay", log_size_value)
continue
except:
clear()
print(f'{RESET}Нужно использовать целое число.')
time.sleep(2)
continue
appendLog(f'Changed option "obs_delay" to {getConfig["obs_delay"]}')
continue
if settings_choose == '4':
if sysname == "windows":
global swl
try:
clear()
shutil.copyfile('daemon.bat', 'startdaemon.bat')
with open('startdaemon.bat', 'r', encoding='utf-8') as f :
filedata = f.read()
filedata = filedata.replace('python daemon.py', f'python {path}\\daemon.py')
with open('startdaemon.bat', 'w', encoding="utf-8") as f:
f.write(filedata)
f.close()
swl.create_lnk(f'{path}\\startdaemon.bat', f'{pathlib.Path.home()}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\AutoZoomDaemon.lnk')
appendLog('Autorun script added')
none = input(f'{RESET}Демон AutoZoom был добавлен в автозапуск.\nПуть: {BRED}{pathlib.Path.home()}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\AutoZoomDaemon.lnk{RESET}\n\n > ')
continue
except Exception as exp:
clear()
none = input(f'Не удалось добавить в автозапуск:\n{BRED}{exp}{RESET}\n\n > ')
appendLog(f'Could not add autorun: {exp}')
continue
continue
else:
continue
elif settings_choose == '5':
setConfig("remove_old", not getConfig("remove_old"))
appendLog(f'Changed option "remove_old" to {getConfig("remove_old")}')
elif settings_choose == '6':
appendLog('Going to customize page')
clear()
customize()
elif settings_choose == '7':
appendLog('Resetting configuration')
while True:
clear()
reset_decision = input(f'{RESET}Вы уверены что хотите сбросить настройки? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n{BRED}Внимание!{RESET} Это действие нельзя обратить!\nВаш список конференций затронут НЕ будет.\n\n > ')
if reset_decision.lower() in yes_list:
from functions import default_config
saveJson(files_folder+'config.json', default_config)
appendLog('Configuration dropped to default')
clear()
none = input(f'{RESET}Все настройки были сброшены до стандартных.\n\n > ')
clear()
break
elif reset_decision.lower() in no_list:
appendLog('Configuration reset aborted')
clear()
break
else:
clear()
continue
continue
clear()
continue
elif settings_choose == '8':
appendLog('Returned to settings page 2')
clear()
return
except KeyboardInterrupt:
rpc.inMenu()
clear()
return

BIN
sounds/debug.wav Normal file

Binary file not shown.

BIN
sounds/warning.wav Normal file

Binary file not shown.