5 Commits
v1.5 ... v1.8

Author SHA1 Message Date
5206b3e2fa Обновление 1.8 2021-04-07 23:57:02 +03:00
7598e594da Фикс номера версии 2021-04-06 01:53:48 +03:00
747e666cf1 Обновление 1.7
Фиксы багов связанных с RPC и файлами.
2021-04-06 01:32:55 +03:00
c8e3f64762 Фикс версии 2021-01-22 15:03:17 +02:00
84d47b131c Обновление 1.6
• Исправлены баги с подгрузкой конфига;
• Добавлена возможность выбора пути через Настройки;
• В демоне больше не нужно выбирать OBS если ранее было выбрано "Нет".
2021-01-22 14:53:33 +02:00
8 changed files with 333 additions and 118 deletions

347
daemon.py
View File

@@ -10,7 +10,6 @@ import pathlib
import json import json
import getopt import getopt
import sys import sys
import winsound
from random import randint from random import randint
from pathlib import Path from pathlib import Path
from datetime import datetime, date, timedelta from datetime import datetime, date, timedelta
@@ -30,6 +29,11 @@ if os.name == 'nt':
else: else:
clear = lambda: os.system('clear') clear = lambda: os.system('clear')
if os.name == 'nt':
import winsound
else:
import playsound
clear() clear()
os.system("title Загрузка daemon...") os.system("title Загрузка daemon...")
@@ -90,19 +94,28 @@ def getLessons():
if not os.path.exists(files_folder+'lessons.json'): if not os.path.exists(files_folder+'lessons.json'):
with open(files_folder+'lessons.json', 'w', encoding="utf-8") as f: with open(files_folder+'lessons.json', 'w', encoding="utf-8") as f:
f.write("[]") f.write("[]")
f.close()
lessons_list = [] lessons_list = []
else: else:
with open(files_folder+'lessons.json', encoding="utf-8") as json_file: with open(files_folder+'lessons.json', encoding="utf-8") as json_file:
lessons_list = json.load(json_file) lessons_list = json.load(json_file)
json_file.close()
return lessons_list return lessons_list
def getState(): def getState():
output = os.popen('wmic process get description, processid').read() if os.system == 'nt':
if "CptHost.exe" in output: output = os.popen('wmic process get description, processid').read()
return True if "CptHost.exe" in output:
else: return True
return False else:
return False
### KODIL TUT
#else:
#check_result = subprocess.check_output('ps -efww', shell=True)
#if
def listLessons(from_where='remove'): def listLessons(from_where='remove'):
try: try:
@@ -241,7 +254,15 @@ def addLesson():
continue continue
clear() clear()
lesslink = input(f'{RESET}Введите ссылку на конференцию:\n\n > {BRED}') lesslink = input(f'{RESET}Введите ссылку на конференцию:\n{BBLACK}Формат: {BRED}https://us01web.zoom.us/j/ИДЕНТИФИКАТОР?pwd=ПАРОЛЬ{RESET}\n{BBLACK}Либо введите {YELLOW}1 {BBLACK}для добавления по номеру и паролю{RESET}\n\n > {BRED}')
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}) local_lessons.update({"link": lesslink})
while True: while True:
@@ -405,10 +426,18 @@ def editLesson():
continue continue
clear() clear()
lesslink = input(f'{RESET}Введите ссылку на конференцию\n\nОригинальная ссылка: {BRED}{lessons_got[edi]["link"]}{RESET}\n\n > {BRED}') lesslink = input(f'{RESET}Введите ссылку на конференцию:\n{BBLACK}Формат: {BRED}https://us01web.zoom.us/j/ИДЕНТИФИКАТОР?pwd=ПАРОЛЬ{RESET}\n{BBLACK}Либо введите {YELLOW}1 {BBLACK}для добавления по номеру и паролю{RESET}\n\n > {BRED}')
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 == '': if lesslink == '':
lesslink = lessons_got[edi]["link"] lesslink = lessons_got[edi]["link"]
local_lessons.update({"link": lesslink}) local_lessons.update({"link": lesslink})
while True: while True:
@@ -528,6 +557,7 @@ def removeAllLessons():
if removeall.lower() in ['y', 'yes', 'д', 'да']: if removeall.lower() in ['y', 'yes', 'д', 'да']:
with open(files_folder+'lessons.json', 'w', encoding="utf-8") as f: with open(files_folder+'lessons.json', 'w', encoding="utf-8") as f:
f.write("[]") f.write("[]")
f.close()
clear() clear()
none = input('Все уроки были удалены.\n\n > ') none = input('Все уроки были удалены.\n\n > ')
clear() clear()
@@ -592,11 +622,18 @@ def tgsend(enabled, message):
tg_file = open(files_folder+'telegram.conf', 'r', encoding="utf-8") tg_file = open(files_folder+'telegram.conf', 'r', encoding="utf-8")
tg_text = tg_file.read() tg_text = tg_file.read()
if tg_text != 'Not Configured': if tg_text != 'Not Configured':
telegram_send.send(messages=[f"{message}"], parse_mode="markdown", conf=files_folder+"telegram.conf") try:
telegram_send.send(messages=[f"{message}"], parse_mode="markdown", conf=files_folder+"telegram.conf")
except as Exception:
print(f'{nowtime()} Не удалось отправить Telegram сообщение "{message}" (Ошибка: {Exception})')
def playSound(soundname): def playSound(soundname):
if getConfig("sounds"): if getConfig("sounds"):
winsound.PlaySound(sounds_folder+soundname+".wav", winsound.SND_FILENAME)
if os.name == 'nt':
winsound.PlaySound(sounds_folder+soundname+".wav", winsound.SND_FILENAME)
else:
playsound.playsound(sounds_folder+soundname+".wav")
def settings(): def settings():
try: try:
@@ -626,6 +663,11 @@ def settings():
else: else:
sounds_val = f'{BRED}ERROR{RESET}' 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_rpc"): # if getConfig("use_rpc"):
# rpc_val = f'{BGREEN}Вкл.{RESET}' # rpc_val = f'{BGREEN}Вкл.{RESET}'
@@ -669,7 +711,7 @@ def settings():
start_val = getConfig("start") start_val = getConfig("start")
stop_val = getConfig("stop") stop_val = getConfig("stop")
print(f'{BBLACK}»{RESET} Настройки\n') print(f'{RESET}{BBLACK}»{RESET} Настройки\n')
print(f' {BRED}1.{RESET} Режим отладки ({debug_val})') print(f' {BRED}1.{RESET} Режим отладки ({debug_val})')
print(f' {BBLACK}Не рекомендуем включать его без необходимости\n') print(f' {BBLACK}Не рекомендуем включать его без необходимости\n')
@@ -682,33 +724,37 @@ def settings():
print(f' {BRED}4.{RESET} Звуковые сигналы ({sounds_val})') print(f' {BRED}4.{RESET} Звуковые сигналы ({sounds_val})')
print(f' {BBLACK}Воспроизводить звуки при начале/конце уроков и записи видео\n') print(f' {BBLACK}Воспроизводить звуки при начале/конце уроков и записи видео\n')
print(f' {BRED}5.{RESET} Запись через OBS ({obs_val})')
print(f' {BBLACK}Возможность записи уроков через OBS\n')
# Пока слишком много ошибок # Пока слишком много ошибок
# print(f' {BRED}3.{RESET} Discord RPC ({rpc_val})') # print(f' {BRED}3.{RESET} Discord RPC ({rpc_val})')
# print(f' {BBLACK}Показывать какой идёт урок и какое меню открыто (нужен перезапуск)\n') # print(f' {BBLACK}Показывать какой идёт урок и какое меню открыто (нужен перезапуск)\n')
print(f' {BRED}5.{RESET} Автовыключение ({shutdown_en_val})') print(f' {BRED}6.{RESET} Автовыключение ({shutdown_en_val})')
print(f' {BBLACK}Когда уроки закончатся компьютер выключится\n') print(f' {BBLACK}Когда уроки закончатся компьютер выключится\n')
print(f' {BRED}6.{RESET} Таймаут выключения ({YELLOW}{shutdown_time_val} мин.{RESET})') print(f' {BRED}7.{RESET} Таймаут выключения ({YELLOW}{shutdown_time_val} мин.{RESET})')
print(f' {BBLACK}Время в минутах после которого ПК будет выключен\n') print(f' {BBLACK}Время в минутах после которого ПК будет выключен\n')
print(f' {BRED}7.{RESET} Начать запись ({YELLOW}{start_val}{RESET})') print(f' {BRED}8.{RESET} Начать запись ({YELLOW}{start_val}{RESET})')
print(f' {BBLACK}Комбинация клавиш для начала записи через OBS (см. документацию)\n') print(f' {BBLACK}Комбинация клавиш для начала записи через OBS (см. документацию)\n')
print(f' {BRED}8.{RESET} Остановить запись ({YELLOW}{stop_val}{RESET})') print(f' {BRED}9.{RESET} Остановить запись ({YELLOW}{stop_val}{RESET})')
print(f' {BBLACK}Комбинация клавиш для остановки записи через OBS (см. документацию)\n') print(f' {BBLACK}Комбинация клавиш для остановки записи через OBS (см. документацию)\n')
print(f' {BRED}9.{RESET} Отправлять уведомления ({telegram_en_val})') print(f' {BRED}10.{RESET} Отправлять уведомления ({telegram_en_val})')
print(f' {BBLACK}Ваш бот отправит сообщениия о начале/конце урока и выключении ПК\n') print(f' {BBLACK}Ваш бот отправит сообщениия о начале/конце урока и выключении ПК\n')
print(f' {BRED}10.{RESET} Настроить Telegram бота ({tg_var})') print(f' {BRED}11.{RESET} Настроить Telegram бота ({tg_var})')
print(f' {BBLACK}Настроить на вашем ПК бота для ЛС (см. документацию)\n') print(f' {BBLACK}Настроить на вашем ПК бота для ЛС (см. документацию)\n')
print(f' {BRED}11.{RESET} Сбросить все настройки') print(f' {BRED}12.{RESET} Сбросить все настройки')
print(f' {BBLACK}Восстановить настройки по умолчанию\n') print(f' {BBLACK}Восстановить настройки по умолчанию\n')
print(f' {BRED}12.{RESET} В главное меню') print(f' {BRED}13.{RESET} В главное меню')
print(f' {BBLACK}Выйти без внесения изменений{RESET}\n') print(f' {BBLACK}Выйти без внесения изменений{RESET}\n')
print(f' {BBLACK}Для переключения параметров Вкл/Выкл просто введите номер\n Если окно приложения слишком мелкое - увеличьте его или листайте это меню{RESET}') print(f' {BBLACK}Для переключения параметров Вкл/Выкл просто введите номер\n Если окно приложения слишком мелкое - увеличьте его или листайте это меню{RESET}')
@@ -717,6 +763,7 @@ def settings():
if settings_choose == '1': if settings_choose == '1':
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()
config_list["debug"] = not getConfig("debug") config_list["debug"] = not getConfig("debug")
saveJson(files_folder+'config.json', config_list) saveJson(files_folder+'config.json', config_list)
@@ -726,6 +773,7 @@ def settings():
elif settings_choose == '2': elif settings_choose == '2':
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()
config_list["use_colors"] = not getConfig("use_colors") config_list["use_colors"] = not getConfig("use_colors")
saveJson(files_folder+'config.json', config_list) saveJson(files_folder+'config.json', config_list)
@@ -735,6 +783,7 @@ def settings():
elif settings_choose == '3': elif settings_choose == '3':
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()
config_list["run_fullscreen"] = not getConfig("run_fullscreen") config_list["run_fullscreen"] = not getConfig("run_fullscreen")
saveJson(files_folder+'config.json', config_list) saveJson(files_folder+'config.json', config_list)
@@ -745,12 +794,58 @@ def settings():
elif settings_choose == '4': elif settings_choose == '4':
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()
config_list["sounds"] = not getConfig("sounds") config_list["sounds"] = not getConfig("sounds")
saveJson(files_folder+'config.json', config_list) saveJson(files_folder+'config.json', config_list)
clear() clear()
continue continue
elif settings_choose == '5':
with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file)
json_file.close()
if getConfig("obs_core") and getConfig("obs_exe") not in [None, 'Disabled']:
config_list["obs_core"] = 'Disabled'
config_list["obs_exe"] = 'Disabled'
else:
clear()
obs_choice = input(f'{RESET}Хотите использовать запись через OBS? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET}): ')
if obs_choice.lower() in ['y', 'yes', 'д', 'да']:
while True:
try:
filename = easygui.fileopenbox('Выберите путь до obs32.exe или obs64.exe')
if filename.find("obs64.exe") != -1:
config_list["obs_exe"] = filename
config_list["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:
config_list["obs_exe"] = filename
config_list["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:
f.write(filename)
config_list["obs_exe"] = filename
config_list["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:
none = input('Вы не выбрали верный путь для OBS.\n\n > ')
clear()
break
saveJson(files_folder+'config.json', config_list)
clear()
continue
# Пока слишком много ошибок # Пока слишком много ошибок
# elif settings_choose == '3': # elif settings_choose == '3':
@@ -763,18 +858,20 @@ def settings():
# clear() # clear()
# continue # continue
elif settings_choose == '5': elif settings_choose == '6':
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()
config_list["shutdown_enabled"] = not getConfig("shutdown_enabled") config_list["shutdown_enabled"] = not getConfig("shutdown_enabled")
saveJson(files_folder+'config.json', config_list) saveJson(files_folder+'config.json', config_list)
clear() clear()
continue continue
elif settings_choose == '6': elif settings_choose == '7':
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()
try: try:
clear() clear()
@@ -788,9 +885,10 @@ def settings():
continue continue
continue continue
elif settings_choose == '7': elif settings_choose == '8':
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()
try: try:
clear() clear()
@@ -804,9 +902,10 @@ def settings():
continue continue
continue continue
elif settings_choose == '8': elif settings_choose == '9':
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()
try: try:
clear() clear()
@@ -820,16 +919,17 @@ def settings():
continue continue
continue continue
elif settings_choose == '9': elif settings_choose == '10':
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()
config_list["telegram_enabled"] = not getConfig("telegram_enabled") config_list["telegram_enabled"] = not getConfig("telegram_enabled")
saveJson(files_folder+'config.json', config_list) saveJson(files_folder+'config.json', config_list)
clear() clear()
continue continue
elif settings_choose == '10': elif settings_choose == '11':
clear() clear()
print(f'{RESET}Пожалуйста, прочтите инструкцию по установке Telegram бота в {BRED}README.txt{RESET}') print(f'{RESET}Пожалуйста, прочтите инструкцию по установке Telegram бота в {BRED}README.txt{RESET}')
print(f'или в документации/инструкции что в разделе {CYAN}Помощь{RESET} главного меню') print(f'или в документации/инструкции что в разделе {CYAN}Помощь{RESET} главного меню')
@@ -848,7 +948,7 @@ def settings():
clear() clear()
continue continue
elif settings_choose == '11': elif settings_choose == '12':
while True: while True:
clear() clear()
reset_decision = input(f'{RESET}Вы уверены что хотите сбросить настройки? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n{BRED}Внимание!{RESET} Это действие нельзя обратить!\nВаш список конференций затронут НЕ будет.\n\n > ') reset_decision = input(f'{RESET}Вы уверены что хотите сбросить настройки? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET})\n\n{BRED}Внимание!{RESET} Это действие нельзя обратить!\nВаш список конференций затронут НЕ будет.\n\n > ')
@@ -861,13 +961,13 @@ def settings():
temp_config_list["stop"] = "shift+f8" temp_config_list["stop"] = "shift+f8"
temp_config_list["telegram_enabled"] = False temp_config_list["telegram_enabled"] = False
temp_config_list["use_colors"] = True 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)
if os.path.exists(files_folder+"obscorepath.txt"):
os.remove(files_folder+"obscorepath.txt")
if os.path.exists(files_folder+"obspath.txt"):
os.remove(files_folder+"obspath.txt")
if os.path.exists(files_folder+"telegram.conf"):
os.remove(files_folder+"telegram.conf")
clear() clear()
none = input(f'{RESET}Все настройки были сброшены до стандартных.\n\n > ') none = input(f'{RESET}Все настройки были сброшены до стандартных.\n\n > ')
clear() clear()
@@ -882,7 +982,7 @@ def settings():
clear() clear()
continue continue
elif settings_choose == '12': elif settings_choose == '13':
rpc.inMenu() rpc.inMenu()
clear() clear()
os.system("title AutoZoom (Главная)") os.system("title AutoZoom (Главная)")
@@ -893,6 +993,21 @@ def settings():
return return
def main(source='deamon'): def main(source='deamon'):
##########################################
# Возможность профилей сделана для себя
# и не планируется как фича, однако
# вы можете присобачить сюда что хотите.
try:
from profile import profilename
except:
profilename = ''
pass
##########################################
try: try:
import time import time
from main import mainMenu from main import mainMenu
@@ -901,58 +1016,69 @@ def main(source='deamon'):
os.system("title AutoZoom (Демон)") os.system("title AutoZoom (Демон)")
import webbrowser import webbrowser
try:
with open(files_folder+'obspath.txt', 'r', encoding="utf-8") as f:
current_obs_path = f.read()
except:
current_obs_path = ''
if not os.path.exists(files_folder+'obspath.txt') or current_obs_path == '': if (getConfig("obs_core") or getConfig("obs_exe")) == None:
clear() clear()
obs_choice = input(f'Хотите использовать запись через OBS? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET}): ') while True:
if obs_choice.lower() == 'д' or obs_choice.lower() == 'да' or obs_choice.lower() == 'y' or obs_choice.lower() == 'yes': obs_choice = input(f'{RESET}Хотите использовать запись через OBS? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET}): ')
with open(files_folder+'obspath.txt', 'w', encoding="utf-8") as f: if obs_choice.lower() in ['y', 'yes', 'д', 'да']:
while True: with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
try: config_list = json.load(json_file)
filename = easygui.fileopenbox('Выберите путь до obs32.exe или obs64.exe') json_file.close()
if filename.find("obs64.exe") != -1: while True:
f.write(filename) try:
with open(files_folder+'obscorepath.txt', 'w', encoding="utf-8") as f: filename = easygui.fileopenbox('Выберите путь до obs32.exe или obs64.exe')
f.write(filename[:-9]) if filename.find("obs64.exe") != -1:
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-9]}{RESET}') config_list["obs_exe"] = filename
time.sleep(3) config_list["obs_core"] = filename[:-9]
saveJson(files_folder+'config.json', config_list)
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-9]}{RESET}')
time.sleep(3)
break
elif filename.find("obs32.exe") != -1:
config_list["obs_exe"] = filename
config_list["obs_core"] = filename[:-9]
saveJson(files_folder+'config.json', config_list)
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-9]}{RESET}')
time.sleep(3)
break
elif filename.find("obs.exe") != -1:
config_list["obs_exe"] = filename
config_list["obs_core"] = filename[:-7]
saveJson(files_folder+'config.json', config_list)
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-7]}{RESET}')
time.sleep(3)
break
else:
easygui.msgbox("Неверный путь")
continue
break break
elif filename.find("obs32.exe") != -1: except:
f.write(filename) none = input('Вы не выбрали верный путь для OBS.\n\n > ')
with open(files_folder+'obscorepath.txt', 'w', encoding="utf-8") as f: config_list["obs_exe"] = 'Disabled'
f.write(filename[:-9]) config_list["obs_core"] = 'Disabled'
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-9]}{RESET}') saveJson(files_folder+'config.json', config_list)
time.sleep(3) clear()
break break
elif filename.find("obs.exe") != -1: break
f.write(filename) elif obs_choice.lower() in ['n', 'no', 'н', 'нет']:
with open(files_folder+'obscorepath.txt', 'w', encoding="utf-8") as f: with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
f.write(filename[:-7]) config_list = json.load(json_file)
print(f'Сохранены пути для OBS:\nПриложение: {BRED}{filename}{RESET}\nКорневая папка: {BRED}{filename[:-7]}{RESET}') config_list["obs_exe"] = 'Disabled'
time.sleep(3) config_list["obs_core"] = 'Disabled'
break saveJson(files_folder+'config.json', config_list)
else: json_file.close()
easygui.msgbox("Неверный путь")
break clear()
except: break
none = input('Вы не выбрали верный путь для OBS.\n\n > ') else:
if os.path.exists(files_folder+"obscorepath.txt"): clear()
os.remove(files_folder+"obscorepath.txt") continue
if os.path.exists(files_folder+"obspath.txt"):
os.remove(files_folder+"obspath.txt")
clear()
break
if not os.path.exists(files_folder+'telegram.conf'): if not os.path.exists(files_folder+'telegram.conf'):
clear() clear()
tg_choice = input(f'Хотите использовать Telegram бота? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET}): ') tg_choice = input(f'{RESET}Хотите использовать Telegram бота? {RESET}({BGREEN}Да{RESET}/{BRED}Нет{RESET}): ')
if tg_choice.lower() == 'д' or tg_choice.lower() == 'да' or tg_choice.lower() == 'y' or tg_choice.lower() == 'yes': if tg_choice.lower() in ['y', 'yes', 'д', 'да']:
clear() clear()
print(f'Пожалуйста, прочтите инструкцию по установке Telegram бота в {BRED}README.txt{RESET}') print(f'Пожалуйста, прочтите инструкцию по установке Telegram бота в {BRED}README.txt{RESET}')
print(f'или в документации/инструкции что в разделе {CYAN}Помощь{RESET} главного меню') print(f'или в документации/инструкции что в разделе {CYAN}Помощь{RESET} главного меню')
@@ -970,9 +1096,10 @@ def main(source='deamon'):
continue continue
telegram_send.send(messages=[f"🎊 Конфигурация правильна, всё работает!"], parse_mode="markdown", conf=f"{files_folder}telegram.conf") telegram_send.send(messages=[f"🎊 Конфигурация правильна, всё работает!"], parse_mode="markdown", conf=f"{files_folder}telegram.conf")
clear() clear()
elif tg_choice.lower() == 'н' or tg_choice.lower() == 'нет' or tg_choice.lower() == 'n' or tg_choice.lower() == 'no': elif tg_choice.lower() in ['n', 'no', 'н', 'нет']:
with open(files_folder+'telegram.conf', 'w', encoding="utf-8") as f: with open(files_folder+'telegram.conf', 'w', encoding="utf-8") as f:
f.write('Not Configured') f.write('Not Configured')
f.close()
lessons_count = 0 lessons_count = 0
try: try:
@@ -1008,17 +1135,61 @@ def main(source='deamon'):
rpc.waitLesson(lesson_name, waiting_time_unix) rpc.waitLesson(lesson_name, waiting_time_unix)
waitStart(lesson_time, lambda: act(100)) waitStart(lesson_time, lambda: act(100))
webbrowser.open(lesson_url)
try:
if os.name == 'nt':
i = 0
while i < 10:
lesson_url = lesson_url.replace(f"https://us0{i}web.zoom.us/j/", "zoommtg://zoom.us/join?action=join&confno=")
i += 1
lesson_url = lesson_url.replace("&", "^&")
lesson_url = lesson_url.replace("?pwd", "^&pwd")
if getConfig("debug"):
print(lesson_url)
os.system(f'start {lesson_url}')
else:
i = 0
while i < 10:
lesson_url = lesson_url.replace(f"https://us0{i}web.zoom.us/j/", "zoommtg://zoom.us/join?action=join&confno=")
i += 1
lesson_url = lesson_url.replace("?pwd=", "&pwd=")
if getConfig("debug"):
print(lesson_url)
os.system(f'xdg-open "{lesson_url}"')
except:
try:
webbrowser.open(lesson_url)
except:
print(f'{nowtime()} Открыть урок {CYAN}{lesson_name}{RESET} не удалось ни напрямую, ни в браузере.')
easteregg_number = randint(1, 100000) easteregg_number = randint(1, 100000)
if easteregg_number == 69420: if easteregg_number == 69420:
webbrowser.open('https://www.pornhub.com/view_video.php?viewkey=ph5f3eb1e206aa8') webbrowser.open('https://www.pornhub.com/view_video.php?viewkey=ph5f3eb1e206aa8')
print(f'{nowtime()} Ждём {BRED}10 секунд{RESET} до отслеживания Zoom...') print(f'{nowtime()} Ждём {BRED}10 секунд{RESET} до отслеживания Zoom...')
time.sleep(10) time.sleep(10)
retries = 0
while not getState(): while not getState():
if getConfig("debug"): if getConfig("debug"):
print(f'{nowtime()} Урок задерживается, ждём...') print(f'{nowtime()} Урок задерживается, ждём...')
time.sleep(5) time.sleep(5)
retries += 1
if retries == 36:
tgsend(getConfig("telegram_enabled"), f"⚠ Задержка урока *{lesson_name}* превысила 3 минуты {profilename}")
if retries == 120:
tgsend(getConfig("telegram_enabled"), f"⚠ Задержка урока *{lesson_name}* превысила 10 минут {profilename}")
continue continue
record_now = False record_now = False
@@ -1049,19 +1220,13 @@ def main(source='deamon'):
print(f'{nowtime()} Захвачен текущий урок в Zoom.') print(f'{nowtime()} Захвачен текущий урок в Zoom.')
playSound("started") playSound("started")
tgsend(getConfig("telegram_enabled"), f"▶ Зашёл на урок *{lesson_name}* в *{nowtime(False, False, False)}*") tgsend(getConfig("telegram_enabled"), f"▶ Зашёл на урок *{lesson_name}* в *{nowtime(False, False, False)}* {profilename}")
rpc.onLesson(lesson_name, start_time_unix) rpc.onLesson(lesson_name, start_time_unix)
if lesson_obs: if lesson_obs:
try: try:
obs_path_file = open(files_folder+'obspath.txt', 'r', encoding="utf-8") obs_process = subprocess.Popen(getConfig("obs_exe"), cwd=getConfig("obs_core"))
obs_path_file_text = obs_path_file.read()
obs_core_path_file = open(files_folder+'obscorepath.txt', 'r', encoding="utf-8")
obs_core_path_file_text = obs_core_path_file.read()
obs_process = subprocess.Popen(obs_path_file_text, cwd=obs_core_path_file_text)
time.sleep(5) time.sleep(5)
except: except:
print(f'{nowtime()} Не удалось открыть OBS для записи.') print(f'{nowtime()} Не удалось открыть OBS для записи.')
@@ -1150,7 +1315,7 @@ def main(source='deamon'):
if getConfig("shutdown_enabled"): if getConfig("shutdown_enabled"):
if getConfig("end_mode") == 'shutdown': if getConfig("end_mode") == 'shutdown':
try: try:
tgsend(getConfig("telegram_enabled"), f"⚠ Уроки кончились, автовыключение через {nowtime(False, False, False)} мин...") tgsend(getConfig("telegram_enabled"), f"⚠ Уроки кончились, автовыключение {profilename}через {str(getConfig('shutdown_timeout'))} мин...")
print(f'{nowtime()} Ваш ПК автоматически выключится через {BRED}{str(getConfig("shutdown_timeout"))} мин{RESET}.') print(f'{nowtime()} Ваш ПК автоматически выключится через {BRED}{str(getConfig("shutdown_timeout"))} мин{RESET}.')
playSound("shutdown") playSound("shutdown")
end_unix = int(time.time())+getConfig("shutdown_timeout")*60 end_unix = int(time.time())+getConfig("shutdown_timeout")*60
@@ -1203,4 +1368,4 @@ if __name__ == '__main__':
import sys import sys
clear() clear()
main() main()

4
daemon.sh Normal file
View File

@@ -0,0 +1,4 @@
#!/bin/bash
echo "Running AutoZoom daemon with Python 3. Please read README.md!"
python3 daemon.py

View File

@@ -9,5 +9,7 @@
"run_fullscreen": false, "run_fullscreen": false,
"use_rpc": true, "use_rpc": true,
"sounds": true, "sounds": true,
"end_mode": "shutdown" "end_mode": "shutdown",
"obs_exe": null,
"obs_core": null
} }

View File

@@ -3,9 +3,7 @@
import pip import pip
import json import json
import os import os
import importlib
from pathlib import Path from pathlib import Path
from colors import *
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
@@ -28,19 +26,49 @@ def getConfig(some_var):
temp_config_list["use_rpc"] = True temp_config_list["use_rpc"] = True
temp_config_list["sounds"] = True temp_config_list["sounds"] = True
temp_config_list["end_mode"] = "shutdown" 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]
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()
return config_list[some_var] return config_list[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'):
temp_config_list = {}
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)
return temp_config_list[some_var]
else:
try:
with open(f"{files_folder}config.json", encoding="utf-8") as json_file:
config_list = json.load(json_file)
json_file.close()
return config_list[some_var]
except:
return "Error"
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)
f.close()

View File

@@ -61,6 +61,11 @@ try:
except ModuleNotFoundError: except ModuleNotFoundError:
libs.append("requests") libs.append("requests")
################################### ###################################
try:
import playsound
except ModuleNotFoundError:
libs.append("playsound")
###################################
try: try:
from zipfile import ZipFile from zipfile import ZipFile
except ModuleNotFoundError: except ModuleNotFoundError:
@@ -102,6 +107,7 @@ if len(libs) > 0:
import telegram_send import telegram_send
import wget import wget
import requests import requests
import playsound
import asyncio import asyncio
from zipfile import ZipFile from zipfile import ZipFile
from pypresence import Presence from pypresence import Presence

View File

@@ -30,7 +30,7 @@ import requests
import keyboard import keyboard
from zipfile import ZipFile from zipfile import ZipFile
version = 1.5 version = 1.8
path = Path(__file__).resolve().parent path = Path(__file__).resolve().parent
def mainMenu(): def mainMenu():
@@ -68,6 +68,7 @@ def mainMenu():
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}') menu_choose = input(f'\n > {BRED}')
print(RESET)
if menu_choose == '1': if menu_choose == '1':
main('menu') main('menu')
@@ -272,4 +273,4 @@ if __name__ == '__main__':
keyboard.release('alt, enter') keyboard.release('alt, enter')
os.system("title AutoZoom (Главная)") os.system("title AutoZoom (Главная)")
mainMenu() mainMenu()
sys.exit() sys.exit()

47
rpc.py
View File

@@ -3,9 +3,10 @@
import time import time
import os import os
import sys import sys
from colors import *
from functions import * from functions import *
version = '1.5' version = '1.8'
import libinstaller import libinstaller
from pypresence import Presence from pypresence import Presence
@@ -26,6 +27,8 @@ else:
connected = False connected = False
def disconnect(): def disconnect():
global connected
if getConfig("use_rpc"): if getConfig("use_rpc"):
try: try:
RPC.close() RPC.close()
@@ -34,6 +37,8 @@ def disconnect():
pass pass
def connect(): def connect():
global connected
try: try:
RPC.connect() RPC.connect()
connected = True connected = True
@@ -55,11 +60,11 @@ def waitLesson(lesson, start):
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def onLesson(lesson, start): def onLesson(lesson, start):
try: try:
@@ -70,13 +75,13 @@ def onLesson(lesson, start):
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def inMenu(): def inMenu():
try: try:
if getConfig("use_rpc"): if getConfig("use_rpc"):
if connected == False: if connected == False:
@@ -85,11 +90,11 @@ def inMenu():
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def shutdown(end): def shutdown(end):
try: try:
@@ -100,11 +105,11 @@ def shutdown(end):
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def inSettings(): def inSettings():
try: try:
@@ -115,11 +120,11 @@ def inSettings():
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def inEditor(): def inEditor():
try: try:
@@ -130,11 +135,11 @@ def inEditor():
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def inUpdater(): def inUpdater():
try: try:
@@ -145,11 +150,11 @@ def inUpdater():
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
def inHelp(): def inHelp():
try: try:
@@ -160,11 +165,11 @@ def inHelp():
except AttributeError: except AttributeError:
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(2) time.sleep(1)
except AssertionError: except AssertionError:
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(2) time.sleep(1)
@@ -175,7 +180,7 @@ if __name__ == "__main__":
except AttributeError: except AttributeError:
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(2) time.sleep(1)
################################################################################ ################################################################################
@@ -249,7 +254,7 @@ if __name__ == "__main__":
# ) # )
# discord_rpc.update_connection() # discord_rpc.update_connection()
# time.sleep(2) # time.sleep(1)
# discord_rpc.run_callbacks() # discord_rpc.run_callbacks()
# discord_rpc.shutdown() # discord_rpc.shutdown()
@@ -287,4 +292,4 @@ if __name__ == "__main__":
# 'large_image_text': f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom', # 'large_image_text': f'AutoZoom • v{version}\nhttp://bit.ly/auto_zoom',
# 'small_image_text': 'Ожидание', # 'small_image_text': 'Ожидание',
# } # }
# ) # )

4
start.sh Normal file
View File

@@ -0,0 +1,4 @@
#!/bin/bash
echo "AutoZoom needs Python 3 to work. Please read README.md!"
python3 main.py