diff --git a/.gitignore b/.gitignore index 541d26b..654822f 100644 --- a/.gitignore +++ b/.gitignore @@ -50,7 +50,6 @@ coverage.xml *.py,cover .hypothesis/ .pytest_cache/ -cover/ # Translations *.mo @@ -165,4 +164,5 @@ db/ test.py data/ export/ -temp/ \ No newline at end of file +temp/ +log/ diff --git a/compose.yml b/compose.yml index f498f9c..c814bfc 100644 --- a/compose.yml +++ b/compose.yml @@ -28,7 +28,7 @@ services: - dislocker_network db: - image: postgres:alpine3.20 + image: postgres:16-alpine3.20 restart: always environment: - TZ=Asia/Tokyo diff --git a/compose_db.yml b/compose_db.yml index 7cff067..f2a5251 100644 --- a/compose_db.yml +++ b/compose_db.yml @@ -1,6 +1,6 @@ services: db: - image: postgres:alpine3.20 + image: postgres:16-alpine3.20 restart: always environment: - TZ=Asia/Tokyo diff --git a/dislocker.py b/dislocker.py index fcb0401..7d5e140 100644 --- a/dislocker.py +++ b/dislocker.py @@ -1,14 +1,14 @@ -import json import discord -from discord import Interaction, TextStyle, app_commands -from discord.ui import TextInput, View, Modal import os +import json import psycopg2 from psycopg2 import sql -import hashlib +from datetime import datetime, timedelta +import asyncio import string import random -from datetime import datetime, timedelta +import hashlib +import openpyxl from openpyxl import Workbook import threading import time @@ -17,7 +17,10 @@ class DL(): def __init__(self): self.config_dir_path = "./config/" self.export_dir_path = "./export/" + self.log_dir_path = "./log/" self.server_config_path = self.config_dir_path + "server.json" + self.onetime_config_path = self.config_dir_path + "onetime.json" + self.log_path = self.log_dir_path + "dislocker.txt" try: if not os.path.isdir(self.config_dir_path): print("config ディレクトリが見つかりません... 作成します。") @@ -34,6 +37,7 @@ class DL(): "password": "password" }, "bot": { + "server_id": ["TYPE HERE SERVER ID (YOU MUST USE INT !!!!)"], "token": "TYPE HERE BOTS TOKEN KEY", "activity": { "name": "Dislocker", @@ -50,7 +54,7 @@ class DL(): "fstop_time": "21:00:00" }, "preset_games": ["TEST1", "TEST2", "TEST3", "TEST4", "TEST5"], - "admin_user_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", + "admin_user_id": ["TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)"], "debug": False } } @@ -63,11 +67,18 @@ class DL(): with open(self.server_config_path, "r", encoding="utf-8") as r: self.server_config = json.load(r) print("config ファイルを読み込みました。") - if not os.path.isdir(self.export_dir_path): print("export ディレクトリが見つかりません... 作成します。") os.mkdir(self.export_dir_path) + + if not os.path.isdir(self.log_dir_path): + print("log ディレクトリが見つかりません... 作成します。") + os.mkdir(self.log_dir_path) + + if os.path.isfile(self.onetime_config_path): + print("ワンタイムパスワードが見つかりました。削除します。") + os.remove(self.onetime_config_path) if type(self.server_config["bot"]["log_channel_id"]) is not int or type(self.server_config["bot"]["config_channel_id"]) is not int: print("config ファイル内でチャンネルIDがint型で記述されていません。int型で記述して、起動してください。") @@ -77,30 +88,53 @@ class DL(): cursor = self.db.cursor() self.pc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + self.keyboard_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + self.mouse_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.preset_games = self.server_config["bot"]["preset_games"] + self.debug = self.server_config["bot"]["debug"] - cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')") + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')") find_club_member_table = cursor.fetchall() print(find_club_member_table) if find_club_member_table[0][0] == False: - cursor.execute("CREATE TABLE club_member (id SERIAL NOT NULL, name VARCHAR(128) NOT NULL, discord_username VARCHAR(128) NOT NULL, discord_userid VARCHAR(18) NOT NULL, PRIMARY KEY (id))") + cursor.execute("CREATE TABLE club_member (member_id SERIAL NOT NULL, name TEXT NOT NULL, discord_user_name TEXT NOT NULL, discord_user_id TEXT NOT NULL, PRIMARY KEY (member_id))") self.db.commit() - cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_list')") + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_list')") find_pc_list_table = cursor.fetchall() print(find_pc_list_table) if find_pc_list_table[0][0] == False: - cursor.execute("CREATE TABLE pc_list (pc_number INTEGER NOT NULL, using_user_id INTEGER, password_hash VARCHAR(32), PRIMARY KEY (pc_number), FOREIGN KEY (using_user_id) REFERENCES club_member(id))") - for i in range(10): + cursor.execute("CREATE TABLE pc_list (pc_number INTEGER NOT NULL, using_member_id INTEGER, password_hash VARCHAR(64), pc_uuid VARCHAR(36), pc_token VARCHAR(36), master_password VARCHAR(16), detail TEXT, alt_name TEXT, PRIMARY KEY (pc_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))") + for i in self.pc_list: print(i) - cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (i + 1,)) + cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (i,)) self.db.commit() - cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_usage_history')") + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'keyboard_list')") + find_keyboard_list_table = cursor.fetchall() + print(find_keyboard_list_table) + if find_keyboard_list_table[0][0] == False: + cursor.execute("CREATE TABLE keyboard_list (keyboard_number INTEGER NOT NULL, using_member_id INTEGER, device_instance_path TEXT, device_name TEXT, detail TEXT, alt_name TEXT, PRIMARY KEY (keyboard_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))") + for i in self.keyboard_list: + print(i) + cursor.execute("INSERT INTO keyboard_list (keyboard_number) VALUES (%s)", (i,)) + self.db.commit() + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'mouse_list')") + find_mouse_list_table = cursor.fetchall() + print(find_mouse_list_table) + if find_mouse_list_table[0][0] == False: + cursor.execute("CREATE TABLE mouse_list (mouse_number INTEGER NOT NULL, using_member_id INTEGER, device_instance_path TEXT, device_name TEXT, detail TEXT, alt_name TEXT, PRIMARY KEY (mouse_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))") + for i in self.mouse_list: + print(i) + cursor.execute("INSERT INTO mouse_list (mouse_number) VALUES (%s)", (i,)) + self.db.commit() + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_usage_history')") find_pc_usage_history_table = cursor.fetchall() print(find_pc_usage_history_table) if find_pc_usage_history_table[0][0] == False: - cursor.execute("CREATE TABLE pc_usage_history (id SERIAL NOT NULL, member_id INTEGER NOT NULL, pc_number INTEGER NOT NULL, device_number INTEGER NOT NULL, start_use_time TIMESTAMP NOT NULL, end_use_time TIMESTAMP, use_detail VARCHAR(128), bot_about VARCHAR(128), PRIMARY KEY (id), FOREIGN KEY (member_id) REFERENCES club_member(id), FOREIGN KEY (pc_number) REFERENCES pc_list(pc_number))") + cursor.execute("CREATE TABLE pc_usage_history (id SERIAL NOT NULL, member_id INTEGER NOT NULL, pc_number INTEGER NOT NULL, keyboard_number INTEGER, mouse_number INTEGER, start_use_time TIMESTAMP NOT NULL, end_use_time TIMESTAMP, use_detail TEXT, bot_about TEXT, PRIMARY KEY (id), FOREIGN KEY (member_id) REFERENCES club_member(member_id), FOREIGN KEY (pc_number) REFERENCES pc_list(pc_number), FOREIGN KEY (keyboard_number) REFERENCES keyboard_list(keyboard_number), FOREIGN KEY (mouse_number) REFERENCES mouse_list(mouse_number))") self.db.commit() cursor.close() @@ -112,173 +146,363 @@ class DL(): finally: pass + + def log(self, **kwargs): + if self.debug == True: + flag = 1 + else: + if "flag" in kwargs: + if kwargs["flag"] == 1: + flag = 1 + else: + flag = 0 + else: + flag = 0 + + if flag == 1: + title = str(kwargs["title"]) + if "message" in kwargs: + message = str(kwargs["message"]) + else: + message = None + current_datetime = str(datetime.now()) -class Bot(discord.Client): + if message == None: + detail = f"{current_datetime} | {title}\n" + else: + detail = f"{current_datetime} | {title}\n{message}\n" + print(detail) + + if os.path.isfile(self.log_path): + try: + with open(self.log_path, "a", encoding="utf-8") as a: + a.write(detail) + except: + print("LOGGING ERROR mode a") + else: + try: + with open(self.log_path, "w", encoding="utf-8") as w: + w.write(detail) + except: + print("LOGGING ERROR mode w") + def password_generate(self, length): numbers = string.digits # (1) password = ''.join(random.choice(numbers) for _ in range(length)) # (2) return password def hash_genarate(self, source): - hashed = hashlib.md5(source.encode()) + hashed = hashlib.sha256(source.encode()) return hashed.hexdigest() + def user_register_check(self, **kwargs): + try: + discord_user_id = str(kwargs["discord_user_id"]) + + cursor = self.db.cursor() + + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) + user_record = cursor.fetchall() + #ユーザーデータが見つかった場合(登録済みの場合) + if user_record: + member_id = user_record[0][0] + name = user_record[0][1] + discord_user_name = user_record[0][2] + return {"result": 0, "about": "exist", "user_info": {"member_id": member_id, "name": name, "discord_user_name": discord_user_name}} + #ユーザーデータがなかったら(未登録の場合) + else: + return {"result": 1, "about": "user_data_not_found"} + + except Exception as error: + self.log(title=f"[ERROR] ユーザーの登録状態を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + cursor.close() + + def pc_used_check(self, **kwargs): + try: + if "pc_number" in kwargs: + pc_number = int(kwargs["pc_number"]) + else: + pc_number = None + if "discord_user_id" in kwargs: + discord_user_id = str(kwargs["discord_user_id"]) + else: + discord_user_id = None + if "member_id" in kwargs: + member_id = int(kwargs["member_id"]) + else: + member_id = None + + cursor = self.db.cursor() + + if pc_number != None: + # pc番号を指定してpc_listから探す + cursor.execute("SELECT * FROM pc_list WHERE pc_number= %s", (pc_number,)) + pc_list_record = cursor.fetchall() + if pc_list_record[0][1] == None: + return {"result": 0, "about": "vacent"} + else: + return {"result": 1, "about": "used_by_other"} + elif discord_user_id != None: + #ユーザーIDを指定してPC使用履歴から探す + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) + user_record = cursor.fetchall() + #ユーザーデータが見つかった場合(登録済みの場合) + if user_record: + member_id = user_record[0][0] + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage_history_record = cursor.fetchall() + if pc_usage_history_record: + if pc_usage_history_record[0][6] == None: + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + + return {"result": 1, "about": "used_by_you", "pc_usage_history": {"pc_number": str(pc_usage_history_record[0][2]), "keyboard_number": keyboard_number, "mouse_number": mouse_number, "start_time": str(pc_usage_history_record[0][5]), "use_detail": str(pc_usage_history_record[0][7])}} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 1, "about": "user_data_not_found"} + elif member_id != None: + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage_history_record = cursor.fetchall() + if pc_usage_history_record: + if pc_usage_history_record[0][6] == None: + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + return {"result": 1, "about": "used_by_you", "pc_usage_history": {"pc_number": str(pc_usage_history_record[0][2]), "keyboard_number": keyboard_number, "mouse_number": mouse_number, "start_time": str(pc_usage_history_record[0][5]), "use_detail": str(pc_usage_history_record[0][7])}} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 1, "about": "search_options_error"} + + except Exception as error: + self.log(title=f"[ERROR] PCの使用状況を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def keyboard_used_check(self, **kwargs): + try: + cursor = self.db.cursor() + if kwargs["keyboard_number"] == None: + return {"result": 0, "about": "ok"} + else: + keyboard_number = int(kwargs["keyboard_number"]) + + cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number=%s", (keyboard_number,)) + keyboard_list_record = cursor.fetchall() + if keyboard_list_record[0][1] == None: + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "keyboard_already_in_use_by_other"} + + except Exception as error: + self.log(title=f"[ERROR] キーボードの使用状況を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def mouse_used_check(self, **kwargs): + try: + cursor = self.db.cursor() + if kwargs["mouse_number"] == None: + return {"result": 0, "about": "ok"} + else: + mouse_number = int(kwargs["mouse_number"]) + + cursor.execute("SELECT * FROM mouse_list WHERE mouse_number=%s", (mouse_number,)) + mouse_list_record = cursor.fetchall() + if mouse_list_record[0][1] == None: + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "mouse_already_in_use_by_other"} + + except Exception as error: + self.log(title=f"[ERROR] マウスの使用状況を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def register(self, **kwargs): try: + cursor = self.db.cursor() user_info = { - "id": str(kwargs["user_id"]), + "id": str(kwargs["discord_user_id"]), "name": str(kwargs["name"]), "display_name": str(kwargs["display_name"]), "pc_number": int(kwargs["pc_number"]), - "device_number": int(kwargs["device_number"]), + "keyboard_number": 0, + "mouse_number": 0, "detail": None } if "detail" in kwargs: user_info["detail"] = str(kwargs["detail"]) else: pass - #パスワード生成、ハッシュ化 - password = self.password_generate(4) - password_hash = self.hash_genarate(password) - print("password generated") - #メンバーリストと送信者を照合 - cursor = dislocker.db.cursor() - cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (user_info["id"],)) - user_record = cursor.fetchall() - #ユーザーデータがなかったら(未登録の場合) - if not user_record: - result = {"result": "user_data_not_found"} - #ユーザーデータが見つかった場合(登録済みの場合) + + if kwargs["keyboard_number"] == "0": + pass else: - print("found user data") - cursor.execute("SELECT * FROM pc_usage_history WHERE member_id=%s ORDER BY id DESC LIMIT 1", (user_record[0][0],)) - pc_usage_history_record = cursor.fetchall() - if pc_usage_history_record: - print("used") - if pc_usage_history_record[0][5] == None: - result = {"result": "pc_already_in_use_by_you", "pc_number": str(pc_usage_history_record[0][2]), "device_number": str(pc_usage_history_record[0][3]), "start_time": str(pc_usage_history_record[0][4]), "detail": str(pc_usage_history_record[0][6])} - else: - cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (user_info["pc_number"],)) - pc_list_record = cursor.fetchall() - if not pc_list_record[0][1] == None: - result = {"result": "pc_already_in_use_by_other"} - else: - if user_info["detail"] == None: - cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time) VALUES (%s, %s, %s, clock_timestamp())", (user_record[0][0], user_info["pc_number"], user_info["device_number"])) - #使用用途があるとき + user_info["keyboard_number"] = int(kwargs["keyboard_number"]) + + if kwargs["mouse_number"] == "0": + pass + else: + user_info["mouse_number"] = int(kwargs["mouse_number"]) + # ユーザー登録されているかの確認 + user_register = self.user_register_check(discord_user_id=user_info["id"]) + if user_register["result"] == 0: + member_id = user_register["user_info"]["member_id"] + name = user_register["user_info"]["name"] + # ユーザーがPCを使っているか + pc_check_self = self.pc_used_check(member_id=member_id) + if pc_check_self["result"] == 0: + # 他の人がそのPCを使っているか + pc_check = self.pc_used_check(pc_number=user_info["pc_number"]) + if pc_check["result"] == 0: + # キーボードは使われているか + keyboard_check = self.keyboard_used_check(keyboard_number=user_info["keyboard_number"]) + if keyboard_check["result"] == 0: + # マウスは使われているか + mouse_check = self.mouse_used_check(mouse_number=user_info["mouse_number"]) + if mouse_check["result"] == 0: + # パスワードとハッシュ作成 + password = self.password_generate(4) + password_hash = self.hash_genarate(password) + # PC使用履歴のテーブルにレコードを挿入 + + cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, keyboard_number, mouse_number, start_use_time, use_detail) VALUES (%s, %s, %s, %s, clock_timestamp(), %s)", (member_id, user_info["pc_number"], user_info["keyboard_number"], user_info["mouse_number"], user_info["detail"])) + # PCリストの該当のレコードを更新 + cursor.execute("UPDATE pc_list SET using_member_id = %s, password_hash = %s WHERE pc_number = %s", (member_id, password_hash, user_info["pc_number"])) + # キーボードリストの該当のレコードを自前(None)だったらスキップ、借りていたら更新 + if user_info["keyboard_number"] == 0: + pass + else: + cursor.execute("UPDATE keyboard_list SET using_member_id = %s WHERE keyboard_number = %s", (member_id, user_info["keyboard_number"])) + # マウスも同様に + if user_info["mouse_number"] == 0: + pass + else: + cursor.execute("UPDATE mouse_list SET using_member_id = %s WHERE mouse_number = %s", (member_id, user_info["mouse_number"])) + self.db.commit() + return {"result": 0, "about": "ok", "output_dict": {"password": str(password), "name": str(name)}} else: - cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, clock_timestamp(), %s)", (user_record[0][0], user_info["pc_number"], user_info["device_number"], user_info["detail"])) - - cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], user_info["pc_number"])) - cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"])) - dislocker.db.commit() - result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])} + return {"result": 1, "about": "mouse_already_in_use"} + else: + return {"result": 1, "about": "keyboard_already_in_use"} + else: + return {"result": 1, "about": "pc_already_in_use_by_other"} else: - print("unused") - cursor.execute("SELECT * FROM pc_list WHERE pc_number=%s", (user_info["pc_number"],)) - pc_list_record = cursor.fetchall() - if pc_list_record: - if not pc_list_record[0][1] == None: - result = {"result": "pc_already_in_use_by_other"} - else: - if user_info["detail"] == None: - cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time) VALUES (%s, %s, %s, clock_timestamp())", (user_record[0][0], user_info["pc_number"], user_info["device_number"])) - #使用用途があるとき - else: - cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, clock_timestamp(), %s)", (user_record[0][0], user_info["pc_number"], user_info["device_number"], user_info["detail"])) - - cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], user_info["pc_number"])) - cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"])) - dislocker.db.commit() - result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])} - else: - if user_info["detail"] == None: - cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time) VALUES (%s, %s, %s, clock_timestamp())", (user_record[0][0], user_info["pc_number"], user_info["device_number"])) - #使用用途があるとき - else: - cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, clock_timestamp(), %s)", (user_record[0][0], user_info["pc_number"], user_info["device_number"], user_info["detail"])) - - cursor.execute("UPDATE pc_list SET using_user_id = %s WHERE pc_number = %s", (user_record[0][0], user_info["pc_number"])) - cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"])) - dislocker.db.commit() - result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])} - - + return {"result": 1, "about": "pc_already_in_use_by_you", "pc_usage_history": {"pc_number": pc_check_self["pc_usage_history"]["pc_number"], "keyboard_number": pc_check_self["pc_usage_history"]["keyboard_number"], "mouse_number": pc_check_self["pc_usage_history"]["mouse_number"], "start_time": pc_check_self["pc_usage_history"]["start_time"], "use_detail": pc_check_self["pc_usage_history"]["use_detail"]}} + else: + return {"result": 1, "about": "user_data_not_found"} except Exception as error: - print("登録処理中にエラーが発生しました。\nエラー内容") - print(str(error.__class__.__name__)) - print(str(error.args)) - print(str(error)) - result = {"result": "error"} - + self.log(title=f"[ERROR] PCの使用登録中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} finally: - cursor.close() - return result + if cursor: + cursor.close() + def stop(self, **kwargs): try: - discord_user_id = str(kwargs["user_id"]) + cursor = self.db.cursor() + discord_user_id = str(kwargs["discord_user_id"]) if "bot_about" in kwargs: bot_about = kwargs["bot_about"] else: bot_about = None - cursor = dislocker.db.cursor() - cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) - user_record = cursor.fetchall() - if user_record: - cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (user_record[0][0],)) - pc_usage_history_record = cursor.fetchall() - if pc_usage_history_record: - if not pc_usage_history_record[0][5] == None: - result = {"result": "unused"} - else: - if not bot_about == None: - cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record[0][0])) - else: - cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (pc_usage_history_record[0][0],)) + + # ユーザーが登録してるかというよりはデータの取得のため + user_register = self.user_register_check(discord_user_id=discord_user_id) + member_id = user_register["user_info"]["member_id"] + name = user_register["user_info"]["name"] - cursor.execute("UPDATE pc_list SET using_user_id = NULL, password_hash = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],)) - dislocker.db.commit() - result = {"result": "ok", "pc_number": str(pc_usage_history_record[0][2]), "name": str(user_record[0][1])} + if user_register["result"] == 0: + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage_history_record = cursor.fetchall() + + if pc_usage_history_record: + pc_usage_history_id = pc_usage_history_record[0][0] + pc_number = pc_usage_history_record[0][2] + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + end_use_time = pc_usage_history_record[0][6] + + # 使用中のとき (使用停止時間がNoneのとき) + if end_use_time == None: + # 利用停止の理由の有無を判断 + if bot_about == None: + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (pc_usage_history_id,)) + else: + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_id)) + # pc_listの使用中ユーザーを消す + cursor.execute("UPDATE pc_list SET using_member_id = NULL, password_hash = NULL WHERE pc_number = %s", (pc_number,)) + if keyboard_number == None: + pass + else: + # keyboard_listの使用中ユーザーを消す + cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,)) + if mouse_number == None: + pass + else: + # mouse_listの使用中ユーザーを消す + cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE mouse_number = %s", (mouse_number,)) + self.db.commit() + return {"result": 0, "about": "ok", "output_dict": {"pc_number": str(pc_number), "name": str(name)}} + else: + return {"result": 1, "about": "unused"} else: - result = {"result": "unused"} + return {"result": 1, "about": "unused"} else: - result = {"result": "user_data_not_found"} - except: - print("停止処理にエラーが発生しました。") - result = {"result": "error"} + return {"result": 1, "about": "user_data_not_found"} + + except Exception as error: + self.log(title=f"[ERROR] PCの使用停止処理中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} finally: - cursor.close() - return result + if cursor: + cursor.close() def user_register(self, **kwargs): try: discord_user_id = str(kwargs["discord_user_id"]) discord_user_name = str(kwargs["discord_user_name"]) name = str(kwargs["name"]) - cursor = dislocker.db.cursor() - cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) + cursor = self.db.cursor() + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) user_record = cursor.fetchall() if not user_record: - cursor.execute("INSERT INTO club_member (name, discord_username, discord_userid) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id)) - dislocker.db.commit() - result = {"result": "ok"} + cursor.execute("INSERT INTO club_member (name, discord_user_name, discord_user_id) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id)) + self.db.commit() + return {"result": 0, "about": "ok"} else: - result = {"result": "already_exists"} + return {"result": 1, "about": "already_exists"} except Exception as error: - print("ユーザー登録中にエラーが発生しました。\nエラー内容") - print(str(error.__class__.__name__)) - print(str(error.args)) - print(str(error)) - result = {"result": "error"} + self.log(title=f"[ERROR] ユーザー情報の登録中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} finally: - cursor.close() - return result + if cursor: + cursor.close() + def format_datetime(self, value): if isinstance(value, datetime): @@ -288,34 +512,31 @@ class Bot(discord.Client): def pc_register(self, **kwargs): try: pc_number = int(kwargs["pc_number"]) - cursor = dislocker.db.cursor() + cursor = self.db.cursor() cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_list = cursor.fetchall() if not pc_list: cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (pc_number,)) - dislocker.db.commit() - result = {"result": "ok"} + self.db.commit() + return {"result": 0, "about": "ok"} else: - result = {"result": "already_exists"} + return {"result": 1, "about": "already_exists"} except Exception as error: - print("PCの登録中にエラーが発生しました。\nエラー内容") - print(str(error.__class__.__name__)) - print(str(error.args)) - print(str(error)) - result = {"result": "error"} + self.log(title=f"[ERROR] PCの情報を登録中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} finally: - cursor.close() - return result + if cursor: + cursor.close() def report_export(self, **kwargs): try: - cursor = dislocker.db.cursor() - csv_file_path = dislocker.export_dir_path + "pc_usage_history.csv" + cursor = self.db.cursor() + csv_file_path = self.export_dir_path + "pc_usage_history.csv" main_table = "pc_usage_history" related_table = "club_member" - excel_file_path = dislocker.export_dir_path + "pc_usage_history.xlsx" + excel_file_path = self.export_dir_path + "pc_usage_history.xlsx" # メインテーブルの列情報を取得(user_idを除く) cursor.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table))) @@ -325,7 +546,7 @@ class Bot(discord.Client): query = sql.SQL(""" SELECT {main_columns}, {related_table}.name FROM {main_table} - LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.id + LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.member_id ORDER BY id """).format( main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]), @@ -368,331 +589,401 @@ class Bot(discord.Client): # Excelファイルを保存 wb.save(excel_file_path) - - print(f"テーブル '{main_table}' の内容を '{excel_file_path}' に出力しました。") - result = {"result": "ok", "file_path": excel_file_path} + self.log(title=f"[SUCCESS] PCの使用履歴をエクスポートしました。", message=f"ファイルパス | {excel_file_path}", flag=0) + return {"result": 0, "about": "ok", "file_path": excel_file_path} + + + except Exception as error: + self.log(title=f"[ERROR] PCの使用履歴をエクスポート中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} - except (Exception, psycopg2.Error) as error: - print("使用履歴のエクスポート時にエラーが発生しました\nエラー内容\n", str(error)) - result = {"result": "export_error"} - finally: - cursor.close() - return result + if cursor: + cursor.close() + def force_stop(self, **kwargs): try: pc_number = kwargs["pc_number"] + cursor = self.db.cursor() if "bot_about" in kwargs: bot_about = kwargs["bot_about"] - cursor = dislocker.db.cursor() cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_list_record = cursor.fetchall() - if not pc_list_record[0][1] == None: - cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_number,)) - - if not pc_list_record[0][2] == None: + pc_using_member_id = pc_list_record[0][1] + pc_password_hash = pc_list_record[0][2] + if pc_using_member_id == None: + return {"result": 1, "about": "not_used"} + else: + cursor.execute("UPDATE pc_list SET using_member_id = NULL WHERE pc_number = %s", (pc_number,)) + if pc_password_hash == None: + pass + else: cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) - - cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_list_record[0][1], pc_number)) + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number)) pc_usage_history_record = cursor.fetchall() - cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record[0][0])) - dislocker.db.commit() - result = {"result": "ok"} - - else: - result = {"result": "not_used"} + pc_usage_history_record_id = pc_usage_history_record[0][0] + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + if keyboard_number == None: + pass + else: + # keyboard_listの使用中ユーザーを消す + cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,)) + if mouse_number == None: + pass + else: + # mouse_listの使用中ユーザーを消す + cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE mouse_number = %s", (mouse_number,)) + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record_id)) + self.db.commit() + return {"result": 0, "about": "ok"} else: - bot_about = None - result = {"result": "bot_about_not_found"} + return {"result": 1, "about": "bot_about_not_found"} - - except: - result = {"result": "error"} - - finally: - cursor.close() - return result - - - async def timeout_notify(self, **kwargs): - try: - pc_number = kwargs["pc_number"] - discord_display_name = kwargs["discord_display_name"] - - await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {discord_display_name} さんのPC {pc_number} の使用登録はタイムアウトにより解除されました。') - result = {"result": "ok"} - except Exception as error: - print("自動停止処理中にエラーが発生しました。\nエラー内容") - print(str(error.__class__.__name__)) - print(str(error.args)) - print(str(error)) - result = {"result": "error"} + self.log(title=f"[ERROR] fstop中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} finally: - return result - + if cursor: + cursor.close() + + def pc_onetime_gen(self, **kwargs): + if kwargs.get("max_count") == None: + max_count = 1 + elif isinstance(kwargs.get("max_count"), int): + max_count = int(kwargs.get("max_count")) + else: + max_count = 1 - async def on_ready(self): - print("DiscordのBotが起動しました。") - dislocker_activity = discord.Activity( - name=dislocker.server_config["bot"]["activity"]["name"], - type=discord.ActivityType.competing, - details=dislocker.server_config["bot"]["activity"]["details"], - state=dislocker.server_config["bot"]["activity"]["state"] - ) - await bot.change_presence(activity=dislocker_activity) - - async def on_interaction(self, interaction:discord.Interaction): try: - if interaction.data["component_type"] == 2: - await self.on_button(interaction) - except KeyError: - pass - - async def on_message(self, message): - if message.author.bot: - pass - - elif isinstance(message.channel, discord.DMChannel): - msg_split = message.content.split() - if msg_split[0] == "/password" or msg_split[0] == "/start": - #メッセージの要素が2つ以下の場合は拒否 - if len(msg_split) <= 2: - await message.channel.send("# :warning: PC番号、もしくはデバイス番号が入力されていません。") - #メッセージの要素が3つ以上の場合 - elif len(msg_split) >= 3: - #番号が数字であることを確認 - if msg_split[1].isdigit() and msg_split[2].isdigit(): - #PC番号が1以上10以下であることを確認 - if int(msg_split[1]) <= 10 and int(msg_split[1]) >= 1: - if len(msg_split) == 3: - register = self.register(user_id=message.author.id, name=message.author.name, display_name=message.author.display_name, pc_number=msg_split[1], device_number=msg_split[2]) - elif len(msg_split) == 4: - register = self.register(user_id=message.author.id, name=message.author.name, display_name=message.author.display_name, pc_number=msg_split[1], device_number=msg_split[2], detail=msg_split[3]) - - if register["result"] == "ok": - if len(msg_split) == 3: - await message.channel.send(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {msg_split[1]}\n## デバイス番号 | {msg_split[2]}") - elif len(msg_split) == 4: - await message.channel.send(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {msg_split[1]}\n## デバイス番号 | {msg_split[2]}\n## 使用目的 | {msg_split[3]}") - await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["name"]} さんがPC {msg_split[1]} の使用を開始しました。') - elif register["result"] == "user_data_not_found": - await message.channel.send("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。") - elif register["result"] == "pc_already_in_use_by_you": - await message.channel.send(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには /stop で使用終了をお知らせください。\n>>> # PC番号 | {register["pc_number"]}\n# デバイス番号 | {register["device_number"]}\n# 使用開始時刻 | {register["start_time"]}\n# 使用目的 | {register["detail"]}") - elif register["result"] == "pc_already_in_use_by_other": - await message.channel.send(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。") - else: - await message.channel.send("# :dizzy_face: 番号がおかしいようです。") - else: - await message.channel.send("# :dizzy_face: 指定された番号は不正です。") + if os.path.isfile(dislocker.onetime_config_path): + with open(dislocker.onetime_config_path, "r") as r: + onetime_config = json.load(r) + onetime_password = onetime_config["onetime"]["pc_register"]["password"] + if onetime_password == None: + onetime_password = str(self.password_generate(8)) + onetime_config["onetime"]["pc_register"]["password"] = onetime_password + onetime_config["onetime"]["pc_register"]["max_count"] = max_count + onetime_config["onetime"]["pc_register"]["current_count"] = 0 + current_count = onetime_config["onetime"]["pc_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + else: + current_count = onetime_config["onetime"]["pc_register"]["current_count"] + max_count = onetime_config["onetime"]["pc_register"]["max_count"] + return {"result": 1, "about": "already_exists", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + else: + onetime_password = str(self.password_generate(8)) + onetime_config = { + "onetime": { + "pc_register": { + "password": onetime_password, + "current_count": 0, + "max_count": int(max_count) + }, + "device_register": { + "password": None, + "current_count": None, + "max_count": None + } + } + } + current_count = onetime_config["onetime"]["pc_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} - elif msg_split[0] == "/stop": - stop = self.stop(user_id=message.author.id) - if stop["result"] == "unused": - await message.channel.send("# :shaking_face: 使用されていないようです...") - elif stop["result"] == "ok": - await message.channel.send(f":white_check_mark: PC番号 {stop["pc_number"]} の使用が終了されました。") - await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {stop["name"]} さんがPC {stop["pc_number"]} の使用を終了しました。') + except Exception as error: + self.log(title=f"[ERROR] PC登録用のワンタイムパスワード発行中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} - elif message.channel.id == dislocker.server_config["bot"]["config_channel_id"]: - msg_split = message.content.split() - if msg_split[0] == "/register": - print(len(msg_split)) - if len(msg_split) == 1: - register = self.user_register(name=message.author.display_name, discord_user_name=message.author.name, discord_user_id=message.author.id) - print(register) - if register["result"] == "ok": - await message.channel.send(f"# :white_check_mark: ユーザー情報が登録されました。\n>>> ユーザー名:{message.author.display_name}") - elif register["result"] == "already_exists": - await message.channel.send("# :no_entry: 登録できませんでした。\nもう登録されている可能性があります。") - else: - await message.channel.send("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。") - - elif len(msg_split) <= 3: - await message.channel.send("# :japanese_goblin: 入力内容に不備があります。\n名前、Discordのユーザー名、DiscordのユーザーIDのいずれかが入力されていません。") - elif len(msg_split) == 4: - if msg_split[3].isdigit(): - register = self.user_register(name=msg_split[1], discord_user_name=msg_split[2], discord_user_id=msg_split[3]) - if register["result"] == "ok": - await message.channel.send(f"# :white_check_mark: 登録が完了しました。\n>>> # 名前 | {msg_split[1]}\n# Discordのユーザー名 | {msg_split[2]}\n# DiscordのユーザーID | {msg_split[3]}") - elif register["result"] == "already_exists": - await message.channel.send("# :skull_crossbones: 登録できませんでした。\nそのDiscordアカウントはすでに登録されています。") - else: - await message.channel.send("# :skull_crossbones: 登録できませんでした。\nDiscordのユーザーIDが不正です。") - else: - await message.channel.send("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。") - - elif msg_split[0] == "/export": - export = self.report_export() - if export["result"] == "ok": - await message.channel.send("# :page_facing_up: 使用履歴のレポートです。", file=discord.File(export["file_path"])) - pass - elif export["result"] == "export_error": - await message.channel.send("# :volcano: エクスポートに失敗しました。") - - elif msg_split[0] == "/fstop": - if len(msg_split) == 1: - await message.channel.send("# :warning: 登録を解除できませんでした。\n使用を停止したいPC番号を指定してください。\n-# /fstop PC番号") - elif len(msg_split) == 2: - if msg_split[1].isdigit(): - fstop = self.force_stop(pc_number=msg_split[1], bot_about="管理者による強制停止。") - if fstop["result"] == "ok": - await message.channel.send(f"# :white_check_mark: PC番号 {msg_split[1]} の使用登録を解除しました。") - elif fstop["result"] == "not_used": - await message.channel.send("# :exploding_head: 登録を解除できませんでした。\nPCは使用されていないようです...") - else: - await message.channel.send("# :x: 登録を解除できませんでした。\n内部エラーが発生しています。") - else: - await message.channel.send("# :warning: 登録を解除できませんでした。\nPC番号を認識できません。\n-# 半角数字で入力してください。") - else: - await message.channel.send("# warning: 登録を解除できませんでした。\構文が間違っています。\n-# /fstop PC番号") - - elif msg_split[0] == "/pcregister": - if len(msg_split) == 1: - await message.channel.send("# :warning: PCを登録できませんでした。\n登録したいPC番号を指定してください。\n-# 半角数字で入力してください。") - elif len(msg_split) == 2: - if msg_split[1].isdigit(): - pc_register = self.pc_register(pc_number=msg_split[1]) - if pc_register["result"] == "ok": - await message.channel.send(f"# :white_check_mark: PCを登録しました。\n>>> # PC番号 | {msg_split[1]}") - elif pc_register["result"] == "already_exists": - await message.channel.send(f":x: PCを登録できませんでした。\nその番号のPCは既に存在します。") - else: - await message.channel.send("# :x: PCを登録できませんでした。\n内部エラーが発生しています。") - else: - await message.channel.send("# :warning: PCを登録できませんでした。\nPC番号を認識できません。\n-# 半角数字で入力してください。") - else: - await message.channel.send("# :warning: PCを登録できませんでした。\n構文が間違っています。\n-# /pcregister PC番号") - - elif msg_split[0] == "/registerbutton": - pc_button_view = View(timeout=None) - for i in range(1, 11): - pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{i}", custom_id=f"pcregister_{i}") - pc_button_view.add_item(pc_register_button) - - await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: 使いたいPCの番号を選んでください!', view=pc_button_view) - - elif msg_split[0] == "/stopbutton": - stop_button_view = View(timeout=None) - stop_button = discord.ui.Button(style=discord.ButtonStyle.danger, label="PCの使用を停止", custom_id="stop") - stop_button_view.add_item(stop_button) - - await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: 使用を停止しますか?', view=stop_button_view) - - elif msg_split[0] == "/userbutton": - user_register_button_view = View(timeout=None) - user_register_button = discord.ui.Button(style=discord.ButtonStyle.green, label="ユーザー登録", custom_id="user_register") - user_register_button_view.add_item(user_register_button) - - await self.get_channel(dislocker.server_config["bot"]["config_public_channel_id"]).send(f'# :index_pointing_at_the_viewer: ユーザー登録はお済ですか?', view=user_register_button_view) - - - - elif message.channel.id == dislocker.server_config["bot"]["config_public_channel_id"]: - msg_split = message.content.split() - if msg_split[0] == "/register": - print(len(msg_split)) - if len(msg_split) == 1: - register = self.user_register(name=message.author.display_name, discord_user_name=message.author.name, discord_user_id=message.author.id) - print(register) - if register["result"] == "ok": - await message.channel.send(f"# :white_check_mark: ユーザー情報が登録されました。\nユーザー名:{message.author.display_name}") - elif register["result"] == "already_exists": - await message.channel.send("# :skull_crossbones: 登録できませんでした。\nそのDiscordアカウントはすでに登録されています。") - else: - await message.channel.send("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。") - else: - await message.channel.send("# :skull_crossbones: 登録できませんでした。\n\n-# もしかして...\n-# 手動でメンバーを登録したいですか?\n-# もしそうなら、このチャンネルにはその権限がありません。\n-# そのチャンネルに移動してから、もう一度試してみてください!") - - async def on_button(self, interaction: Interaction): - custom_id = interaction.data["custom_id"] - custom_id_split = custom_id.split("_") - print(custom_id, custom_id_split[0]) - if custom_id_split[0] == "pcregister": - device_register_view = View(timeout=15) - pc_number = custom_id_split[1] - print(custom_id_split) - for i in range(1, 11): - device_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{i}", custom_id=f"deviceregister_{str(pc_number)}_{i}") - device_register_view.add_item(device_register_button) - device_own_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="自前", custom_id=f"deviceregister_{str(pc_number)}_own") - device_register_view.add_item(device_own_register_button) + def device_onetime_gen(self, **kwargs): + if kwargs.get("max_count") == None: + max_count = 1 + elif isinstance(kwargs.get("max_count"), int): + max_count = int(kwargs.get("max_count")) + else: + max_count = 1 - await interaction.response.send_message(f"# :keyboard: デバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=device_register_view, ephemeral=True) - - elif custom_id_split[0] == "deviceregister": - pc_number = custom_id_split[1] - device_number = custom_id_split[2] - reason_register_view = View(timeout=15) - for i in dislocker.preset_games: - reason_quick_button = reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"reasonregister_{str(pc_number)}_{str(device_number)}_quick_{str(i)}") - reason_register_view.add_item(reason_quick_button) - reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(device_number)}") - reason_register_view.add_item(reason_button) - - await interaction.response.send_message(f"# :regional_indicator_q: 使用目的を書いてください!\n>>> # PC番号 | {str(pc_number)}\n# デバイス番号 | {str(device_number)}", view=reason_register_view, ephemeral=True) - - elif custom_id_split[0] == "reasonregister": - pc_number = custom_id_split[1] - device_number = custom_id_split[2] - - if len(custom_id_split) >= 4: - if custom_id_split[3] == "quick": - reason = custom_id_split[4] - if device_number == "own": - device_number = 0 - else: - device_number = custom_id_split[2] - - register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, device_number=device_number, detail=reason) - print(register["result"]) - - if register["result"] == "ok": - await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {pc_number}\n## デバイス番号 | {device_number}\n## 使用目的 | {reason}", ephemeral=True) - await bot.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["name"]} さんがPC {pc_number} の使用を開始しました。') - elif register["result"] == "pc_already_in_use_by_you": - await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {register["pc_number"]}\n# デバイス番号 | {register["device_number"]}\n# 使用開始時刻 | {register["start_time"]}\n# 使用目的 | {register["detail"]}", ephemeral=True) - elif register["result"] == "pc_already_in_use_by_other": - await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True) - elif register["result"] == "user_data_not_found": - await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) - else: - await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + try: + if os.path.isfile(dislocker.onetime_config_path): + with open(dislocker.onetime_config_path, "r") as r: + onetime_config = json.load(r) + onetime_password = onetime_config["onetime"]["device_register"]["password"] + if onetime_password == None: + onetime_password = str(self.password_generate(8)) + onetime_config["onetime"]["device_register"]["password"] = onetime_password + onetime_config["onetime"]["device_register"]["max_count"] = max_count + onetime_config["onetime"]["device_register"]["current_count"] = 0 + current_count = onetime_config["onetime"]["device_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} else: - reason_input_form = Reason(title="Dislocker | 登録", pc_number=str(pc_number), device_number=str(device_number)) - await interaction.response.send_modal(reason_input_form) + current_count = onetime_config["onetime"]["device_register"]["current_count"] + max_count = onetime_config["onetime"]["device_register"]["max_count"] + return {"result": 1, "about": "already_exists", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} else: - reason_input_form = Reason(title="Dislocker | 登録", pc_number=str(pc_number), device_number=str(device_number)) - await interaction.response.send_modal(reason_input_form) + onetime_password = str(self.password_generate(8)) + onetime_config = { + "onetime": { + "pc_register": { + "password": None, + "current_count": None, + "max_count": None + }, + "device_register": { + "password": onetime_password, + "current_count": 0, + "max_count": int(max_count) + } + } + } + current_count = onetime_config["onetime"]["device_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + + except Exception as error: + self.log(title=f"[ERROR] デバイス登録用のワンタイムパスワード発行中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + def show_pc_master_password(self, **kwargs): + try: + if isinstance(kwargs.get("pc_number"), int): + pc_number = int(kwargs.get("pc_number")) - elif custom_id_split[0] == "stop": - print("STOP running") - pc_stop = self.stop(user_id=interaction.user.id) - print(pc_stop) - stop_view = View(timeout=15) - if pc_stop["result"] == "unused": - await interaction.response.send_message("# :shaking_face: 使用されていないようです...", ephemeral=True) - elif pc_stop["result"] == "user_data_not_found": - await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) - elif pc_stop["result"] == "ok": - await interaction.response.send_message(f":white_check_mark: PC番号 {pc_stop["pc_number"]} の使用が終了されました。", ephemeral=True) - await self.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {pc_stop["name"]} さんがPC {pc_stop["pc_number"]} の使用を終了しました。') - else: - await interaction.response.send_message("# :skull_crossbones: 停止できませんでした。\n内部エラーが発生しています。", ephemeral=True) + cursor = self.db.cursor() + cursor.execute("SELECT master_password FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_master_password_list = cursor.fetchall() + pc_master_password = pc_master_password_list[0][0] - elif custom_id_split[0] == "user" and custom_id_split[1] == "register": - print("User Register RUnning") - user_register = self.user_register(name=interaction.user.display_name, discord_user_name=interaction.user.name, discord_user_id=interaction.user.id) - if user_register["result"] == "ok": - await interaction.response.send_message(f"# :white_check_mark: ユーザー情報が登録されました。\n>>> ユーザー名:{interaction.user.display_name}", ephemeral=True) - elif user_register["result"] == "already_exists": - await interaction.response.send_message("# :no_entry: 登録できませんでした。\nもう登録されている可能性があります。", ephemeral=True) + return {"result": 0, "about": "ok", "output_dict": {"pc_master_password": pc_master_password}} + else: - await interaction.response.send_message("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + return {"result": 1, "about": "syntax_error"} + except Exception as error: + self.log(title=f"[ERROR] PCのマスターパスワードを取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_discord_user_id(self, **kwargs): + try: + member_id = int(kwargs["member_id"]) + cursor = self.db.cursor() + cursor.execute("SELECT discord_user_id FROM club_member WHERE member_id = %s", (member_id,)) + discord_user_id_list = cursor.fetchall() + discord_user_id = discord_user_id_list[0][0] + return {"result": 0, "about": "ok", "discord_user_id": discord_user_id} + + except Exception as error: + self.log(title=f"[ERROR] DiscordのユーザーIDの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_pc_list(self, **kwargs): + try: + cursor = self.db.cursor() + + if "pc_number" in kwargs: + pc_number = int(kwargs["pc_number"]) + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_list = cursor.fetchall() + + return {"result": 0, "about": "ok", "output_dict": {pc_number: {"pc_number": pc_list[0][0], "using_member_id": pc_list[0][1], "pc_token": i[4], "master_password": [0][5], "detail": pc_list[0][6], "alt_name": pc_list[0][7]}}} + else: + cursor.execute("SELECT * FROM pc_list ORDER BY pc_number") + pc_list = cursor.fetchall() + pc_list_base = {} + for i in pc_list: + pc_list_base[i[0]] = {"pc_number": i[0], "using_member_id": i[1], "pc_token": i[4], "master_password": i[5], "detail": i[6], "alt_name": i[7]} + + return {"result": 0, "about": "ok", "output_dict": pc_list_base} + + except Exception as error: + self.log(title=f"[ERROR] PCリストの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_keyboard_list(self, **kwargs): + try: + cursor = self.db.cursor() + + if "keyboard_number" in kwargs: + keyboard_number = int(kwargs["keyboard_number"]) + cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number = %s", (keyboard_number,)) + keyboard_list = cursor.fetchall() + + return {"result": 0, "about": "ok", "output_dict": {keyboard_number: {"keyboard_number": keyboard_list[0][0], "using_member_id": keyboard_list[0][1], "device_instance_path": keyboard_list[0][2], "device_name": keyboard_list[0][3], "detail": keyboard_list[0][4], "alt_name": keyboard_list[0][5]}}} + else: + cursor.execute("SELECT * FROM keyboard_list ORDER BY keyboard_number") + keyboard_list = cursor.fetchall() + keyboard_list_base = {} + for i in keyboard_list: + if i[0] == 0: + pass + else: + keyboard_list_base[i[0]] = {"keyboard_number": i[0], "using_member_id": i[1], "device_instance_path": i[2], "device_name": i[3], "detail": i[4], "alt_name": i[5]} + + return {"result": 0, "about": "ok", "output_dict": keyboard_list_base} + + except Exception as error: + self.log(title=f"[ERROR] キーボードリストの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_mouse_list(self, **kwargs): + try: + cursor = self.db.cursor() + + if "mouse_number" in kwargs: + mouse_number = int(kwargs["mouse_number"]) + cursor.execute("SELECT * FROM mouse_list WHERE mouse_number = %s", (mouse_number,)) + mouse_list = cursor.fetchall() + + return {"result": 0, "about": "ok", "output_dict": {mouse_number: {"mouse_number": mouse_list[0][0], "using_member_id": mouse_list[0][1], "device_instance_path": mouse_list[0][2], "device_name": mouse_list[0][3], "detail": mouse_list[0][4], "alt_name": mouse_list[0][5]}}} + else: + cursor.execute("SELECT * FROM mouse_list ORDER BY mouse_number") + mouse_list = cursor.fetchall() + mouse_list_base = {} + for i in mouse_list: + if i[0] == 0: + pass + else: + mouse_list_base[i[0]] = {"mouse_number": i[0], "using_member_id": i[1], "device_instance_path": i[2], "device_name": i[3], "detail": i[4], "alt_name": i[5]} + + return {"result": 0, "about": "ok", "output_dict": mouse_list_base} + + except Exception as error: + self.log(title=f"[ERROR] マウスリストの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def set_pc_nickname(self, **kwargs): + try: + cursor = self.db.cursor() + + if 'pc_number' in kwargs and 'alt_name' in kwargs: + pc_number = int(kwargs["pc_number"]) + alt_name = kwargs["alt_name"] + cursor.execute("UPDATE pc_list SET alt_name = %s WHERE pc_number = %s", (alt_name, pc_number)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "syntax_error"} + + except Exception as error: + self.log(title=f"[ERROR] PCのニックネームの設定中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def pc_unregister(self, **kwargs): + try: + cursor = self.db.cursor() + + if 'pc_number' in kwargs: + pc_number = int(kwargs["pc_number"]) + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_list = cursor.fetchall() + if pc_list: + cursor.execute("UPDATE pc_list SET using_member_id = NULL, password_hash = NULL, pc_uuid = NULL, pc_token = NULL, master_password = NULL, detail = NULL, alt_name = NULL WHERE pc_number = %s", (pc_number,)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "not_exists"} + else: + return {"result": 1, "about": "syntax_error"} + + except Exception as error: + self.log(title=f"[ERROR] PCの登録解除中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + +class ReasonModal(discord.ui.Modal): + def __init__(self, title: str, pc_number: str, keyboard_number: str, mouse_number: str, timeout=15) -> None: + super().__init__(title=title, timeout=timeout) + self.reason_input_form = discord.ui.TextInput(label="使用目的を入力してください", style=discord.TextStyle.short, custom_id=f"register_{pc_number}_{keyboard_number}_{mouse_number}") + self.add_item(self.reason_input_form) + + async def on_submit(self, interaction: discord.Interaction) -> None: + custom_id = interaction.data["components"][0]["components"][0]["custom_id"] + custom_id_split = custom_id.split("_") + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "0": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "0": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + register = dislocker.register(discord_user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=self.reason_input_form.value) + + if register["about"] == "ok": + await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["output_dict"]["password"]}\n## PC番号 | {pc_number}\n## キーボード番号 | {keyboard_number_show}\n## マウス番号 | {mouse_number_show}\n## 使用目的 | {self.reason_input_form.value}", ephemeral=True) + await send_log(mode="use", pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, reason=self.reason_input_form.value, discord_user_id=interaction.user.id) + dislocker.log(title=f"[INFO] PC番号{pc_number} の使用が開始されました。", message=f"名前 | {register["output_dict"]["name"]}, 使用目的 | {self.reason_input_form.value}", flag=0) + elif register["about"] == "pc_already_in_use_by_you": + pc_usage_history = register["pc_usage_history"] + if pc_usage_history["keyboard_number"] == None: + keyboard_number_show = "未認証" + elif pc_usage_history["keyboard_number"] == 0: + keyboard_number_show = "自前" + else: + keyboard_number_show = str(pc_usage_history["keyboard_number"]) + + if pc_usage_history["mouse_number"] == None: + mouse_number_show = "未認証" + elif pc_usage_history["mouse_number"] == 0: + mouse_number_show = "自前" + else: + mouse_number_show = str(pc_usage_history["mouse_number"]) + + await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}", ephemeral=True) + #await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}\n# 使用目的 | {pc_usage_history["use_detail"]}", ephemeral=True) + + elif register["about"] == "pc_already_in_use_by_other": + await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "keyboard_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのキーボードは他のメンバーによって使用されています。\n別のキーボードのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "mouse_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのマウスは他のメンバーによって使用されています。\n別のマウスのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "user_data_not_found": + await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) + else: + await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + class Monitor(): def __init__(self, **kwargs) -> None: @@ -705,7 +996,6 @@ class Monitor(): search_thread = threading.Thread(target=self.search) search_thread.start() - def search(self): try: time.sleep(self.init_wait_time) @@ -716,128 +1006,699 @@ class Monitor(): current_datetime = datetime.now() fstop_time = self.fstop_time if current_datetime.time().strftime("%H:%M:%S") == fstop_time: + dislocker.log(title=f"[INFO] 定期のPCの使用停止処理を開始します。", flag=0) for i in dislocker.pc_list: - stop = bot.force_stop(pc_number=i, bot_about="使用停止忘れによるBotによる強制停止。") + stop = dislocker.force_stop(pc_number=i, bot_about="使用停止忘れによるBotによる強制停止。") result = {"result": "FSTOP"} + dislocker.log(title=f"[SUCCESS] 定期のPCの使用停止処理は完了しました。", flag=0) else: if pc_list: - if len(pc_list) == 1: - user_id = pc_list[0][1] - cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s AND end_use_time IS NULL ORDER BY id DESC LIMIT 1", (user_id,)) + for i in pc_list: + member_id = i[1] + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s AND end_use_time IS NULL ORDER BY id DESC LIMIT 1", (member_id,)) pc_usage = cursor.fetchall() - print(pc_usage) - start_time = pc_usage[0][4] - print(start_time) - print(type(start_time)) + start_time = pc_usage[0][5] time_difference = current_datetime - start_time - print(current_datetime, start_time) - print(time_difference.seconds, timedelta(seconds=self.allowable_time).seconds) + dislocker.log(title=f"[INFO] 現在確認されているパスワード未使用のユーザー", message=f"レコード | {str(pc_usage)}, 経過時間(Sec) | {time_difference.seconds}/{timedelta(seconds=self.allowable_time).seconds}", flag=0) if time_difference.seconds >= timedelta(seconds=self.allowable_time).seconds: - cursor.execute("SELECT * FROM club_member WHERE id = %s", (user_id,)) + cursor.execute("SELECT * FROM club_member WHERE member_id = %s", (member_id,)) user_info = cursor.fetchall() - stop = bot.stop(user_id=user_info[0][3], bot_about="パスワードのタイムアウトでBotによる強制停止。") - - bot.timeout_notify(pc_number=pc_list[0][0], discord_display_name=user_info[0][1]) + stop = dislocker.stop(discord_user_id=user_info[0][3], bot_about="タイムアウトでBotによる強制停止。") + #discord_user_id = dislocker.get_discord_user_id(member_id=member_id)["discord_user_id"] + #asyncio.run_coroutine_threadsafe(send_log(mode="timeout", pc_number=i[0], discord_user_id=discord_user_id)) + dislocker.log(title=f"[INFO] パスワードのタイムアウト時間に達したため、強制停止されました。", flag=0) result = {"result": "STOP", "details": str(pc_usage)} else: result = {"result": "BUT SAFE", "details": str(pc_usage)} - - - elif len(pc_list) >= 2: - for i in pc_list: - print(i) - user_id = i[1] - cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s AND end_use_time IS NULL ORDER BY id DESC LIMIT 1", (user_id,)) - pc_usage = cursor.fetchall() - print(pc_usage) - start_time = pc_usage[0][4] - print(start_time) - print(type(start_time)) - time_difference = current_datetime - start_time - print(time_difference.seconds, timedelta(seconds=self.allowable_time).seconds) - if time_difference.seconds >= timedelta(seconds=self.allowable_time).seconds: - cursor.execute("SELECT * FROM club_member WHERE id = %s", (user_id,)) - user_info = cursor.fetchall() - stop = bot.stop(user_id=user_info[0][3], bot_about="タイムアウトでBotによる強制停止。") - - bot.timeout_notify(pc_number=i[0], discord_display_name=user_info[0][1]) - result = {"result": "STOP", "details": str(pc_usage)} - else: - result = {"result": "BUT SAFE", "details": str(pc_usage)} - - else: - result = {"result": "NONE"} else: result = {"result": "NONE"} if result["result"] == "NONE": pass else: - print(current_datetime) - print(result["result"]) + pass time.sleep(self.search_frequency) except Exception as error: - print("自動停止処理中にエラーが発生しました。\nエラー内容") - print(str(error.__class__.__name__)) - print(str(error.args)) - print(str(error)) + dislocker.log(title=f"[ERROR] 自動停止処理中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) result = {"result": "error"} dislocker.db.rollback() finally: - cursor.close() - print(result["result"]) + if cursor: + cursor.close() return result + + +dislocker = DL() + +intents = discord.Intents.default() +intents.message_content = True + +client = discord.Client(intents=intents) +tree = discord.app_commands.CommandTree(client) + +async def send_log(**kwargs): + try: + pc_number = str(kwargs.get("pc_number")) + discord_user_id = int(kwargs.get("discord_user_id")) + mode = str(kwargs.get("mode")) + + if mode == "use": + keyboard_number = int(kwargs.get("keyboard_number")) + mouse_number = int(kwargs.get("mouse_number")) + reason = str(kwargs.get("reason")) + + if keyboard_number == 0: + keyboard_number_show = "自前" + else: + keyboard_number_show = str(keyboard_number) + + if mouse_number == 0: + mouse_number_show = "自前" + else: + mouse_number_show = str(mouse_number) + + + log_embed = discord.Embed(title=f":video_game: PC {pc_number} 番 | 使用開始通知", description=f"<@{discord_user_id}> さんはPCの使用を開始しました。", color=0x1343EB) + log_embed.add_field(name="PC番号", value=pc_number) + log_embed.add_field(name="キーボード番号", value=keyboard_number_show) + log_embed.add_field(name="マウス番号", value=mouse_number_show) + log_embed.add_field(name="使用目的", value=reason) + + elif mode == "stop": + log_embed = discord.Embed(title=f":stop_button: PC {pc_number} 番 | 使用終了通知", description=f"<@{discord_user_id}> さんはPCの使用を終了しました。", color=0xE512EB) - - -class Reason(Modal): - def __init__(self, title: str, pc_number: str, device_number: str, timeout=15) -> None: - super().__init__(title=title, timeout=timeout) - print(pc_number) - print(device_number) - self.reason_input_form = TextInput(label="使用目的を入力してください", style=TextStyle.short, custom_id=f"register_{pc_number}_{device_number}") - self.add_item(self.reason_input_form) - - async def on_submit(self, interaction: Interaction) -> None: - custom_id = interaction.data["components"][0]["components"][0]["custom_id"] - print(custom_id) - custom_id_split = custom_id.split("_") - pc_number = custom_id_split[1] - device_number = custom_id_split[2] + elif mode == "timeout": + log_embed = discord.Embed(title=f":alarm_clock: PC {pc_number} 番 | タイムアウト通知", description=f"<@{discord_user_id}> さんが指定時間内にPCを使用しなかったため、停止されました。", color=0xE512EB) - if device_number == "own": - device_number = 0 + elif mode == "userreg": + log_embed = discord.Embed(title=f":bust_in_silhouette: ユーザー登録通知", description=f"<@{discord_user_id}> さんがユーザーとして登録されました。", color=0x1343EB) + + elif mode == "fstop": + reason = str(kwargs.get("reason")) + log_embed = discord.Embed(title=f":stop_button: PC {pc_number} 番 | 強制停止通知", description=f"<@{discord_user_id}> さんによってPCの使用は停止されました。", color=0xE512EB) + log_embed.add_field(name="理由", value=reason) + + elif mode == "pcnickname": + alt_name = str(kwargs.get("alt_name")) + log_embed = discord.Embed(title=f":pencil: PC {pc_number} 番 | PCのニックネーム変更通知", description=f"<@{discord_user_id}> さんによってPCのニックネームが変更されました。\nボタンに変更を適用する場合は、再度 /init コマンドでボタンを送信して下さい。\n古いボタンを削除することをお忘れなく!", color=0x1343EB) + log_embed.add_field(name="ニックネーム", value=alt_name) + + elif mode == "pcunreg": + alt_name = str(kwargs.get("alt_name")) + if alt_name == None: + log_embed = discord.Embed(title=f":x: PC {pc_number} 番 | PCの登録解除通知", description=f"<@{discord_user_id}> さんによってPCの登録が解除されました。", color=0xE512EB) + else: + log_embed = discord.Embed(title=f":x: PC {pc_number} 番 | PCの登録解除通知", description=f"<@{discord_user_id}> さんによってPCの登録が解除されました。", color=0xE512EB) + log_embed.add_field(name="ニックネーム", value=alt_name) + + await client.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(embed=log_embed) + + return {"result": 0, "about": "ok"} + + except Exception as error: + dislocker.log(title=f"[ERROR] ログ送信中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + +@client.event +async def on_ready(): + dislocker.log(title=f"[SUCCESS] DiscordのBotが起動しました。", message=f"{client.user.name} としてログインしています。", flag=1) + await tree.sync() + dislocker_activity = discord.Activity( + name=dislocker.server_config["bot"]["activity"]["name"], + type=discord.ActivityType.competing, + details=dislocker.server_config["bot"]["activity"]["details"], + state=dislocker.server_config["bot"]["activity"]["state"] + ) + await client.change_presence(activity=dislocker_activity) + +@client.event +async def on_message(message): + if message.author.bot: + pass + + elif isinstance(message.channel, discord.DMChannel): + if message.author.id in dislocker.server_config["bot"]["admin_user_id"]: + msg_split = message.content.split() + + if msg_split[0] == "/pcreg": + max_count = 1 + if len(msg_split) == 2: + if msg_split[1].isdecimal(): + max_count = int(msg_split[1]) + + pc_onetime_password_gen = dislocker.pc_onetime_gen(max_count=max_count) + + if pc_onetime_password_gen["result"] == 0: + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"PC登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + elif pc_onetime_password_gen["result"] == 1: + if pc_onetime_password_gen["about"] == "already_exists": + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_onetime_password_gen['output_dict']['error_class_name']}", value=f"{pc_onetime_password_gen['output_dict']['error_args']}") + + await message.channel.send(embed=result_embed) + + elif msg_split[0] == "/devreg": + max_count = 1 + if len(msg_split) == 2: + if msg_split[1].isdecimal(): + max_count = int(msg_split[1]) + + device_onetime_password_gen = dislocker.device_onetime_gen(max_count=max_count) + + if device_onetime_password_gen["result"] == 0: + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"デバイス登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + elif device_onetime_password_gen["result"] == 1: + if device_onetime_password_gen["about"] == "already_exists": + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{device_onetime_password_gen['output_dict']['error_class_name']}", value=f"{device_onetime_password_gen['output_dict']['error_args']}") + + await message.channel.send(embed=result_embed) + + else: + result_embed = discord.Embed(title=":x: 警告", description=f'DMでの操作はサポートされていません。', color=0xC91111) + await message.channel.send(embed=result_embed) else: - device_number = custom_id_split[2] - - register = bot.register(user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, device_number=device_number, detail=self.reason_input_form.value) - print(register["result"]) + pass - if register["result"] == "ok": - await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["password"]}\n## PC番号 | {pc_number}\n## デバイス番号 | {device_number}\n## 使用目的 | {self.reason_input_form.value}", ephemeral=True) - await bot.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["name"]} さんがPC {pc_number} の使用を開始しました。') - elif register["result"] == "pc_already_in_use_by_you": - await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {register["pc_number"]}\n# デバイス番号 | {register["device_number"]}\n# 使用開始時刻 | {register["start_time"]}\n# 使用目的 | {register["detail"]}", ephemeral=True) - elif register["result"] == "pc_already_in_use_by_other": +@client.event +async def on_interaction(interaction: discord.Interaction): + try: + if interaction.data["component_type"] == 2: + await on_button(interaction) + except KeyError: + pass + +async def on_button(interaction: discord.Interaction): + custom_id = interaction.data["custom_id"] + custom_id_split = custom_id.split("_") + dislocker.log(title=f"[INFO] ボタンが押されました。", message=f"custom_id | {custom_id}, DiscordユーザーID | {interaction.user.id}", flag=0) + + if custom_id_split[0] == "pcregister": + keyboard_register_view = discord.ui.View(timeout=15) + pc_number = custom_id_split[1] + keyboard_list = dislocker.get_keyboard_list() + + for i in keyboard_list["output_dict"].keys(): + current_keyboard_list = keyboard_list['output_dict'][i] + if current_keyboard_list['alt_name'] == None: + keyboard_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_keyboard_list['keyboard_number'])} 番", custom_id=f"keyboardregister_{str(pc_number)}_{str(current_keyboard_list['keyboard_number'])}") + else: + keyboard_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_keyboard_list['keyboard_number'])} 番 | ({current_keyboard_list['alt_name']})", custom_id=f"keyboardregister_{str(pc_number)}_{str(current_keyboard_list['keyboard_number'])}") + keyboard_register_view.add_item(keyboard_register_button) + + keyboard_not_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="キーボードは自前", custom_id=f"keyboardregister_{str(pc_number)}_0") + keyboard_register_view.add_item(keyboard_not_register_button) + + await interaction.response.send_message(f"# :keyboard: キーボードのデバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=keyboard_register_view, ephemeral=True) + + elif custom_id_split[0] == "keyboardregister": + mouse_register_view = discord.ui.View(timeout=15) + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_list = dislocker.get_mouse_list() + if keyboard_number == "0": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + for i in mouse_list["output_dict"].keys(): + current_mouse_list = mouse_list['output_dict'][i] + if current_mouse_list['alt_name'] == None: + mouse_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_mouse_list['mouse_number'])} 番", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_{str(current_mouse_list['mouse_number'])}") + else: + mouse_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_mouse_list['mouse_number'])} 番 | ({current_mouse_list['alt_name']})", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_{str(current_mouse_list['mouse_number'])}") + mouse_register_view.add_item(mouse_register_button) + + mouse_not_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="マウスは自前", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_0") + mouse_register_view.add_item(mouse_not_register_button) + + await interaction.response.send_message(f"# :mouse_three_button: マウスのデバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}\n# キーボード番号 | {str(keyboard_number_show)}", view=mouse_register_view, ephemeral=True) + + elif custom_id_split[0] == "mouseregister": + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "0": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "0": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + reason_register_view = discord.ui.View(timeout=15) + for i in dislocker.preset_games: + reason_quick_button = reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"quickreasonregister_{str(pc_number)}_{str(keyboard_number)}_{str(mouse_number)}_{str(i)}") + reason_register_view.add_item(reason_quick_button) + reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(keyboard_number)}_{str(mouse_number)}") + reason_register_view.add_item(reason_button) + + await interaction.response.send_message(f"# :regional_indicator_q: 使用目的を書いてください!\n>>> # PC番号 | {str(pc_number)}\n# キーボード番号 | {str(keyboard_number_show)}\n# マウス番号 | {str(mouse_number_show)}", view=reason_register_view, ephemeral=True) + + elif custom_id_split[0] == "quickreasonregister": + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "0": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "0": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + reason = custom_id_split[4] + + register = dislocker.register(discord_user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=reason) + if register["about"] == "ok": + await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["output_dict"]["password"]}\n## PC番号 | {pc_number}\n## キーボード番号 | {str(keyboard_number_show)}\n## マウス番号 | {str(mouse_number_show)}\n## 使用目的 | {reason}", ephemeral=True) + await send_log(mode="use", pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, reason=reason, discord_user_id=interaction.user.id) + dislocker.log(title=f"[INFO] PC番号{pc_number} の使用が開始されました。", message=f"名前 | {register["output_dict"]["name"]}, 使用目的 | {reason}", flag=0) + elif register["about"] == "pc_already_in_use_by_you": + pc_usage_history = register["pc_usage_history"] + if pc_usage_history["keyboard_number"] == None: + keyboard_number_show = "未認証" + elif pc_usage_history["keyboard_number"] == 0: + keyboard_number_show = "自前" + else: + keyboard_number_show = str(pc_usage_history["keyboard_number"]) + + if pc_usage_history["mouse_number"] == None: + mouse_number_show = "未認証" + elif pc_usage_history["mouse_number"] == 0: + mouse_number_show = "自前" + else: + mouse_number_show = str(pc_usage_history["mouse_number"]) + await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}", ephemeral=True) + #await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}\n# 使用目的 | {pc_usage_history["use_detail"]}", ephemeral=True) + elif register["about"] == "pc_already_in_use_by_other": await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True) - elif register["result"] == "user_data_not_found": + elif register["about"] == "keyboard_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのキーボードは他のメンバーによって使用されています。\n別のキーボードのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "mouse_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのマウスは他のメンバーによって使用されています。\n別のマウスのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "user_data_not_found": await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) else: await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + elif custom_id_split[0] == "reasonregister": + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "0": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "0": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + reason_input_form = ReasonModal(title="Dislocker | 登録", pc_number=str(pc_number), keyboard_number=str(keyboard_number), mouse_number=str(mouse_number)) + await interaction.response.send_modal(reason_input_form) + + elif custom_id_split[0] == "stop": + pc_stop = dislocker.stop(discord_user_id=interaction.user.id) + stop_view = discord.ui.View(timeout=15) + if pc_stop["about"] == "unused": + await interaction.response.send_message("# :shaking_face: 使用されていないようです...", ephemeral=True) + elif pc_stop["about"] == "user_data_not_found": + await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) + elif pc_stop["about"] == "ok": + await interaction.response.send_message(f":white_check_mark: PC番号 {pc_stop["output_dict"]["pc_number"]} の使用が終了されました。", ephemeral=True) + await send_log(mode="stop", pc_number=pc_stop['output_dict']['pc_number'], discord_user_id=interaction.user.id) + else: + await interaction.response.send_message("# :skull_crossbones: 停止できませんでした。\n内部エラーが発生しています。", ephemeral=True) + + elif custom_id_split[0] == "user" and custom_id_split[1] == "register": + user_register = dislocker.user_register(name=interaction.user.display_name, discord_user_name=interaction.user.name, discord_user_id=interaction.user.id) + if user_register["about"] == "ok": + await interaction.response.send_message(f"# :white_check_mark: ユーザー情報が登録されました。\n>>> ユーザー名:{interaction.user.display_name}", ephemeral=True) + await send_log(mode="userreg", discord_user_id=interaction.user.id) + elif user_register["about"] == "already_exists": + await interaction.response.send_message("# :no_entry: 登録できませんでした。\nもう登録されている可能性があります。", ephemeral=True) + else: + await interaction.response.send_message("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) -dislocker = DL() +#使用者側のスラッシュコマンド +@tree.command(name="use", description="パソコンの使用登録をします。通常はこのコマンドを使用する必要はありません。") +async def use(interaction: discord.Interaction, pc_number: int, keyboard_number: int, mouse_number: int, reason: str): + register = dislocker.register(discord_user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=reason) + if register["result"] == 0: + await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["output_dict"]["password"]}\n## PC番号 | {pc_number}\n## 使用目的 | {reason}", ephemeral=True) + dislocker.log(title=f"[INFO] PC番号{pc_number} の使用が開始されました。", message=f"名前 | {register["output_dict"]["name"]}, 使用目的 | {reason}", flag=0) + await send_log(mode="use", pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, reason=reason, discord_user_id=interaction.user.id) + elif register["result"] == 1: + if register["about"] == "pc_already_in_use_by_other": + await interaction.response.send_message(":x: 他の方がそのPCを使用中です。", ephemeral=True) + elif register["about"] == "pc_already_in_use_by_you": + await interaction.response.send_message(f":x: あなたは既にPC {register['pc_usage_history']['pc_number']} を使用中です。\n>>> ## PC番号 | {register['pc_usage_history']['pc_number']}\n## 使用目的 | {register['pc_usage_history']['use_detail']}", ephemeral=True) + elif register["about"] == "keyboard_already_in_use": + await interaction.response.send_message(":x: キーボードは既に使用中です。", ephemeral=True) + elif register["about"] == "mouse_already_in_use": + await interaction.response.send_message(":x: マウスは既に使用中です。", ephemeral=True) + elif register["about"] == "user_data_not_found": + await interaction.response.send_message(":x: ユーザーデータが見つかりませんでした。", ephemeral=True) + elif register["about"] == "error": + await interaction.response.send_message(":x: 内部エラーが発生しました。\nサーバーでエラーが発生しています。管理者に問い合わせてください。", ephemeral=True) + +@tree.command(name="stop", description="パソコンの使用を終了します。通常はこのコマンドを使用する必要はありません。") +async def stop(interaction: discord.Interaction): + pc_stop = dislocker.stop(discord_user_id=interaction.user.id) + if pc_stop["result"] == 0: + await interaction.response.send_message(f":white_check_mark: 使用が終了されました。\n>>> ## PC番号 | {pc_stop['output_dict']['pc_number']}", ephemeral=True) + result_embed = discord.Embed(title=":white_check_mark: 使用停止処理は完了しました。", description=f'PC番号 {pc_stop['output_dict']['pc_number']} 番の使用停止処理が完了しました。', color=0x56FF01) + dislocker.log(title=f"[INFO] PC番号{pc_stop['output_dict']['pc_number']} の使用が終了されました。", message=f"名前 | {pc_stop['output_dict']['name']}", flag=0) + await send_log(mode="stop", pc_number=pc_stop['output_dict']['pc_number'], discord_user_id=interaction.user.id) + + elif pc_stop["result"] == 1: + if pc_stop["about"] == "unused": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'あなたはPCを使用されていないようです...', color=0xC91111) + + elif pc_stop["about"] == "user_data_not_found": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'Dislockerのユーザーとして登録されていないようです。\n登録を行ってから、またお試しください。', color=0xC91111) + + elif pc_stop["about"] == "error": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_stop['output_dict']['error_class_name']}", value=f"{pc_stop['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +#管理者側のスラッシュコマンド +@tree.command(name="userreg", description="ユーザーを登録します。") +@discord.app_commands.default_permissions(administrator=True) +async def userreg(interaction: discord.Interaction, discord_user_id: str, discord_user_name: str, name: str): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + user_register = dislocker.user_register(discord_user_id=discord_user_id, discord_user_name=discord_user_name, name=name) + if user_register["result"] == 0: + result_embed = discord.Embed(title=":white_check_mark: ユーザー登録が完了しました。", description=f'続いて、PCの使用登録を行いましょう!', color=0x56FF01) + dislocker.log(title=f"[INFO] ユーザーを登録しました。", message=f"名前 | {name}, Discordユーザー名 | {discord_user_name}, DiscordユーザーID | {discord_user_id}", flag=0) + await send_log(mode="userreg", discord_user_id=discord_user_id) + + elif user_register["result"] == 1: + if user_register["about"] == "already_exists": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'既に登録されているユーザーです。', color=0xC91111) + + elif user_register["about"] == "error": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{user_register['output_dict']['error_class_name']}", value=f"{user_register['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcreg", description="PCをDislockerに登録するためのワンタイムパスワードを発行します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcreg(interaction: discord.Interaction, how_much: int = 1): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + max_count = how_much + + pc_onetime_password_gen = dislocker.pc_onetime_gen(max_count=max_count) + + if pc_onetime_password_gen["result"] == 0: + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"PC登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + elif pc_onetime_password_gen["result"] == 1: + if pc_onetime_password_gen["about"] == "already_exists": + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_onetime_password_gen['output_dict']['error_class_name']}", value=f"{pc_onetime_password_gen['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="devicereg", description="デバイスをDislockerに登録するためのワンタイムパスワードを発行します。") +@discord.app_commands.default_permissions(administrator=True) +async def devicereg(interaction: discord.Interaction, how_much: int): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + max_count = how_much + + device_onetime_password_gen = dislocker.device_onetime_gen(max_count=max_count) + + if device_onetime_password_gen["result"] == 0: + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"デバイス登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + elif device_onetime_password_gen["result"] == 1: + if device_onetime_password_gen["about"] == "already_exists": + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{device_onetime_password_gen['output_dict']['error_class_name']}", value=f"{device_onetime_password_gen['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + + +@tree.command(name="fstop", description="PCの使用登録を強制的に終了します。") +@discord.app_commands.default_permissions(administrator=True) +async def fstop(interaction: discord.Interaction, pc_number: int, reason: str): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + force_stop = dislocker.force_stop(pc_number=pc_number, bot_about=reason) + if force_stop["result"] == 0: + result_embed = discord.Embed(title=":white_check_mark: 処理が完了しました。", description=f'PC番号 {str(pc_number)} 番の使用登録は抹消されました。', color=0x56FF01) + dislocker.log(title=f"[INFO] PC {pc_number} の使用を強制終了しました。", message=f"理由 | {reason}", flag=0) + await send_log(mode="fstop", pc_number=pc_number, discord_user_id=interaction.user.id, reason=reason) + elif force_stop["result"] == 1: + if force_stop["about"] == "not_used": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'指定されたPCは使用されていないようです...', color=0xC91111) + + elif force_stop["about"] == "bot_about_not_found": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'強制停止する理由を入力してください。', color=0xC91111) + + elif force_stop["about"] == "error": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{force_stop['output_dict']['error_class_name']}", value=f"{force_stop['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="report", description="PCの使用履歴をエクスポートします。") +@discord.app_commands.default_permissions(administrator=True) +async def report(interaction: discord.Interaction): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + report_export = dislocker.report_export() + if report_export["result"] == 0: + await interaction.response.send_message(f":white_check_mark: 使用履歴のレポートです。", file=discord.File(report_export["file_path"]), ephemeral=True) + dislocker.log(title=f"[INFO] PCの使用履歴をエクスポートしました。", message=f"ファイルパス | {report_export['file_path']}", flag=0) + elif report_export["result"] == 1: + if report_export["about"] == "error": + await interaction.response.send_message(":x: 内部エラーが発生しました。\nサーバーでエラーが発生しています。管理者に問い合わせてください。", ephemeral=True) + +@tree.command(name="init", description="操作チャンネルにボタン一式を送信します。") +@discord.app_commands.default_permissions(administrator=True) +async def button_init(interaction: discord.Interaction, text_channel: discord.TextChannel): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_list = dislocker.get_pc_list() + + user_register_button_view = discord.ui.View(timeout=None) + user_register_button = discord.ui.Button(style=discord.ButtonStyle.green, label="ユーザー登録", custom_id="user_register") + user_register_button_view.add_item(user_register_button) + + await client.get_channel(text_channel.id).send(f'# :index_pointing_at_the_viewer: ユーザー登録はお済ですか?', view=user_register_button_view) + + stop_button_view = discord.ui.View(timeout=None) + stop_button = discord.ui.Button(style=discord.ButtonStyle.danger, label="PCの使用を停止", custom_id="stop") + stop_button_view.add_item(stop_button) + + await client.get_channel(text_channel.id).send(f'# :index_pointing_at_the_viewer: 使用を停止しますか?', view=stop_button_view) + + pc_button_view = discord.ui.View(timeout=None) + for i in pc_list["output_dict"].keys(): + current_pc_list = pc_list['output_dict'][i] + if current_pc_list['pc_token'] == None: + pass + else: + if current_pc_list['alt_name'] == None: + pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_pc_list['pc_number'])} 番", custom_id=f"pcregister_{str(current_pc_list['pc_number'])}") + else: + pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_pc_list['pc_number'])} 番 | ({current_pc_list['alt_name']})", custom_id=f"pcregister_{str(current_pc_list['pc_number'])}") + + pc_button_view.add_item(pc_register_button) + + await client.get_channel(text_channel.id).send(f'# :index_pointing_at_the_viewer: 使いたいPCの番号を選んでください!', view=pc_button_view) + dislocker.log(title=f"[INFO] サーバーで初回処理を実行しました。", flag=0) + + result_embed = discord.Embed(title=":white_check_mark: 初回処理が完了しました。", description=f'指定したテキストチャンネルをご確認ください。', color=0x56FF01) + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="masterpass", description="PCのマスターパスワードを表示します。") +@discord.app_commands.default_permissions(administrator=True) +async def masterpass(interaction: discord.Interaction, pc_number: int): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_master_password_get = dislocker.show_pc_master_password(pc_number=pc_number) + + if pc_master_password_get["result"] == 0: + pc_master_password = pc_master_password_get["output_dict"]["pc_master_password"] + + result_embed = discord.Embed(title=":information_source: マスターパスワード", description=f"PC番号 {str(pc_number)} 番のマスターパスワードを表示します。", color=0x2286C9) + result_embed.add_field(name=f"マスターパスワード", value=f"{str(pc_master_password)}") + + else: + result_embed = discord.Embed(title=":x: 取得に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_master_password_get['output_dict']['error_class_name']}", value=f"{pc_master_password_get['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcinfo", description="PCの情報を表示します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcinfo(interaction: discord.Interaction): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_list = dislocker.get_pc_list() + + if pc_list["result"] == 0: + result_embed = discord.Embed(title=":information_source: 現在のPCリスト", description="PCリストです。", color=0x2286C9) + + for i in pc_list['output_dict'].keys(): + current_pc_list = pc_list['output_dict'][i] + if current_pc_list['pc_token'] == None: + pass + else: + if current_pc_list['alt_name'] == None: + pc_name_title = f'{current_pc_list['pc_number']} 番' + else: + pc_name_title = f'{current_pc_list['pc_number']} 番 ({current_pc_list['alt_name']})' + + if current_pc_list['using_member_id'] == None: + pc_using_value = f'未使用' + else: + discord_user_id = dislocker.get_discord_user_id(member_id=current_pc_list['using_member_id'])['discord_user_id'] + pc_using_value = f'<@{discord_user_id}> が使用中' + + result_embed.add_field(name=f'{pc_name_title}', value=f'{pc_using_value}') + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_list['output_dict']['error_class_name']}", value=f"{pc_list['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcnickname", description="PCにニックネームを設定します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcnickname(interaction: discord.Interaction, pc_number: int, nickname: str): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_nickname_set = dislocker.set_pc_nickname(pc_number=pc_number, alt_name=nickname) + if pc_nickname_set["result"] == 0: + result_embed = discord.Embed(title=":white_check_mark: 操作が完了しました。", description=f'PC番号 {str(pc_number)} のニックネームは {str(nickname)} に設定されました。', color=0x56FF01) + await send_log(mode="pcnickname", pc_number=pc_number, discord_user_id=interaction.user.id, alt_name=nickname) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。ニックネームは変更されません。', color=0xC91111) + result_embed.add_field(name=f"{pc_nickname_set['output_dict']['error_class_name']}", value=f"{pc_nickname_set['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcunreg", description="PCの登録を解除します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcunreg(interaction: discord.Interaction, pc_number:int): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_dict = dislocker.get_pc_list()['output_dict'].get(pc_number) + if pc_dict == None: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'指定されたPC番号には登録されていません。', color=0xC91111) + await interaction.response.send_message(embed=result_embed, ephemeral=True) + else: + nickname = pc_dict['alt_name'] + pc_unregister = dislocker.pc_unregister(pc_number=pc_number) + if pc_unregister["result"] == 0: + if nickname == None: + result_embed = discord.Embed(title=":white_check_mark: 操作が完了しました。", description=f'PC {str(pc_number)} 番 の登録は解除されました。', color=0x56FF01) + else: + result_embed = discord.Embed(title=":white_check_mark: 操作が完了しました。", description=f'PC {str(pc_number)} 番 | {str(nickname)}の登録は解除されました。', color=0x56FF01) + + await send_log(mode="pcunreg", pc_number=pc_number, discord_user_id=interaction.user.id, alt_name=nickname) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。登録は解除されません。', color=0xC91111) + result_embed.add_field(name=f"{pc_unregister['output_dict']['error_class_name']}", value=f"{pc_unregister['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + if dislocker.init_result == "ok": print("Botを起動します...") - intents = discord.Intents.default() - intents.message_content = True - bot = Bot(intents=intents) monitor = Monitor(search_frequency=dislocker.server_config["bot"]["monitor"]["search_frequency"], allowable_time=dislocker.server_config["bot"]["monitor"]["allowable_time"], fstop_time=dislocker.server_config["bot"]["monitor"]["fstop_time"]) monitor.start() - bot.run(dislocker.server_config['bot']['token']) + client.run(dislocker.server_config["bot"]["token"]) else: - pass \ No newline at end of file + pass diff --git a/dislocker_auth.py b/dislocker_auth.py index a16ab4d..3ae6611 100644 --- a/dislocker_auth.py +++ b/dislocker_auth.py @@ -2,9 +2,14 @@ import psycopg2 import os import json from flask import Flask, request, jsonify, render_template +import uuid +import string +import random +import hashlib config_dir_path = "./config/" server_config_path = config_dir_path + "server.json" +onetime_config_path = config_dir_path + "onetime.json" if not os.path.isfile(server_config_path): if not os.path.isdir(config_dir_path): os.mkdir(config_dir_path) @@ -40,86 +45,440 @@ class Auth(): def __init__(self, host, db, port, user, password): self.db = psycopg2.connect(f"host={host} dbname={db} port={port} user={user} password={password}") - def check(self, pc_number, password): + def token_generate(self, length): + letters = string.ascii_letters + string.digits + token = ''.join(random.choice(letters) for _ in range(length)) + return token + + def master_password_generate(self, length): + characters = string.ascii_letters + string.digits + string.punctuation + master_password = ''.join(random.choice(characters) for _ in range(length)) + return master_password + + def hash_genarate(self, source): + hashed = hashlib.sha256(source.encode()) + return hashed.hexdigest() + + def check(self, **kwargs): try: cursor = self.db.cursor() - cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s AND password_hash = %s", (pc_number, password)) - pc_info = cursor.fetchall() - if not pc_info: - return 1 + pc_number = int(kwargs["pc_number"]) + pc_uuid = str(kwargs["pc_uuid"]) + pc_token = str(kwargs["pc_token"]) + if "device_list" in kwargs: + if kwargs["device_list"] == []: + device_list = None + else: + device_list = kwargs["device_list"] else: - return 0 + device_list = None + + keyboard_number = 0 + mouse_number = 0 + + if "password_hash" in kwargs: + password_hash = str(kwargs["password_hash"]) + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s AND password_hash = %s AND pc_uuid = %s AND pc_token = %s", (pc_number, password_hash, pc_uuid, pc_token)) + pc_info = cursor.fetchall() + if pc_info: + if device_list == None: + pass + else: + for device in device_list: + cursor.execute("SELECT * FROM keyboard_list WHERE device_instance_path = %s", (device["device_instance_path"],)) + keyboard_record = cursor.fetchall() + if keyboard_record: + keyboard_number = int(keyboard_record[0][0]) + break + else: + pass + + for device in device_list: + cursor.execute("SELECT * FROM mouse_list WHERE device_instance_path = %s", (device["device_instance_path"],)) + mouse_record = cursor.fetchall() + if mouse_record: + mouse_number = int(mouse_record[0][0]) + break + else: + pass + + return {"result": 0, "about": "ok", "output_dict": {"keyboard_number": keyboard_number, "mouse_number": mouse_number}} + else: + return {"result": 1, "about": "incorrect_password"} + else: + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s AND pc_uuid = %s AND pc_token = %s", (pc_number, pc_uuid, pc_token)) + pc_info = cursor.fetchall() + if pc_info: + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "unregistered_pc"} + + except Exception as error: + print("PCの登録状況を調査中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} + finally: cursor.close() - + + def device_use_register(self, **kwargs): + try: + pc_number = int(kwargs["pc_number"]) + if kwargs["keyboard_number"] == "own": + keyboard_number = 0 + else: + keyboard_number = int(kwargs["keyboard_number"]) + + if kwargs["mouse_number"] == "own": + mouse_number = 0 + else: + mouse_number = int(kwargs["mouse_number"]) + + + cursor = self.db.cursor() + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_list_record = cursor.fetchall() + pc_using_member_id = pc_list_record[0][1] + if pc_using_member_id == None: + return {"result": 1, "about": "not_used"} + else: + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number)) + pc_usage_history_record = cursor.fetchall() + pc_usage_history_record_id = pc_usage_history_record[0][0] + + cursor.execute("UPDATE pc_usage_history SET keyboard_number = %s, mouse_number = %s WHERE id = %s", (keyboard_number, mouse_number, pc_usage_history_record_id)) + + if keyboard_number == 0: + pass + else: + cursor.execute("UPDATE keyboard_list SET using_member_id = %s WHERE keyboard_number = %s", (pc_using_member_id, keyboard_number)) + + if mouse_number == 0: + pass + else: + cursor.execute("UPDATE mouse_list SET using_member_id = %s WHERE mouse_number = %s", (pc_using_member_id, mouse_number)) + + self.db.commit() + return {"result": 0, "about": "ok"} + + except Exception as error: + print("デバイスの使用登録中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} + + def device_register(self, **kwargs): + try: + cursor = self.db.cursor() + mode = kwargs["mode"] + number = kwargs["number"] + device_instance_path = kwargs["device_instance_path"] + device_name = kwargs["device_name"] + + if mode == "keyboard": + keyboard_number = int(kwargs["number"]) + cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number = %s", (keyboard_number,)) + keyboard_record = cursor.fetchall() + if keyboard_record: + cursor.execute("UPDATE keyboard_list SET device_instance_path = %s, device_name = %s WHERE keyboard_number = %s", (device_instance_path, device_name, keyboard_number)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + cursor.execute("INSERT INTO keyboard_list (keyboard_number, device_instance_path, device_name) VALUES (%s, %s, %s)", (keyboard_number, device_instance_path, device_name)) + return {"result": 0, "about": "ok"} + elif mode == "mouse": + mouse_number = int(kwargs["number"]) + cursor.execute("SELECT * FROM mouse_list WHERE mouse_number = %s", (mouse_number,)) + mouse_record = cursor.fetchall() + if mouse_record: + cursor.execute("UPDATE mouse_list SET device_instance_path = %s, device_name = %s WHERE mouse_number = %s", (device_instance_path, device_name, mouse_number)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + cursor.execute("INSERT INTO mouse_list (mouse_number, device_instance_path, device_name) VALUES (%s, %s, %s)", (mouse_number, device_instance_path, device_name)) + return {"result": 0, "about": "ok"} + + except Exception as error: + print("停止処理中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} + def delete(self, pc_number): try: cursor = self.db.cursor() cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) self.db.commit() + return {"result": 0, "about": "ok"} + + except Exception as error: + print("パスワードの削除中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} + + finally: + cursor.close() + + def user_register_check(self, **kwargs): + try: + discord_user_id = str(kwargs["discord_user_id"]) + + cursor = self.db.cursor() + + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) + user_record = cursor.fetchall() + #ユーザーデータが見つかった場合(登録済みの場合) + if user_record: + member_id = user_record[0][0] + name = user_record[0][1] + discord_user_name = user_record[0][2] + return {"result": 0, "about": "exist", "user_info": {"member_id": member_id, "name": name, "discord_user_name": discord_user_name}} + #ユーザーデータがなかったら(未登録の場合) + else: + return {"result": 1, "about": "user_data_not_found"} + + except Exception as error: + print("ユーザーの登録状況を調査中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} + finally: cursor.close() def stop(self, **kwargs): + # bot側のfstopを基に try: - pc_number = int(kwargs["pc_number"]) + pc_number = kwargs["pc_number"] cursor = self.db.cursor() cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) pc_list_record = cursor.fetchall() - if not pc_list_record[0][1] == None: - cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_number,)) - - if not pc_list_record[0][2] == None: - cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) - - cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_list_record[0][1], pc_number)) - pc_usage_history_record = cursor.fetchall() - cursor.execute("UPDATE pc_usage_history SET end_use_time = current_timestamp WHERE id = %s", (pc_usage_history_record[0][0],)) - self.db.commit() - result = {"result": "ok"} - + pc_using_member_id = pc_list_record[0][1] + pc_password_hash = pc_list_record[0][2] + if pc_using_member_id == None: + return {"result": 1, "about": "not_used"} else: - result = {"result": "not_used"} + cursor.execute("UPDATE pc_list SET using_member_id = NULL WHERE pc_number = %s", (pc_number,)) + if pc_password_hash == None: + pass + else: + cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number)) + pc_usage_history_record = cursor.fetchall() + pc_usage_history_record_id = pc_usage_history_record[0][0] + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + if keyboard_number == None: + pass + else: + # keyboard_listの使用中ユーザーを消す + cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,)) + if mouse_number == None: + pass + else: + # mouse_listの使用中ユーザーを消す + cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE mouse_number = %s", (mouse_number,)) + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (pc_usage_history_record_id,)) + self.db.commit() + return {"result": 0, "about": "ok"} + + except Exception as error: + print("停止処理中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} - except: - result = {"result": "error"} - finally: cursor.close() - return result + def register(self, **kwargs): + try: + cursor = self.db.cursor() + pc_number = int(kwargs["pc_number"]) + pc_uuid = str(kwargs["pc_uuid"]) + cursor.execute("SELECT pc_number FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_record_number_source = cursor.fetchall() + + if pc_record_number_source == []: + pc_token = self.token_generate(36) + master_password = self.master_password_generate(16) + master_password_hash = self.hash_genarate(master_password) + cursor.execute("INSERT INTO pc_list (pc_number, pc_uuid, pc_token, master_password) VALUES (%s, %s, %s, %s)", (pc_number, pc_uuid, pc_token, master_password)) + self.db.commit() + return {"result": 0, "about": "ok", "output_dict": {"pc_token": pc_token, "master_password": master_password, "master_password_hash": master_password_hash}} + else: + cursor.execute("SELECT pc_uuid FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_record_uuid_source = cursor.fetchall() + pc_record_uuid = pc_record_uuid_source[0][0] + if pc_record_uuid == None: + pc_token = self.token_generate(36) + master_password = self.master_password_generate(16) + master_password_hash = self.hash_genarate(master_password) + cursor.execute("UPDATE pc_list SET pc_uuid = %s, pc_token = %s, master_password = %s WHERE pc_number = %s", (pc_uuid, pc_token, master_password, pc_number)) + self.db.commit() + return {"result": 0, "about": "ok", "output_dict": {"pc_token": pc_token, "master_password": master_password, "master_password_hash": master_password_hash}} + else: + return {"result": 1, "about": "exist"} + + except Exception as error: + print("PCの登録処理中にエラーが発生しました。\nエラー内容") + print(str(error.__class__.__name__)) + print(str(error.args)) + print(str(error)) + return {"result": 1, "about": "error"} + + finally: + cursor.close() app = Flask(__name__, static_folder="./resource/") auth = Auth(server_config["db"]["host"], server_config["db"]["db_name"], server_config["db"]["port"], server_config["db"]["username"], server_config["db"]["password"]) +@app.route('/register', methods=['POST']) +def register(): + pc_number = int(request.json.get('pc_number')) + pc_uuid = str(request.json.get('pc_uuid')) + onetime_password = str(request.json.get('onetime')) + + if os.path.isfile(onetime_config_path): + with open(onetime_config_path, "r") as r: + onetime_config = json.load(r) + + if onetime_password == onetime_config["onetime"]["pc_register"]["password"]: + register_result = auth.register(pc_number=pc_number, pc_uuid=pc_uuid) + if register_result["result"] == 0: + pc_token = register_result["output_dict"]["pc_token"] + master_password = register_result["output_dict"]["master_password"] + master_password_hash = register_result["output_dict"]["master_password_hash"] + onetime_config["onetime"]["pc_register"]["current_count"] += 1 + + if onetime_config["onetime"]["pc_register"]["current_count"] == onetime_config["onetime"]["pc_register"]["max_count"]: + onetime_config["onetime"]["pc_register"]["password"] = None + with open(onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return jsonify({'message': 'ok', 'pc_token': pc_token, 'master_password': master_password, 'master_password_hash': master_password_hash}), 200 + else: + with open(onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return jsonify({'message': 'ok', 'pc_token': pc_token, 'master_password': master_password, 'master_password_hash': master_password_hash}), 200 + elif register_result["result"] == 1: + if register_result["about"] == "exist": + return jsonify({'message': 'exist'}), 400 + else: + return jsonify({'message': 'damedesu'}), 500 + + else: + return jsonify({'message': 'damedesu'}), 401 + else: + return jsonify({'message': 'damedesu'}), 401 + @app.route('/verify', methods=['POST']) def verify(): pc_number = int(request.json.get('pc_number')) - password = request.json.get('password') - print(str(pc_number) + "の認証処理を開始...") + password_hash = request.json.get('password') + pc_uuid = request.json.get('pc_uuid') + pc_token = request.json.get('pc_token') + devices = request.json.get('devices') - if auth.check(pc_number, password) == 0: + print(str(pc_number) + "の認証処理を開始...") + pc_auth = auth.check(pc_number=pc_number, password_hash=password_hash, pc_uuid=pc_uuid, pc_token=pc_token, device_list=devices) + + if pc_auth["result"] == 0: auth.delete(pc_number) + auth.device_use_register(pc_number=pc_number, keyboard_number=pc_auth["output_dict"]["keyboard_number"], mouse_number=pc_auth["output_dict"]["mouse_number"]) print(str(pc_number) + "の認証処理は成功しました.") return jsonify({'message': 'ok'}), 200 - else: - print(str(pc_number) + "の認証処理は失敗しました.") - return jsonify({'message': 'damedesu'}), 401 + elif pc_auth["result"] == 1: + if pc_auth["about"] == "incorrect_password": + print(str(pc_number) + "の認証処理はパスワードが正しくないため失敗しました.") + return jsonify({'message': 'incorrect_password'}), 401 + else: + print(str(pc_number) + "の認証処理は失敗しました.") + return jsonify({'message': 'damedesu'}), 500 @app.route('/stop', methods=['POST']) def stop(): pc_number = int(request.json.get('pc_number')) + pc_uuid = str(request.json.get('pc_uuid')) + pc_token = str(request.json.get('pc_token')) print(str(pc_number) + "の使用停止処理を開始...") - pc_stop = auth.stop(pc_number=pc_number) - if pc_stop["result"] == "ok": - print(str(pc_number) + "の使用停止処理は成功しました.") - return jsonify({'message': 'ok'}), 200 + + pc_auth = auth.check(pc_number=pc_number, pc_uuid=pc_uuid, pc_token=pc_token) + + if pc_auth["result"] == 0: + pc_stop = auth.stop(pc_number=pc_number) + if pc_stop["result"] == 0: + print(str(pc_number) + "の使用停止処理は成功しました.") + return jsonify({'message': 'ok'}), 200 + else: + print(str(pc_number) + "の使用停止処理は失敗しました.") + return jsonify({'message': 'error'}), 500 else: - print(str(pc_number) + "の使用停止処理は失敗しました.") - return jsonify({'message': 'error'}), 500 + return jsonify({'message': 'damedesu'}), 401 + +@app.route('/device_register', methods=['POST']) +def device_register(): + onetime_password = str(request.json.get('onetime')) + mode = str(request.json.get('mode')) + number = int(request.json.get('number')) + device_instance_path = str(request.json.get('device_instance_path')) + device_name = str(request.json.get('device_name')) + + if os.path.isfile(onetime_config_path): + with open(onetime_config_path, "r") as r: + onetime_config = json.load(r) + + if onetime_password == onetime_config["onetime"]["device_register"]: + if mode == "keyboard": + print("キーボードの登録処理を開始...") + device_register = auth.device_register(mode="keyboard", number=number, device_instance_path=device_instance_path, device_name=device_name) + if device_register["result"] == 0: + print(f"キーボード {number} 番の登録処理は成功しました.") + onetime_config["onetime"]["device_register"]["current_count"] += 1 + + if onetime_config["onetime"]["device_register"]["current_count"] == onetime_config["onetime"]["device_register"]["max_count"]: + onetime_config["onetime"]["device_register"] = None + with open(onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return jsonify({'message': 'ok'}), 200 + else: + with open(onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return jsonify({'message': 'ok'}), 200 + else: + print(f"キーボード {number} 番の登録処理は失敗しました.") + return jsonify({'message': 'error'}), 500 + + elif mode == "mouse": + print("マウスの登録処理を開始...") + device_register = auth.device_register(mode="mouse", number=number, device_instance_path=device_instance_path, device_name=device_name) + if device_register["result"] == 0: + print(f"マウス {number} 番の登録処理は成功しました.") + onetime_config["onetime"]["device_register"]["current_count"] += 1 + + if onetime_config["onetime"]["device_register"]["current_count"] == onetime_config["onetime"]["device_register"]["max_count"]: + onetime_config["onetime"]["device_register"] = None + with open(onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return jsonify({'message': 'ok'}), 200 + else: + with open(onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return jsonify({'message': 'ok'}), 200 + else: + print(f"マウス {number} 番の登録処理は失敗しました.") + return jsonify({'message': 'error'}), 500 + else: + return jsonify({'message': 'damedesu'}), 401 - if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=False) \ No newline at end of file diff --git a/dislocker_client.py b/dislocker_client.py index da9b9e1..eb81ecf 100644 --- a/dislocker_client.py +++ b/dislocker_client.py @@ -13,14 +13,21 @@ import tkinter import threading import sys import shutil +import uuid import time - +import win32com.client +import pythoncom +from PIL import Image app_name = "Dislocker" dislocker_dir = os.path.dirname(os.path.abspath(sys.argv[0])) os.chdir(dislocker_dir) +sp_startupinfo = subprocess.STARTUPINFO() +sp_startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW +sp_startupinfo.wShowWindow = subprocess.SW_HIDE + resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource") config_dir_path = "./config/" client_config_path = config_dir_path + "client.json" @@ -29,22 +36,81 @@ if not os.path.isfile(client_config_path): os.mkdir(config_dir_path) client_config = { - "initial": 1, + "initial": True, "auth_host_url": "http://localhost", "pc_number": 1, "master_password_hash": "", - "testing": 0, - "eraser": 1 + "testing": False, + "eraser": True, + "erase_data": { + "example": { + "process_name": "example.exe", + "dir_path": "example" + } + }, + "pc_uuid": "", + "pc_token": "", + "hard_lock": False } elif os.path.isfile(client_config_path): with open(client_config_path, "r") as r: client_config = json.load(r) +def get_input_devices(): + str_computer = "." + obj_wmi_service = win32com.client.Dispatch("WbemScripting.SWbemLocator") + obj_swem_services = obj_wmi_service.ConnectServer(str_computer, "root\\cimv2") + col_items = obj_swem_services.ExecQuery("Select * from Win32_PnPEntity where PNPDeviceID like 'HID%'") + + input_devices = [] + for obj_item in col_items: + input_devices.append({ + "device_id": obj_item.DeviceID, + "PNPDeviceID": obj_item.PNPDeviceID, + "Description": obj_item.Description, + "device_name": obj_item.Name, + "Manufacturer": obj_item.Manufacturer, + "Service": obj_item.Service, + "FriendlyName": obj_item.Name, # デバイスとプリンターで表示される名前 + "device_instance_path": obj_item.DeviceID # デバイスインスタンスパス + }) + + return input_devices + +def device_register(**kwargs): + onetime = str(kwargs["onetime"]) + mode = str(kwargs["mode"]) + number = int(kwargs["number"]) + device_instance_path = str(kwargs["device_instance_path"]) + device_name = str(kwargs["device_name"]) + device_register_json = { + "number": number, + "device_instance_path": device_instance_path, + "device_name": device_name, + "mode": mode, + "onetime": onetime + } + register_url = client_config["auth_host_url"] + "/device_register" + responce = requests.post(register_url, json=device_register_json) + if responce.status_code == 200: + print("デバイスの登録に成功しました。") + return {"result": 0, "about": "ok"} + elif responce.status_code == 401: + print("認証に失敗しました。") + return {"result": 1, "about": "auth_failed"} + else: + print("内部エラーによりデバイスの登録に失敗しました。") + return {"result": 1, "about": "error"} + +def master_password_gen(): + numbers = string.digits # (1) + password = ''.join(random.choice(numbers) for _ in range(10)) # (2) + password_hash = hashlib.sha256(password.encode()).hexdigest() + result = {"password": password, "password_hash": password_hash} + return result + def init(**kwargs): - sp_startupinfo = subprocess.STARTUPINFO() - sp_startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW - sp_startupinfo.wShowWindow = subprocess.SW_HIDE task_exist = subprocess.run('tasklist /fi "IMAGENAME eq dislocker_client.exe"', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) if 'dislocker_client.exe' in task_exist.stdout: task_count = task_exist.stdout.count("dislocker_client.exe") @@ -53,18 +119,63 @@ def init(**kwargs): else: return 1 - if client_config["initial"] == 1: - master_password = master_password_gen() - msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 初回起動を検出", message=f"初回起動のようです。\nマスターパスワードを記録しておいてください。\nこれ以降二度と表示されることはないでしょう。\n\n{master_password["password"]}\n\nまた、認証先サーバーの接続先を指定してください。ロックを解除できなくなります。") - client_config["master_password_hash"] = master_password["password_hash"] - client_config["initial"] = 0 + if client_config["initial"] == True: + pc_uuid = uuid.uuid4() + client_config["pc_uuid"] = str(pc_uuid) + if "pc_number" in kwargs: client_config["pc_number"] = int(kwargs["pc_number"]) else: - client_config["pc_number"] = 1 - with open(client_config_path, "w") as w: - json.dump(client_config, w, indent=4) - return 2 + tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nPC番号が指定されていません。1個目の引数にPC番号、2個目の引数にワンタイムパスワードを指定して、もう一度お試しください。") + return 2 + + if "onetime" in kwargs: + onetime = str(kwargs["onetime"]) + else: + tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nワンタイムパスワードが指定されていません。1個目の引数にPC番号、2個目の引数にワンタイムパスワードを指定して、もう一度お試しください。") + return 2 + + if "host_url" in kwargs: + client_config["auth_host_url"] = str(kwargs["host_url"]) + else: + pass + + register_url = client_config["auth_host_url"] + "/register" + register_json = { + "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(pc_uuid), + "onetime": onetime + } + + responce = requests.post(register_url, json=register_json) + + if responce.status_code == 200: + print("PCの情報が登録されました。") + responce_json = responce.json() + pc_token = str(responce_json["pc_token"]) + master_password_hash = str(responce_json["master_password_hash"]) + master_password = str(responce_json["master_password"]) + client_config["pc_token"] = pc_token + client_config["master_password_hash"] = master_password_hash + + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 初回起動を検出", message=f"初回起動のようです。\nマスターパスワードを記録しておいてください。\nBotが起動している場合は、管理者がDiscordから確認することもできます。\n\n{master_password}\n\n") + client_config["initial"] = False + + with open(client_config_path, "w") as w: + json.dump(client_config, w, indent=4) + return 2 + + elif responce.status_code == 400: + msgbox = tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\n指定されたPC番号には既に登録されています。PCを置き換えたい場合は、Botから登録を解除してください。") + return 2 + + elif responce.status_code == 401: + msgbox = tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nワンタイムパスワードが間違っている可能性があります。") + return 2 + + elif responce.status_code == 500: + msgbox = tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nサーバーで内部エラーが発生しています。") + return 2 else: return 0 @@ -72,16 +183,26 @@ def init(**kwargs): class App(customtkinter.CTk): def __init__(self): super().__init__() - self.title(f"{app_name} | ロック中") - self.iconbitmap(default=resource_path + '\\icon\\dislocker.ico') - if client_config["testing"] == 1: + + if client_config["testing"] == True: pass else: - self.attributes('-fullscreen', True) - self.attributes('-topmost', True) self.block_taskmgr() self.block_key() + shutup_window = keyboard.press_and_release('windows + d') + self.attributes('-fullscreen', True) + self.attributes('-topmost', True) + if client_config["hard_lock"] == True: + exit_explorer = subprocess.run('taskkill /f /im explorer.exe', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) + if exit_explorer.returncode == 0: + pass + else: + signout_session = subprocess.run('shutdown /l /f /t 3', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) + error_msgbox = tkinter.messagebox.showerror(title=f"{app_name} | 初回処理のエラー", message=f"初回処理の実行にエラーが発生しました。\n自動的にサインアウトされます。") + + self.title(f"{app_name} | ロック中") + self.iconbitmap(default=resource_path + '\\icon\\dislocker.ico') self.frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') self.frame.grid(row=0, column=0, sticky='nsew') @@ -89,48 +210,13 @@ class App(customtkinter.CTk): def exit(self): self.unlock_taskmgr() + if client_config["hard_lock"] == True: + self.wake_explorer() + else: + pass + self.toast() self.destroy() - - def delete_appdata(self, **kwargs): - process_name = kwargs["process_name"] - dir_path = kwargs["dir_path"] - - if not os.path.exists(dir_path): - print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。") - return 1 - - i = 0 - i_max = 10 - result = 1 - while i != i_max: - i += 1 - try: - # プロセスの終了 - subprocess.run(['taskkill', '/f', '/t', '/im', process_name]) - print(f"{process_name} を終了しました。") - time.sleep(0.1) - # ディレクトリの削除 - shutil.rmtree(dir_path) - if os.path.isdir(dir_path): - pass - else: - print(f"{dir_path} を削除しました。") - result = 0 - i = i_max - - except subprocess.CalledProcessError as e: - print(f"プロセス終了エラー: {e}") - - except PermissionError as e: - print(f"権限エラー: {e}") - - except Exception as e: - print("エラーが発生しました。\nエラー内容:") - print(f"エラータイプ: {e.__class__.__name__}") - print(f"エラー引数: {e.args}") - print(f"エラーメッセージ: {str(e)}") - def block_key(self): block_keys = ['ctrl', 'alt', 'windows', 'shift', 'delete'] @@ -138,13 +224,17 @@ class App(customtkinter.CTk): keyboard.block_key(i) def block_taskmgr(self): - block = subprocess.run(['reg', 'add', 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System', '/v', 'DisableTaskMgr', '/t', 'REG_DWORD', '/d', '1', '/f']) + block = subprocess.run('reg add HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v DisableTaskMgr /t REG_DWORD /d 1 /f', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) print(block) def unlock_taskmgr(self): - unlock = subprocess.run(['reg', 'delete', 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System', '/v', 'DisableTaskMgr', '/f']) + unlock = subprocess.run('reg delete HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v DisableTaskMgr /f', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) print(unlock) + def wake_explorer(self): + wake_explorer = subprocess.Popen('explorer', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) + + def toast(self): success = Notification( app_id='Dislocker', @@ -162,13 +252,13 @@ class App(customtkinter.CTk): class Lock(customtkinter.CTkToplevel): def __init__(self): super().__init__() - if client_config["testing"] == 1: + if client_config["testing"] == True: self.title(f'{app_name} | PC番号 {client_config["pc_number"]} | テストモード') else: self.title(f'{app_name} | PC番号 {client_config["pc_number"]} | ロックされています') self.iconbitmap(default=resource_path + '\\icon\\dislocker.ico') - self.window_width = 600 + self.window_width = 760 self.window_height = 320 self.screen_width = self.winfo_screenwidth() self.screen_height = self.winfo_screenheight() @@ -189,32 +279,45 @@ class Lock(customtkinter.CTkToplevel): self.general_small_font = customtkinter.CTkFont(family="meiryo", size=12) self.textbox_font = customtkinter.CTkFont(family="meiryo", size=14) self.button_font = customtkinter.CTkFont(family="meiryo", size=14) + + self.cover_img = customtkinter.CTkImage(light_image=Image.open(resource_path + '\\cover\\dislocker_light.png'), dark_image=Image.open(resource_path + '\\cover\\dislocker_dark.png'), size=(160, 320)) + + self.grid_columnconfigure(0, weight=1) + self.grid_columnconfigure(1, weight=6) + + self.cover_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') + self.cover_frame.grid(row=0, column=0, padx=0, pady=0, sticky="nsew", rowspan=4) + self.cover_img_label = customtkinter.CTkLabel(self.cover_frame, image=self.cover_img, text="") + self.cover_img_label.grid(row=0, column=0, padx=0, pady=0, sticky="w") self.msg_title_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') - self.msg_title_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew") + self.msg_title_frame.grid(row=0, column=1, padx=10, pady=10, sticky="nsew") - self.icon_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text='😎', font=self.emoji_font, justify="left") - self.icon_title_1.grid(row=0, column=0, padx=10, sticky="w") + #self.icon_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text='😎', font=self.emoji_font, justify="left") + #self.icon_title_1.grid(row=0, column=0, padx=10, sticky="w") - self.msg_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text=f'ちょっと待って!! PC番号 | {client_config["pc_number"]}', font=self.title_font, justify="left") - self.msg_title_1.grid(row=0, column=1, padx=10, sticky="w") + self.msg_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text=f'ちょっと待って!! ', font=self.title_font, justify="left") + self.msg_title_1.grid(row=0, column=0, padx=10, sticky="we") + + self.pc_number_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text=f'PC番号 | {client_config["pc_number"]}', font=self.title_font, justify="right") + self.pc_number_title_1.grid(row=0, column=1, padx=10, sticky="e") self.msg_title_2 = customtkinter.CTkLabel(self.msg_title_frame, text="本当にあなたですか?", font=self.title_small_font, justify="left") - self.msg_title_2.grid(row=1, column=1, padx=10, sticky="w") + self.msg_title_2.grid(row=1, column=0, padx=10, columnspan=2, sticky="w") self.msg_subtitle_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') - self.msg_subtitle_frame.grid(row=1, column=0, padx=10, pady=10, sticky="nsew") + self.msg_subtitle_frame.grid(row=1, column=1, padx=10, pady=0, sticky="nsew") self.msg_subtitle_frame.grid_columnconfigure(0, weight=1) - self.msg_subtitle_1 = customtkinter.CTkLabel(self.msg_subtitle_frame, text='サインインするには、Discordのダイレクトメッセージに送信された\nパスワードを入力してください。', font=self.general_font, justify="left") - self.msg_subtitle_1.grid(row=0, column=0, padx=10, sticky="ew") + self.msg_subtitle_1 = customtkinter.CTkLabel(self.msg_subtitle_frame, text='サインインするには、Discordを開き、Dislockerから送信された\nパスワードを入力してください。', font=self.general_font, justify="left") + self.msg_subtitle_1.grid(row=0, column=0, padx=10, sticky="w") - self.msg_subtitle_2 = customtkinter.CTkLabel(self.msg_subtitle_frame, text='※ パスワードの有効期限は23:59までです。', font=self.general_small_font, justify="left") + self.msg_subtitle_2 = customtkinter.CTkLabel(self.msg_subtitle_frame, text='※ パスワードの有効期限は発行から5分間です。期限が切れた場合は、もう一度発行してください。', font=self.general_small_font, justify="left") self.msg_subtitle_2.grid(row=1, column=0, padx=10, sticky="w") self.input_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') - self.input_frame.grid(row=2, column=0, padx=10, pady=10, sticky="nsew") + self.input_frame.grid(row=2, column=1, padx=10, pady=0, sticky="nsew") self.input_frame.columnconfigure(0, weight=1) self.password_entry = customtkinter.CTkEntry(self.input_frame, placeholder_text='パスワード', show='*', font=self.textbox_font) @@ -222,7 +325,7 @@ class Lock(customtkinter.CTkToplevel): self.password_entry.bind("", self.auth_start_ev) self.button_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') - self.button_frame.grid(row=3, column=0, padx=10, pady=10, sticky="nsew") + self.button_frame.grid(row=3, column=1, padx=10, pady=10, sticky="nsew") self.button_frame.columnconfigure(0, weight=3) self.button_frame.columnconfigure(1, weight=1) self.button_frame.columnconfigure(2, weight=1) @@ -247,7 +350,7 @@ class Lock(customtkinter.CTkToplevel): keyboard.add_hotkey('ctrl+shift+q', self.exit) def hash_genarate(self, source): - hashed = hashlib.md5(source.encode()) + hashed = hashlib.sha256(source.encode()) return hashed.hexdigest() def auth_start(self): @@ -270,10 +373,39 @@ class Lock(customtkinter.CTkToplevel): self.signin_button.configure(state="normal", fg_color="#3c8dd0") self.signout_button.configure(state="normal", fg_color="#3c8dd0") + def get_input_devices(self): + try: + pythoncom.CoInitialize() + str_computer = "." + obj_wmi_service = win32com.client.Dispatch("WbemScripting.SWbemLocator") + obj_swem_services = obj_wmi_service.ConnectServer(str_computer, "root\\cimv2") + col_items = obj_swem_services.ExecQuery("Select * from Win32_PnPEntity where PNPDeviceID like 'HID%'") + input_devices = [] + for obj_item in col_items: + input_devices.append({ + "device_id": obj_item.DeviceID, + "PNPDeviceID": obj_item.PNPDeviceID, + "Description": obj_item.Description, + "device_name": obj_item.Name, + "Manufacturer": obj_item.Manufacturer, + "Service": obj_item.Service, + "FriendlyName": obj_item.Name, # デバイスとプリンターで表示される名前 + "device_instance_path": obj_item.DeviceID # デバイスインスタンスパス + }) + + pythoncom.CoUninitialize() + return input_devices + except pythoncom.com_error as e: + print("Error:", e) + return [] + def auth(self): self.button_disable() password = str(self.password_entry.get()) + #devices = self.get_input_devices() + devices = [] + if len(password) == 10: print("マスターパスワードで認証を試行します。") master_password_hash = self.hash_genarate(str(self.password_entry.get())) @@ -288,11 +420,13 @@ class Lock(customtkinter.CTkToplevel): self.button_enable() self.deiconify() - print("認証サーバーにアクセスします。") auth_url = client_config["auth_host_url"] + "/verify" auth_json = { "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(client_config["pc_uuid"]), + "pc_token": str(client_config["pc_token"]), + "devices": devices, "password": self.hash_genarate(str(self.password_entry.get())) } try: @@ -300,13 +434,20 @@ class Lock(customtkinter.CTkToplevel): if responce.status_code == 200: print("認証サーバー経由で認証しました。") self.exit() - else: + elif responce.status_code == 401: print("認証サーバー経由での認証に失敗しました。") self.withdraw() msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 誤ったパスワード", message=f"パスワードが間違っています!") self.msg_subtitle_1.configure(text='パスワードが間違っています! ') self.button_enable() self.deiconify() + elif responce.status_code == 500: + print("内部エラーにより認証に失敗しました。") + self.withdraw() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 内部エラー", message=f"サーバーの内部エラーにより認証に失敗しました。") + self.msg_subtitle_1.configure(text='内部エラーにより認証に失敗しました。 ') + self.button_enable() + self.deiconify() except: print("認証サーバーにアクセスできません。マスターパスワードで認証を試行します。") master_password_hash = self.hash_genarate(str(self.password_entry.get())) @@ -324,7 +465,7 @@ class Lock(customtkinter.CTkToplevel): def signout(self): app.unlock_taskmgr() self.destroy() - signout_command = subprocess.run(['shutdown', '/l', '/f']) + signout_command = subprocess.run('shutdown /l /f', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) print(signout_command) @@ -336,7 +477,15 @@ class Lock(customtkinter.CTkToplevel): msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 未実装", message=f"ヘルプページは製作途中です。\nDiscordサーバーの指示に従って、認証を進めてください。") self.deiconify() + def wakeup_shutdown_background(self): + wakeup = subprocess.Popen(f'{dislocker_dir}\\dislocker_client_shutdown.exe', startupinfo=sp_startupinfo) + def exit(self): + try: + self.wakeup_shutdown_background() + except: + pass + self.destroy() app.exit() @@ -344,7 +493,7 @@ class Lock(customtkinter.CTkToplevel): class Help(customtkinter.CTkToplevel): def __init__(self): super().__init__() - if client_config["testing"] == 1: + if client_config["testing"] == True: self.title(f'{app_name} | ヘルプ | テストモード') else: self.title(f'{app_name} | ヘルプ') @@ -385,7 +534,7 @@ class Stop(): i += 1 try: # プロセスの終了 - subprocess.run(['taskkill', '/f', '/t', '/im', process_name]) + subprocess.run(f'taskkill /f /t /im {process_name}', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) print(f"{process_name} を終了しました。") time.sleep(0.1) # ディレクトリの削除 @@ -413,43 +562,39 @@ class Stop(): def shutdown(self): - shutdown_command = subprocess.run(['shutdown', '/s', '/t', '1']) + shutdown_command = subprocess.run('shutdown /s /f /t 0', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) def stop(self): print("停止処理を実行。") - if client_config["eraser"] == 1: + if client_config["eraser"] == True: appdata_local = os.path.expandvars("%LOCALAPPDATA%") appdata_roaming = os.path.expandvars("%APPDATA%") - epic_del = app.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved") - chrome_del = app.delete_appdata(process_name="chrome.exe", dir_path=f"{appdata_local}\\Google\\Chrome\\User Data") - discord_del = app.delete_appdata(process_name="discord.exe", dir_path=f"{appdata_roaming}\\discord") - steam_del = app.delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam") - ea_del = app.delete_appdata(process_name="EADesktop.exe", dir_path=f"{appdata_local}\\Electronic Arts") - riot_del = app.delete_appdata(process_name="RiotClientServices.exe", dir_path=f"{appdata_local}\\Riot Games\\Riot Client") + epic_del = self.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved") + chrome_del = self.delete_appdata(process_name="chrome.exe", dir_path=f"{appdata_local}\\Google\\Chrome\\User Data") + discord_del = self.delete_appdata(process_name="discord.exe", dir_path=f"{appdata_roaming}\\discord") + steam_del = self.delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam") + ea_del = self.delete_appdata(process_name="EADesktop.exe", dir_path=f"{appdata_local}\\Electronic Arts") + riot_del = self.delete_appdata(process_name="RiotClientServices.exe", dir_path=f"{appdata_local}\\Riot Games\\Riot Client") else: print("削除処理をスキップ。") stop_url = client_config["auth_host_url"] + "/stop" stop_json = { - "pc_number": int(client_config["pc_number"]) + "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(client_config["pc_uuid"]), + "pc_token": str(client_config["pc_token"]) } try: responce = requests.post(stop_url, json=stop_json) if responce.status_code == 200: print("停止処理は成功しました。") + elif responce.status_code == 401: + print("認証に失敗しました。") else: print("内部エラーにより停止処理に失敗しました。") except: print("ネットワークエラーにより停止処理に失敗しました。") finally: self.shutdown() - - -def master_password_gen(): - numbers = string.digits # (1) - password = ''.join(random.choice(numbers) for _ in range(10)) # (2) - password_hash = hashlib.md5(password.encode()).hexdigest() - result = {"password": password, "password_hash": password_hash} - return result if __name__ == '__main__': @@ -458,20 +603,61 @@ if __name__ == '__main__': if args[1] == "stop": init_result = init() if init_result == 1: - print("多重起動エラー。") + print("多重起動を検出。") elif init_result == 2: pass else: stop = Stop() stop.run() - elif args[1] == "setup": - init_result = init(pc_number=args[2]) + + elif args[1] == "setup": + if len(args) == 4: + init_result = init(pc_number=args[2], onetime=args[3]) + elif len(args) == 5: + init_result = init(pc_number=args[2], onetime=args[3], host_url=args[4]) + else: + print("引数エラー。") + error_msgbox = tkinter.messagebox.showerror(title=f"{app_name} | 引数エラー", message=f"引数が多すぎるか、少なすぎます。\n引数がPC番号、ワンタイムパスワード、ホストURLの順で正しく指定されているか確認してください。") if init_result == 1: warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"すでに {app_name} は実行されています。\n正常に起動しない場合は、既に起動しているプロセスを終了してから、もう一度起動してみてください。") elif init_result == 2: pass else: pass + + elif args[1] == "deviceregister": + init_result = init() + if init_result == 1: + warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"すでに {app_name} は実行されています。\n正常に起動しない場合は、既に起動しているプロセスを終了してから、もう一度起動してみてください。") + elif init_result == 2: + pass + else: + mode = input('登録するデバイスはキーボードとマウスのどちらですか?(keyboard/mouse): ') + input_devices = get_input_devices() + + i = 0 + for device in input_devices: + print(f"{str(i + 1)} 番目 | デバイス名: {device['device_name']} \n製造元: {device['Manufacturer']} \nデバイスインスタンスパス: {device['device_instance_path']}") + print("-" * 20) + i += 1 + device_num = input('どのデバイスを登録しますか?番号で指定してください: ') + device_register_num = input('そのデバイスは何番目のデバイスとして登録しますか?番号で指定してください: ') + onetime = input('ワンタイムパスワードを入力してください: ') + device_register_result = device_register(onetime=onetime, mode=mode, number=int(device_register_num), device_instance_path=input_devices[int(device_num) - 1]["device_instance_path"], device_name=input_devices[int(device_num) - 1]["device_name"]) + if device_register_result["result"] == 0: + print("登録されました。") + elif device_register_result["result"] == 1: + if device_register_result["about"] == "auth_failed": + print("認証に失敗しました。") + else: + print("エラーが発生しました。") + + elif args[1] == "guitest": + init_result = init() + client_config["testing"] = True + app = App() + app.mainloop() + else: print("引数エラー。") else: diff --git a/dislocker_client_shutdown.py b/dislocker_client_shutdown.py new file mode 100644 index 0000000..51d841e --- /dev/null +++ b/dislocker_client_shutdown.py @@ -0,0 +1,166 @@ +import os +import json +import tkinter.messagebox +import tkinter +import subprocess +import requests +import tkinter +import sys +import time +import shutil + +app_name = "Dislocker" +dislocker_dir = os.path.dirname(os.path.abspath(sys.argv[0])) + +os.chdir(dislocker_dir) + +sp_startupinfo = subprocess.STARTUPINFO() +sp_startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW +sp_startupinfo.wShowWindow = subprocess.SW_HIDE + +resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource") +config_dir_path = "./config/" +client_config_path = config_dir_path + "client.json" +if not os.path.isfile(client_config_path): + msgbox = tkinter.messagebox.showerror(title=f"{app_name} | エラー", message=f"設定ファイルが正しく構成されていません。") + +elif os.path.isfile(client_config_path): + with open(client_config_path, "r") as r: + client_config = json.load(r) + +def init(**kwargs): + task_exist = subprocess.run('tasklist /fi "IMAGENAME eq dislocker_shutdown.exe"', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) + if 'dislocker_shutdown.exe' in task_exist.stdout: + task_count = task_exist.stdout.count("dislocker_shutdown.exe") + if task_count == 1: + pass + else: + return 1 + + if client_config["initial"] == True: + msgbox = tkinter.messagebox.showerror(title=f"{app_name} | エラー", message=f"設定ファイルが正しく構成されていません。") + return 2 + else: + return 0 + + +class App(tkinter.Tk): + def __init__(self): + super().__init__() + + if client_config["testing"] == True: + pass + else: + pass + + self.geometry("160x100") + + self.title(f"{app_name} | シャットダウンを監視") + self.iconbitmap(default=resource_path + '\\icon\\dislocker_shutdown.ico') + + self.protocol("WM_SAVE_YOURSELF", self.handler_close) + + self.frame = tkinter.Frame(self) + self.frame.grid(row=0, column=0, sticky='nsew') + + self.withdraw() + + def delete_appdata(self, **kwargs): + process_name = kwargs["process_name"] + dir_path = kwargs["dir_path"] + + if not os.path.exists(dir_path): + print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。") + return 1 + + i = 0 + i_max = 10 + result = 1 + while i != i_max: + i += 1 + try: + # プロセスの終了 + subprocess.run(f'taskkill /f /t /im {process_name}', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True) + print(f"{process_name} を終了しました。") + time.sleep(0.1) + # ディレクトリの削除 + shutil.rmtree(dir_path) + if os.path.isdir(dir_path): + pass + else: + print(f"{dir_path} を削除しました。") + result = 0 + i = i_max + + except subprocess.CalledProcessError as e: + print(f"プロセス終了エラー: {e}") + + except PermissionError as e: + print(f"権限エラー: {e}") + + except Exception as e: + print("エラーが発生しました。\nエラー内容:") + print(f"エラータイプ: {e.__class__.__name__}") + print(f"エラー引数: {e.args}") + print(f"エラーメッセージ: {str(e)}") + + def handler_close(self): + print("停止処理を実行。") + stop_url = client_config["auth_host_url"] + "/stop" + stop_json = { + "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(client_config["pc_uuid"]), + "pc_token": str(client_config["pc_token"]) + } + try: + responce = requests.post(stop_url, json=stop_json) + if responce.status_code == 200: + print("停止処理は成功しました。") + elif responce.status_code == 401: + print("認証に失敗しました。") + else: + print("内部エラーにより停止処理に失敗しました。") + except: + print("ネットワークエラーにより停止処理に失敗しました。") + + print("データ削除を実行。") + try: + if client_config["eraser"] == True: + appdata_local = os.path.expandvars("%LOCALAPPDATA%") + appdata_roaming = os.path.expandvars("%APPDATA%") + epic_del = self.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved") + chrome_del = self.delete_appdata(process_name="chrome.exe", dir_path=f"{appdata_local}\\Google\\Chrome\\User Data") + discord_del = self.delete_appdata(process_name="discord.exe", dir_path=f"{appdata_roaming}\\discord") + steam_del = self.delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam") + ea_del = self.delete_appdata(process_name="EADesktop.exe", dir_path=f"{appdata_local}\\Electronic Arts") + riot_del = self.delete_appdata(process_name="RiotClientServices.exe", dir_path=f"{appdata_local}\\Riot Games\\Riot Client") + """ + for i in client_config['erase_data'].keys(): + if i == 'example': + pass + else: + erase_process_name = client_config['erase_data'][i]['process_name'] + erase_dir_path = client_config['erase_data'][i]['dir_path'] + erase_del = self.delete_appdata(process_name=erase_process_name, dir_path=erase_dir_path) + """ + + else: + print("削除処理をスキップ。") + except: + print("データ削除に失敗しました。") + + self.destroy() + + def icon(self): + self.iconify() + + +if __name__ == '__main__': + init_result = init() + if init_result == 1: + warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"すでに {app_name} は実行されています。\n正常に起動しない場合は、既に起動しているプロセスを終了してから、もう一度起動してみてください。") + elif init_result == 2: + pass + else: + app = App() + app.mainloop() diff --git a/dislocker_client_universal.py b/dislocker_client_universal.py new file mode 100644 index 0000000..3867471 --- /dev/null +++ b/dislocker_client_universal.py @@ -0,0 +1,441 @@ +import os +import json +import tkinter.messagebox +import customtkinter +import subprocess +import requests +import hashlib +import string +import random +import tkinter +import threading +import sys +import shutil +import uuid +import time + +app_name = "Dislocker" +dislocker_dir = os.path.dirname(os.path.abspath(sys.argv[0])) + +os.chdir(dislocker_dir) + +resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource") +config_dir_path = "./config/" +client_config_path = config_dir_path + "client.json" +if not os.path.isfile(client_config_path): + if not os.path.isdir(config_dir_path): + os.mkdir(config_dir_path) + + client_config = { + "initial": 1, + "auth_host_url": "http://localhost", + "pc_number": 1, + "master_password_hash": "", + "testing": 0, + "eraser": 1, + "pc_uuid": "", + "pc_token": "" + } + +elif os.path.isfile(client_config_path): + with open(client_config_path, "r") as r: + client_config = json.load(r) + +def master_password_gen(): + numbers = string.digits # (1) + password = ''.join(random.choice(numbers) for _ in range(10)) # (2) + password_hash = hashlib.md5(password.encode()).hexdigest() + result = {"password": password, "password_hash": password_hash} + return result + +def init(**kwargs): + if client_config["initial"] == 1: + pc_uuid = uuid.uuid4() + client_config["pc_uuid"] = str(pc_uuid) + + if "pc_number" in kwargs: + client_config["pc_number"] = int(kwargs["pc_number"]) + else: + tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nPC番号が指定されていません。1個目の引数にPC番号、2個目の引数にワンタイムパスワードを指定して、もう一度お試しください。") + return 2 + + if "onetime" in kwargs: + onetime = str(kwargs["onetime"]) + else: + tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nワンタイムパスワードが指定されていません。1個目の引数にPC番号、2個目の引数にワンタイムパスワードを指定して、もう一度お試しください。") + return 2 + + register_url = client_config["auth_host_url"] + "/register" + register_json = { + "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(pc_uuid), + "onetime": onetime + } + + responce = requests.post(register_url, json=register_json) + + if responce.status_code == 200: + print("PCの情報が登録されました。") + responce_json = responce.json() + pc_token = str(responce_json["pc_token"]) + client_config["pc_token"] = pc_token + + master_password = master_password_gen() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 初回起動を検出", message=f"初回起動のようです。\nマスターパスワードを記録しておいてください。\nこれ以降二度と表示されることはないでしょう。\n\n{master_password["password"]}\n\nまた、認証先サーバーの接続先を指定してください。ロックを解除できなくなります。") + client_config["master_password_hash"] = master_password["password_hash"] + client_config["initial"] = 0 + + with open(client_config_path, "w") as w: + json.dump(client_config, w, indent=4) + return 2 + else: + msgbox = tkinter.messagebox.showerror(title=f"{app_name} | 登録時にエラー", message=f"登録時にエラーが発生しました。\nワンタイムパスワードが間違っている可能性があります。") + return 2 + else: + return 0 + + +class App(customtkinter.CTk): + def __init__(self): + super().__init__() + self.title(f"{app_name} | ロック中") + if client_config["testing"] == 1: + pass + else: + self.attributes('-fullscreen', True) + self.attributes('-topmost', True) + + self.frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') + self.frame.grid(row=0, column=0, sticky='nsew') + + lock = Lock() + + def exit(self): + self.unlock_taskmgr() + self.toast() + self.destroy() + + def handler_close(self): + pass + + +class Lock(customtkinter.CTkToplevel): + def __init__(self): + super().__init__() + if client_config["testing"] == 1: + self.title(f'{app_name} | PC番号 {client_config["pc_number"]} | テストモード') + else: + self.title(f'{app_name} | PC番号 {client_config["pc_number"]} | ロックされています') + + self.window_width = 600 + self.window_height = 320 + self.screen_width = self.winfo_screenwidth() + self.screen_height = self.winfo_screenheight() + self.center_x = int(self.screen_width/2 - self.window_width/2) + self.center_y = int(self.screen_height/2 - self.window_height/2) + self.geometry(f"{str(self.window_width)}x{str(self.window_height)}+{str(self.center_x)}+{str(self.center_y)}") + self.resizable(height=False, width=False) + self.attributes('-topmost', True) + self.grab_set() + self.lift() + self.protocol("WM_DELETE_WINDOW", self.handler_close) + + self.emoji_font = customtkinter.CTkFont(family="Noto Color Emoji", size=32) + self.title_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=32, weight="bold") + self.pc_number_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=64, weight="bold") + self.title_small_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=16) + self.general_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=18) + self.general_small_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=12) + self.textbox_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=14) + self.button_font = customtkinter.CTkFont(family="Noto Sans CJK JP", size=14) + + + self.msg_title_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') + self.msg_title_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew") + + self.icon_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text='😎', font=self.emoji_font, justify="left") + self.icon_title_1.grid(row=0, column=0, padx=10, sticky="w") + + self.msg_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text=f'ちょっと待って!! PC番号 | {client_config["pc_number"]}', font=self.title_font, justify="left") + self.msg_title_1.grid(row=0, column=1, padx=10, sticky="w") + + self.msg_title_2 = customtkinter.CTkLabel(self.msg_title_frame, text="本当にあなたですか?", font=self.title_small_font, justify="left") + self.msg_title_2.grid(row=1, column=1, padx=10, sticky="w") + + self.msg_subtitle_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') + self.msg_subtitle_frame.grid(row=1, column=0, padx=10, pady=10, sticky="nsew") + self.msg_subtitle_frame.grid_columnconfigure(0, weight=1) + + self.msg_subtitle_1 = customtkinter.CTkLabel(self.msg_subtitle_frame, text='サインインするには、Discordのダイレクトメッセージに送信された\nパスワードを入力してください。', font=self.general_font, justify="left") + self.msg_subtitle_1.grid(row=0, column=0, padx=10, sticky="ew") + + self.msg_subtitle_2 = customtkinter.CTkLabel(self.msg_subtitle_frame, text='※ パスワードの有効期限は23:59までです。', font=self.general_small_font, justify="left") + self.msg_subtitle_2.grid(row=1, column=0, padx=10, sticky="w") + + self.input_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') + self.input_frame.grid(row=2, column=0, padx=10, pady=10, sticky="nsew") + self.input_frame.columnconfigure(0, weight=1) + + self.password_entry = customtkinter.CTkEntry(self.input_frame, placeholder_text='パスワード', show='*', font=self.textbox_font) + self.password_entry.grid(row=0, column=0, padx=10, sticky="ew") + self.password_entry.bind("", self.auth_start_ev) + + self.button_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent') + self.button_frame.grid(row=3, column=0, padx=10, pady=10, sticky="nsew") + self.button_frame.columnconfigure(0, weight=3) + self.button_frame.columnconfigure(1, weight=1) + self.button_frame.columnconfigure(2, weight=1) + + self.signin_button = customtkinter.CTkButton(self.button_frame, text='サインイン', command=self.auth_start, font=self.button_font) + self.signin_button.grid(row=0, column=2, padx=10, sticky="e") + + self.signout_button = customtkinter.CTkButton(self.button_frame, text='サインアウト', command=self.signout, font=self.button_font) + self.signout_button.grid(row=0, column=1, padx=10, sticky="e") + + self.help_button = customtkinter.CTkButton(self.button_frame, text='ヘルプ', command=self.help_dummy, font=self.button_font) + self.help_button.grid(row=0, column=0, padx=10, sticky="w") + + def help_wakeup(self): + help = Help() + + def hash_genarate(self, source): + hashed = hashlib.md5(source.encode()) + return hashed.hexdigest() + + def auth_start(self): + auth_thread = threading.Thread(target=self.auth) + auth_thread.daemon = True + auth_thread.start() + + def auth_start_ev(self, event): + auth_thread = threading.Thread(target=self.auth) + auth_thread.daemon = True + auth_thread.start() + + def button_disable(self): + self.help_button.configure(state="disabled", fg_color="gray") + self.signin_button.configure(state="disabled", fg_color="gray") + self.signout_button.configure(state="disabled", fg_color="gray") + + def button_enable(self): + self.help_button.configure(state="normal", fg_color="#3c8dd0") + self.signin_button.configure(state="normal", fg_color="#3c8dd0") + self.signout_button.configure(state="normal", fg_color="#3c8dd0") + + + def auth(self): + self.button_disable() + password = str(self.password_entry.get()) + + if len(password) == 10: + print("マスターパスワードで認証を試行します。") + master_password_hash = self.hash_genarate(str(self.password_entry.get())) + if client_config["master_password_hash"] == master_password_hash: + print("マスターパスワードで認証しました。") + self.exit() + else: + print("マスターパスワードで認証できませんでした。") + self.withdraw() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 誤ったパスワード", message=f"パスワードが間違っています!") + self.msg_subtitle_1.configure(text='パスワードが間違っています! ') + self.button_enable() + self.deiconify() + + + print("認証サーバーにアクセスします。") + auth_url = client_config["auth_host_url"] + "/verify" + auth_json = { + "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(client_config["pc_uuid"]), + "pc_token": str(client_config["pc_token"]), + "password": self.hash_genarate(str(self.password_entry.get())) + } + try: + responce = requests.post(auth_url, json=auth_json) + if responce.status_code == 200: + print("認証サーバー経由で認証しました。") + self.exit() + else: + print("認証サーバー経由での認証に失敗しました。") + self.withdraw() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 誤ったパスワード", message=f"パスワードが間違っています!") + self.msg_subtitle_1.configure(text='パスワードが間違っています! ') + self.button_enable() + self.deiconify() + except: + print("認証サーバーにアクセスできません。マスターパスワードで認証を試行します。") + master_password_hash = self.hash_genarate(str(self.password_entry.get())) + if client_config["master_password_hash"] == master_password_hash: + print("マスターパスワードで認証しました。") + self.exit() + else: + print("マスターパスワードで認証できませんでした。") + self.withdraw() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | ネットワークエラー", message=f"認証サーバーにアクセスできませんでした。\n続行するには、マスターパスワードを入力してください。") + self.msg_subtitle_1.configure(text='ネットワークエラーが発生しています。\n続行するには、マスターパスワードを入力して下さい。 ') + self.button_enable() + self.deiconify() + + def signout(self): + self.withdraw() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 未実装", message=f"ログアウトは未実装です。") + self.deiconify() + + def handler_close(self): + pass + + def help_dummy(self): + self.withdraw() + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 未実装", message=f"ヘルプページは製作途中です。\nDiscordサーバーの指示に従って、認証を進めてください。") + self.deiconify() + + def exit(self): + self.destroy() + app.exit() + + +class Help(customtkinter.CTkToplevel): + def __init__(self): + super().__init__() + if client_config["testing"] == 1: + self.title(f'{app_name} | ヘルプ | テストモード') + else: + self.title(f'{app_name} | ヘルプ') + self.geometry("600x400") + self.resizable(height=False, width=False) + self.attributes('-topmost', True) + self.grab_set() + self.lift() + self.protocol("WM_DELETE_WINDOW", self.handler_close) + msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 未実装", message=f"ヘルプページは製作途中です。\nDiscordサーバーの指示に従って、認証を進めてください。") + self.destroy() + + def handler_close(self): + self.destroy() + +class Stop(): + def __init__(self) -> None: + pass + + def run(self): + print("停止処理を実行中...") + stop_thread = threading.Thread(target=self.stop) + stop_thread.run() + + + def delete_appdata(self, **kwargs): + process_name = kwargs["process_name"] + dir_path = kwargs["dir_path"] + + if not os.path.exists(dir_path): + print(f"エラー: 指定されたディレクトリ {dir_path} が存在しません。") + return 1 + + try: + # プロセスの終了 + subprocess.run(['taskkill', '/f', '/t', '/im', process_name]) + print(f"{process_name} を終了しました。") + + time.sleep(0.1) + + # ディレクトリの削除 + i = 1 + ic = 0 + while i == 1: + shutil.rmtree(dir_path) + if os.path.isdir(dir_path): + ic += 1 + if ic == 10: + i = 0 + else: + i = 0 + print(f"{dir_path} を削除しました。") + + return 0 + + except subprocess.CalledProcessError as e: + print(f"プロセス終了エラー: {e}") + return 1 + except PermissionError as e: + print(f"権限エラー: {e}") + return 1 + except Exception as error: + print("エラーが発生しました。\nエラー内容:") + print(f"エラータイプ: {error.__class__.__name__}") + print(f"エラー引数: {error.args}") + print(f"エラーメッセージ: {str(error)}") + return 1 + + def shutdown(self): + shutdown_command = subprocess.run(['shutdown', '/s', '/t', '1']) + + def stop(self): + print("停止処理を実行。") + if client_config["eraser"] == 1: + #appdata_local = os.path.expandvars("%LOCALAPPDATA%") + #appdata_roaming = os.path.expandvars("%APPDATA%") + #epic_del = app.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved") + #chrome_del = app.delete_appdata(process_name="chrome.exe", dir_path=f"{appdata_local}\\Google\\Chrome\\User Data") + #discord_del = app.delete_appdata(process_name="discord.exe", dir_path=f"{appdata_roaming}\\discord") + #steam_del = app.delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam") + #ea_del = app.delete_appdata(process_name="EADesktop.exe", dir_path=f"{appdata_local}\\Electronic Arts") + #riot_del = app.delete_appdata(process_name="RiotClientServices.exe", dir_path=f"{appdata_local}\\Riot Games\\Riot Client") + pass + else: + print("削除処理をスキップ。") + stop_url = client_config["auth_host_url"] + "/stop" + stop_json = { + "pc_number": int(client_config["pc_number"]), + "pc_uuid": str(client_config["pc_uuid"]), + "pc_token": str(client_config["pc_token"]) + } + try: + responce = requests.post(stop_url, json=stop_json) + if responce.status_code == 200: + print("停止処理は成功しました。") + elif responce.status_code == 401: + print("認証に失敗しました。") + tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"認証に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。") + else: + print("内部エラーにより停止処理に失敗しました。") + result_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"内部エラーにより停止処理に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。") + except: + print("ネットワークエラーにより停止処理に失敗しました。") + result_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"ネットワークエラーにより停止処理に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。") + finally: + self.shutdown() + + +if __name__ == '__main__': + args = sys.argv + if len(args) >= 2: + if args[1] == "stop": + init_result = init() + if init_result == 1: + warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"もう終了処理を行っています。\nPCがシャットダウンするまで、もう少しお待ちください。") + elif init_result == 2: + pass + else: + stop = Stop() + stop.run() + + elif args[1] == "setup": + init_result = init(pc_number=args[2], onetime=args[3]) + if init_result == 1: + warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"すでに {app_name} は実行されています。\n正常に起動しない場合は、既に起動しているプロセスを終了してから、もう一度起動してみてください。") + elif init_result == 2: + pass + else: + pass + else: + print("引数エラー。") + else: + init_result = init() + if init_result == 1: + warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"すでに {app_name} は実行されています。\n正常に起動しない場合は、既に起動しているプロセスを終了してから、もう一度起動してみてください。") + elif init_result == 2: + pass + else: + app = App() + app.protocol("WM_DELETE_WINDOW", app.handler_close) + app.mainloop() diff --git a/dislocker_slash.py b/dislocker_slash.py new file mode 100644 index 0000000..8b01d1d --- /dev/null +++ b/dislocker_slash.py @@ -0,0 +1,1605 @@ +import discord +import os +import json +import psycopg2 +from psycopg2 import sql +from datetime import datetime, timedelta +import asyncio +import string +import random +import hashlib +import openpyxl +from openpyxl import Workbook +import threading +import time + +class DL(): + def __init__(self): + self.config_dir_path = "./config/" + self.export_dir_path = "./export/" + self.log_dir_path = "./log/" + self.server_config_path = self.config_dir_path + "server.json" + self.onetime_config_path = self.config_dir_path + "onetime.json" + self.log_path = self.log_dir_path + "dislocker.txt" + try: + if not os.path.isdir(self.config_dir_path): + print("config ディレクトリが見つかりません... 作成します。") + os.mkdir(self.config_dir_path) + + if not os.path.isfile(self.server_config_path): + print("config ファイルが見つかりません... 作成します。") + self.server_config = { + "db": { + "host": "localhost", + "port": "5432", + "db_name": "dislocker", + "username": "user", + "password": "password" + }, + "bot": { + "server_id": ["TYPE HERE SERVER ID (YOU MUST USE INT !!!!)"], + "token": "TYPE HERE BOTS TOKEN KEY", + "activity": { + "name": "Dislocker", + "details": "ロック中...", + "type": "playing", + "state": "ロック中..." + }, + "log_channel_id" : "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", + "config_channel_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", + "config_public_channel_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", + "monitor": { + "search_frequency": 1, + "allowable_time": 180, + "fstop_time": "21:00:00" + }, + "preset_games": ["TEST1", "TEST2", "TEST3", "TEST4", "TEST5"], + "admin_user_id": ["TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)"], + "debug": False + } + } + + with open(self.server_config_path, "w", encoding="utf-8") as w: + json.dump(self.server_config, w, indent=4, ensure_ascii=False) + + + elif os.path.isfile(self.server_config_path): + with open(self.server_config_path, "r", encoding="utf-8") as r: + self.server_config = json.load(r) + print("config ファイルを読み込みました。") + + if not os.path.isdir(self.export_dir_path): + print("export ディレクトリが見つかりません... 作成します。") + os.mkdir(self.export_dir_path) + + if not os.path.isdir(self.log_dir_path): + print("log ディレクトリが見つかりません... 作成します。") + os.mkdir(self.log_dir_path) + + if os.path.isfile(self.onetime_config_path): + print("ワンタイムパスワードが見つかりました。削除します。") + os.remove(self.onetime_config_path) + + if type(self.server_config["bot"]["log_channel_id"]) is not int or type(self.server_config["bot"]["config_channel_id"]) is not int: + print("config ファイル内でチャンネルIDがint型で記述されていません。int型で記述して、起動してください。") + self.init_result = "not_int" + else: + self.db = psycopg2.connect(f"host={self.server_config['db']['host']} dbname={self.server_config['db']['db_name']} port={self.server_config['db']['port']} user={self.server_config['db']['username']} password={self.server_config['db']['password']}") + cursor = self.db.cursor() + + self.pc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + self.keyboard_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + self.mouse_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + self.preset_games = self.server_config["bot"]["preset_games"] + self.debug = self.server_config["bot"]["debug"] + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'club_member')") + find_club_member_table = cursor.fetchall() + print(find_club_member_table) + if find_club_member_table[0][0] == False: + cursor.execute("CREATE TABLE club_member (member_id SERIAL NOT NULL, name TEXT NOT NULL, discord_user_name TEXT NOT NULL, discord_user_id TEXT NOT NULL, PRIMARY KEY (member_id))") + self.db.commit() + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_list')") + find_pc_list_table = cursor.fetchall() + print(find_pc_list_table) + if find_pc_list_table[0][0] == False: + cursor.execute("CREATE TABLE pc_list (pc_number INTEGER NOT NULL, using_member_id INTEGER, password_hash VARCHAR(64), pc_uuid VARCHAR(36), pc_token VARCHAR(36), master_password VARCHAR(16), detail TEXT, alt_name TEXT, PRIMARY KEY (pc_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))") + for i in self.pc_list: + print(i) + cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (i,)) + self.db.commit() + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'keyboard_list')") + find_keyboard_list_table = cursor.fetchall() + print(find_keyboard_list_table) + if find_keyboard_list_table[0][0] == False: + cursor.execute("CREATE TABLE keyboard_list (keyboard_number INTEGER NOT NULL, using_member_id INTEGER, device_instance_path TEXT, device_name TEXT, detail TEXT, alt_name TEXT, PRIMARY KEY (keyboard_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))") + for i in self.keyboard_list: + print(i) + cursor.execute("INSERT INTO keyboard_list (keyboard_number) VALUES (%s)", (i,)) + self.db.commit() + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'mouse_list')") + find_mouse_list_table = cursor.fetchall() + print(find_mouse_list_table) + if find_mouse_list_table[0][0] == False: + cursor.execute("CREATE TABLE mouse_list (mouse_number INTEGER NOT NULL, using_member_id INTEGER, device_instance_path TEXT, device_name TEXT, detail TEXT, alt_name TEXT, PRIMARY KEY (mouse_number), FOREIGN KEY (using_member_id) REFERENCES club_member(member_id))") + for i in self.mouse_list: + print(i) + cursor.execute("INSERT INTO mouse_list (mouse_number) VALUES (%s)", (i,)) + self.db.commit() + + cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pc_usage_history')") + find_pc_usage_history_table = cursor.fetchall() + print(find_pc_usage_history_table) + if find_pc_usage_history_table[0][0] == False: + cursor.execute("CREATE TABLE pc_usage_history (id SERIAL NOT NULL, member_id INTEGER NOT NULL, pc_number INTEGER NOT NULL, keyboard_number INTEGER, mouse_number INTEGER, start_use_time TIMESTAMP NOT NULL, end_use_time TIMESTAMP, use_detail TEXT, bot_about TEXT, PRIMARY KEY (id), FOREIGN KEY (member_id) REFERENCES club_member(member_id), FOREIGN KEY (pc_number) REFERENCES pc_list(pc_number), FOREIGN KEY (keyboard_number) REFERENCES keyboard_list(keyboard_number), FOREIGN KEY (mouse_number) REFERENCES mouse_list(mouse_number))") + self.db.commit() + + cursor.close() + self.init_result = "ok" + + except (Exception) as error: + print("初回処理でエラーが発生しました。\nエラー内容\n" + str(error)) + self.init_result = "error" + + finally: + pass + + def log(self, **kwargs): + if self.debug == True: + flag = 1 + else: + if "flag" in kwargs: + if kwargs["flag"] == 1: + flag = 1 + else: + flag = 0 + else: + flag = 0 + + if flag == 1: + title = str(kwargs["title"]) + if "message" in kwargs: + message = str(kwargs["message"]) + else: + message = None + + current_datetime = str(datetime.now()) + + if message == None: + detail = f"{current_datetime} | {title}\n" + else: + detail = f"{current_datetime} | {title}\n{message}\n" + + print(detail) + + if os.path.isfile(self.log_path): + try: + with open(self.log_path, "a", encoding="utf-8") as a: + a.write(detail) + except: + print("LOGGING ERROR mode a") + else: + try: + with open(self.log_path, "w", encoding="utf-8") as w: + w.write(detail) + except: + print("LOGGING ERROR mode w") + + def password_generate(self, length): + numbers = string.digits # (1) + password = ''.join(random.choice(numbers) for _ in range(length)) # (2) + return password + + def hash_genarate(self, source): + hashed = hashlib.sha256(source.encode()) + return hashed.hexdigest() + + def user_register_check(self, **kwargs): + try: + discord_user_id = str(kwargs["discord_user_id"]) + + cursor = self.db.cursor() + + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) + user_record = cursor.fetchall() + #ユーザーデータが見つかった場合(登録済みの場合) + if user_record: + member_id = user_record[0][0] + name = user_record[0][1] + discord_user_name = user_record[0][2] + return {"result": 0, "about": "exist", "user_info": {"member_id": member_id, "name": name, "discord_user_name": discord_user_name}} + #ユーザーデータがなかったら(未登録の場合) + else: + return {"result": 1, "about": "user_data_not_found"} + + except Exception as error: + self.log(title=f"[ERROR] ユーザーの登録状態を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + cursor.close() + + def pc_used_check(self, **kwargs): + try: + if "pc_number" in kwargs: + pc_number = int(kwargs["pc_number"]) + else: + pc_number = None + if "discord_user_id" in kwargs: + discord_user_id = str(kwargs["discord_user_id"]) + else: + discord_user_id = None + if "member_id" in kwargs: + member_id = int(kwargs["member_id"]) + else: + member_id = None + + cursor = self.db.cursor() + + if pc_number != None: + # pc番号を指定してpc_listから探す + cursor.execute("SELECT * FROM pc_list WHERE pc_number= %s", (pc_number,)) + pc_list_record = cursor.fetchall() + if pc_list_record[0][1] == None: + return {"result": 0, "about": "vacent"} + else: + return {"result": 1, "about": "used_by_other"} + elif discord_user_id != None: + #ユーザーIDを指定してPC使用履歴から探す + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) + user_record = cursor.fetchall() + #ユーザーデータが見つかった場合(登録済みの場合) + if user_record: + member_id = user_record[0][0] + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage_history_record = cursor.fetchall() + if pc_usage_history_record: + if pc_usage_history_record[0][6] == None: + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + + return {"result": 1, "about": "used_by_you", "pc_usage_history": {"pc_number": str(pc_usage_history_record[0][2]), "keyboard_number": keyboard_number, "mouse_number": mouse_number, "start_time": str(pc_usage_history_record[0][5]), "use_detail": str(pc_usage_history_record[0][7])}} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 1, "about": "user_data_not_found"} + elif member_id != None: + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage_history_record = cursor.fetchall() + if pc_usage_history_record: + if pc_usage_history_record[0][6] == None: + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + return {"result": 1, "about": "used_by_you", "pc_usage_history": {"pc_number": str(pc_usage_history_record[0][2]), "keyboard_number": keyboard_number, "mouse_number": mouse_number, "start_time": str(pc_usage_history_record[0][5]), "use_detail": str(pc_usage_history_record[0][7])}} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 0, "about": "vacent"} + else: + return {"result": 1, "about": "search_options_error"} + + except Exception as error: + self.log(title=f"[ERROR] PCの使用状況を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def keyboard_used_check(self, **kwargs): + try: + cursor = self.db.cursor() + if kwargs["keyboard_number"] == None: + return {"result": 0, "about": "ok"} + else: + keyboard_number = int(kwargs["keyboard_number"]) + + cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number=%s", (keyboard_number,)) + keyboard_list_record = cursor.fetchall() + if keyboard_list_record[0][1] == None: + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "keyboard_already_in_use_by_other"} + + except Exception as error: + self.log(title=f"[ERROR] キーボードの使用状況を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def mouse_used_check(self, **kwargs): + try: + cursor = self.db.cursor() + if kwargs["mouse_number"] == None: + return {"result": 0, "about": "ok"} + else: + mouse_number = int(kwargs["mouse_number"]) + + cursor.execute("SELECT * FROM mouse_list WHERE mouse_number=%s", (mouse_number,)) + mouse_list_record = cursor.fetchall() + if mouse_list_record[0][1] == None: + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "mouse_already_in_use_by_other"} + + except Exception as error: + self.log(title=f"[ERROR] マウスの使用状況を調査中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + + def register(self, **kwargs): + try: + cursor = self.db.cursor() + user_info = { + "id": str(kwargs["discord_user_id"]), + "name": str(kwargs["name"]), + "display_name": str(kwargs["display_name"]), + "pc_number": int(kwargs["pc_number"]), + "keyboard_number": 0, + "mouse_number": 0, + "detail": None + } + if "detail" in kwargs: + user_info["detail"] = str(kwargs["detail"]) + else: + pass + + if kwargs["keyboard_number"] == "own": + pass + else: + user_info["keyboard_number"] = int(kwargs["keyboard_number"]) + + if kwargs["mouse_number"] == "own": + pass + else: + user_info["mouse_number"] = int(kwargs["mouse_number"]) + # ユーザー登録されているかの確認 + user_register = self.user_register_check(discord_user_id=user_info["id"]) + if user_register["result"] == 0: + member_id = user_register["user_info"]["member_id"] + name = user_register["user_info"]["name"] + # ユーザーがPCを使っているか + pc_check_self = self.pc_used_check(member_id=member_id) + if pc_check_self["result"] == 0: + # 他の人がそのPCを使っているか + pc_check = self.pc_used_check(pc_number=user_info["pc_number"]) + if pc_check["result"] == 0: + # キーボードは使われているか + keyboard_check = self.keyboard_used_check(keyboard_number=user_info["keyboard_number"]) + if keyboard_check["result"] == 0: + # マウスは使われているか + mouse_check = self.mouse_used_check(mouse_number=user_info["mouse_number"]) + if mouse_check["result"] == 0: + # パスワードとハッシュ作成 + password = self.password_generate(4) + password_hash = self.hash_genarate(password) + # PC使用履歴のテーブルにレコードを挿入 + + cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, keyboard_number, mouse_number, start_use_time, use_detail) VALUES (%s, %s, %s, %s, clock_timestamp(), %s)", (member_id, user_info["pc_number"], user_info["keyboard_number"], user_info["mouse_number"], user_info["detail"])) + # PCリストの該当のレコードを更新 + cursor.execute("UPDATE pc_list SET using_member_id = %s, password_hash = %s WHERE pc_number = %s", (member_id, password_hash, user_info["pc_number"])) + # キーボードリストの該当のレコードを自前(None)だったらスキップ、借りていたら更新 + if user_info["keyboard_number"] == 0: + pass + else: + cursor.execute("UPDATE keyboard_list SET using_member_id = %s WHERE keyboard_number = %s", (member_id, user_info["keyboard_number"])) + # マウスも同様に + if user_info["mouse_number"] == 0: + pass + else: + cursor.execute("UPDATE mouse_list SET using_member_id = %s WHERE mouse_number = %s", (member_id, user_info["mouse_number"])) + self.db.commit() + return {"result": 0, "about": "ok", "output_dict": {"password": str(password), "name": str(name)}} + else: + return {"result": 1, "about": "mouse_already_in_use"} + else: + return {"result": 1, "about": "keyboard_already_in_use"} + else: + return {"result": 1, "about": "pc_already_in_use_by_other"} + else: + return {"result": 1, "about": "pc_already_in_use_by_you", "pc_usage_history": {"pc_number": pc_check_self["pc_usage_history"]["pc_number"], "keyboard_number": pc_check_self["pc_usage_history"]["keyboard_number"], "mouse_number": pc_check_self["pc_usage_history"]["mouse_number"], "start_time": pc_check_self["pc_usage_history"]["start_time"], "use_detail": pc_check_self["pc_usage_history"]["use_detail"]}} + else: + return {"result": 1, "about": "user_data_not_found"} + except Exception as error: + self.log(title=f"[ERROR] PCの使用登録中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + finally: + if cursor: + cursor.close() + + + def stop(self, **kwargs): + try: + cursor = self.db.cursor() + discord_user_id = str(kwargs["discord_user_id"]) + if "bot_about" in kwargs: + bot_about = kwargs["bot_about"] + else: + bot_about = None + + # ユーザーが登録してるかというよりはデータの取得のため + user_register = self.user_register_check(discord_user_id=discord_user_id) + member_id = user_register["user_info"]["member_id"] + name = user_register["user_info"]["name"] + + if user_register["result"] == 0: + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage_history_record = cursor.fetchall() + + if pc_usage_history_record: + pc_usage_history_id = pc_usage_history_record[0][0] + pc_number = pc_usage_history_record[0][2] + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + end_use_time = pc_usage_history_record[0][6] + + # 使用中のとき (使用停止時間がNoneのとき) + if end_use_time == None: + # 利用停止の理由の有無を判断 + if bot_about == None: + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp() WHERE id = %s", (pc_usage_history_id,)) + else: + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_id)) + # pc_listの使用中ユーザーを消す + cursor.execute("UPDATE pc_list SET using_member_id = NULL, password_hash = NULL WHERE pc_number = %s", (pc_number,)) + if keyboard_number == None: + pass + else: + # keyboard_listの使用中ユーザーを消す + cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,)) + if mouse_number == None: + pass + else: + # mouse_listの使用中ユーザーを消す + cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE mouse_number = %s", (mouse_number,)) + self.db.commit() + return {"result": 0, "about": "ok", "output_dict": {"pc_number": str(pc_number), "name": str(name)}} + else: + return {"result": 1, "about": "unused"} + else: + return {"result": 1, "about": "unused"} + else: + return {"result": 1, "about": "user_data_not_found"} + + except Exception as error: + self.log(title=f"[ERROR] PCの使用停止処理中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def user_register(self, **kwargs): + try: + discord_user_id = str(kwargs["discord_user_id"]) + discord_user_name = str(kwargs["discord_user_name"]) + name = str(kwargs["name"]) + cursor = self.db.cursor() + cursor.execute("SELECT * FROM club_member WHERE discord_user_id = %s", (discord_user_id,)) + user_record = cursor.fetchall() + if not user_record: + cursor.execute("INSERT INTO club_member (name, discord_user_name, discord_user_id) VALUES (%s, %s, %s)", (name, discord_user_name, discord_user_id)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "already_exists"} + + except Exception as error: + self.log(title=f"[ERROR] ユーザー情報の登録中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + + def format_datetime(self, value): + if isinstance(value, datetime): + return value.strftime('%Y-%m-%d %H:%M:%S') + return value + + def pc_register(self, **kwargs): + try: + pc_number = int(kwargs["pc_number"]) + cursor = self.db.cursor() + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_list = cursor.fetchall() + if not pc_list: + cursor.execute("INSERT INTO pc_list (pc_number) VALUES (%s)", (pc_number,)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "already_exists"} + + except Exception as error: + self.log(title=f"[ERROR] PCの情報を登録中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def report_export(self, **kwargs): + try: + cursor = self.db.cursor() + csv_file_path = self.export_dir_path + "pc_usage_history.csv" + main_table = "pc_usage_history" + related_table = "club_member" + excel_file_path = self.export_dir_path + "pc_usage_history.xlsx" + + # メインテーブルの列情報を取得(user_idを除く) + cursor.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table))) + main_columns = [desc[0] for desc in cursor.description if desc[0] != 'member_id'] + + # クエリを作成(列名を明確に指定) + query = sql.SQL(""" + SELECT {main_columns}, {related_table}.name + FROM {main_table} + LEFT JOIN {related_table} ON {main_table}.member_id = {related_table}.member_id + ORDER BY id + """).format( + main_columns=sql.SQL(', ').join([sql.SQL("{}.{}").format(sql.Identifier(main_table), sql.Identifier(col)) for col in main_columns]), + main_table=sql.Identifier(main_table), + related_table=sql.Identifier(related_table) + ) + + cursor.execute(query) + + # 列名を再構成(nameを2番目に配置) + column_names = [main_columns[0], 'name'] + main_columns[1:] + + rows = cursor.fetchall() + + # Excelワークブックを作成 + wb = Workbook() + ws = wb.active + + # 列名を書き込み + ws.append(column_names) + + # データを書き込み + for row in rows: + # nameを2番目に移動 + formatted_row = [self.format_datetime(row[0])] + [row[-1]] + [self.format_datetime(field) if field is not None else '' for field in row[1:-1]] + ws.append(formatted_row) + + # 列幅を自動調整 + for col in ws.columns: + max_length = 0 + column = col[0].column_letter + for cell in col: + try: + if len(str(cell.value)) > max_length: + max_length = len(str(cell.value)) + except: + pass + adjusted_width = (max_length + 2) * 1.2 + ws.column_dimensions[column].width = adjusted_width + + # Excelファイルを保存 + wb.save(excel_file_path) + self.log(title=f"[SUCCESS] PCの使用履歴をエクスポートしました。", message=f"ファイルパス | {excel_file_path}", flag=0) + return {"result": 0, "about": "ok", "file_path": excel_file_path} + + + except Exception as error: + self.log(title=f"[ERROR] PCの使用履歴をエクスポート中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + + def force_stop(self, **kwargs): + try: + pc_number = kwargs["pc_number"] + cursor = self.db.cursor() + if "bot_about" in kwargs: + bot_about = kwargs["bot_about"] + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_list_record = cursor.fetchall() + pc_using_member_id = pc_list_record[0][1] + pc_password_hash = pc_list_record[0][2] + if pc_using_member_id == None: + return {"result": 1, "about": "not_used"} + else: + cursor.execute("UPDATE pc_list SET using_member_id = NULL WHERE pc_number = %s", (pc_number,)) + if pc_password_hash == None: + pass + else: + cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_number,)) + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id = %s AND pc_number = %s ORDER BY id DESC LIMIT 1", (pc_using_member_id, pc_number)) + pc_usage_history_record = cursor.fetchall() + pc_usage_history_record_id = pc_usage_history_record[0][0] + keyboard_number = pc_usage_history_record[0][3] + mouse_number = pc_usage_history_record[0][4] + if keyboard_number == None: + pass + else: + # keyboard_listの使用中ユーザーを消す + cursor.execute("UPDATE keyboard_list SET using_member_id = NULL WHERE keyboard_number = %s", (keyboard_number,)) + if mouse_number == None: + pass + else: + # mouse_listの使用中ユーザーを消す + cursor.execute("UPDATE mouse_list SET using_member_id = NULL WHERE mouse_number = %s", (mouse_number,)) + cursor.execute("UPDATE pc_usage_history SET end_use_time = clock_timestamp(), bot_about = %s WHERE id = %s", (bot_about, pc_usage_history_record_id)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "bot_about_not_found"} + + except Exception as error: + self.log(title=f"[ERROR] fstop中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def pc_onetime_gen(self, **kwargs): + if kwargs.get("max_count") == None: + max_count = 1 + elif isinstance(kwargs.get("max_count"), int): + max_count = int(kwargs.get("max_count")) + else: + max_count = 1 + + try: + if os.path.isfile(dislocker.onetime_config_path): + with open(dislocker.onetime_config_path, "r") as r: + onetime_config = json.load(r) + onetime_password = onetime_config["onetime"]["pc_register"]["password"] + if onetime_password == None: + onetime_password = str(self.password_generate(8)) + onetime_config["onetime"]["pc_register"]["password"] = onetime_password + onetime_config["onetime"]["pc_register"]["max_count"] = max_count + onetime_config["onetime"]["pc_register"]["current_count"] = 0 + current_count = onetime_config["onetime"]["pc_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + else: + current_count = onetime_config["onetime"]["pc_register"]["current_count"] + max_count = onetime_config["onetime"]["pc_register"]["max_count"] + return {"result": 1, "about": "already_exists", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + else: + onetime_password = str(self.password_generate(8)) + onetime_config = { + "onetime": { + "pc_register": { + "password": onetime_password, + "current_count": 0, + "max_count": int(max_count) + }, + "device_register": { + "password": None, + "current_count": None, + "max_count": None + } + } + } + current_count = onetime_config["onetime"]["pc_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + + except Exception as error: + self.log(title=f"[ERROR] PC登録用のワンタイムパスワード発行中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + + def device_onetime_gen(self, **kwargs): + if kwargs.get("max_count") == None: + max_count = 1 + elif isinstance(kwargs.get("max_count"), int): + max_count = int(kwargs.get("max_count")) + else: + max_count = 1 + + try: + if os.path.isfile(dislocker.onetime_config_path): + with open(dislocker.onetime_config_path, "r") as r: + onetime_config = json.load(r) + onetime_password = onetime_config["onetime"]["device_register"]["password"] + if onetime_password == None: + onetime_password = str(self.password_generate(8)) + onetime_config["onetime"]["device_register"]["password"] = onetime_password + onetime_config["onetime"]["device_register"]["max_count"] = max_count + onetime_config["onetime"]["device_register"]["current_count"] = 0 + current_count = onetime_config["onetime"]["device_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + else: + current_count = onetime_config["onetime"]["device_register"]["current_count"] + max_count = onetime_config["onetime"]["device_register"]["max_count"] + return {"result": 1, "about": "already_exists", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + else: + onetime_password = str(self.password_generate(8)) + onetime_config = { + "onetime": { + "pc_register": { + "password": None, + "current_count": None, + "max_count": None + }, + "device_register": { + "password": onetime_password, + "current_count": 0, + "max_count": int(max_count) + } + } + } + current_count = onetime_config["onetime"]["device_register"]["current_count"] + with open(dislocker.onetime_config_path, "w") as w: + json.dump(onetime_config, w, indent=4) + return {"result": 0, "about": "ok", "output_dict": {"onetime_password": onetime_password, "current_count": current_count, "max_count": max_count}} + + except Exception as error: + self.log(title=f"[ERROR] デバイス登録用のワンタイムパスワード発行中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + def show_pc_master_password(self, **kwargs): + try: + if isinstance(kwargs.get("pc_number"), int): + pc_number = int(kwargs.get("pc_number")) + + cursor = self.db.cursor() + cursor.execute("SELECT master_password FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_master_password_list = cursor.fetchall() + pc_master_password = pc_master_password_list[0][0] + + return {"result": 0, "about": "ok", "output_dict": {"pc_master_password": pc_master_password}} + + else: + return {"result": 1, "about": "syntax_error"} + except Exception as error: + self.log(title=f"[ERROR] PCのマスターパスワードを取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_discord_user_id(self, **kwargs): + try: + member_id = int(kwargs["member_id"]) + cursor = self.db.cursor() + cursor.execute("SELECT discord_user_id FROM club_member WHERE member_id = %s", (member_id,)) + discord_user_id_list = cursor.fetchall() + discord_user_id = discord_user_id_list[0][0] + return {"result": 0, "about": "ok", "discord_user_id": discord_user_id} + + except Exception as error: + self.log(title=f"[ERROR] DiscordのユーザーIDの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_pc_list(self, **kwargs): + try: + cursor = self.db.cursor() + + if "pc_number" in kwargs: + pc_number = int(kwargs["pc_number"]) + cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) + pc_list = cursor.fetchall() + + return {"result": 0, "about": "ok", "output_dict": {pc_number: {"pc_number": pc_list[0][0], "using_member_id": pc_list[0][1], "master_password": [0][5], "detail": pc_list[0][6], "alt_name": pc_list[0][7]}}} + else: + cursor.execute("SELECT * FROM pc_list ORDER BY pc_number") + pc_list = cursor.fetchall() + pc_list_base = {} + for i in pc_list: + pc_list_base[i[0]] = {"pc_number": i[0], "using_member_id": i[1], "master_password": i[5], "detail": i[6], "alt_name": i[7]} + + return {"result": 0, "about": "ok", "output_dict": pc_list_base} + + except Exception as error: + self.log(title=f"[ERROR] PCリストの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_keyboard_list(self, **kwargs): + try: + cursor = self.db.cursor() + + if "keyboard_number" in kwargs: + keyboard_number = int(kwargs["keyboard_number"]) + cursor.execute("SELECT * FROM keyboard_list WHERE keyboard_number = %s", (keyboard_number,)) + keyboard_list = cursor.fetchall() + + return {"result": 0, "about": "ok", "output_dict": {keyboard_number: {"keyboard_number": keyboard_list[0][0], "using_member_id": keyboard_list[0][1], "device_instance_path": keyboard_list[0][2], "device_name": keyboard_list[0][3], "detail": keyboard_list[0][4], "alt_name": keyboard_list[0][5]}}} + else: + cursor.execute("SELECT * FROM keyboard_list ORDER BY keyboard_number") + keyboard_list = cursor.fetchall() + keyboard_list_base = {} + for i in keyboard_list: + if i[0] == 0: + pass + else: + keyboard_list_base[i[0]] = {"keyboard_number": i[0], "using_member_id": i[1], "device_instance_path": i[2], "device_name": i[3], "detail": i[4], "alt_name": i[5]} + + return {"result": 0, "about": "ok", "output_dict": keyboard_list_base} + + except Exception as error: + self.log(title=f"[ERROR] キーボードリストの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def get_mouse_list(self, **kwargs): + try: + cursor = self.db.cursor() + + if "mouse_number" in kwargs: + mouse_number = int(kwargs["mouse_number"]) + cursor.execute("SELECT * FROM mouse_list WHERE mouse_number = %s", (mouse_number,)) + mouse_list = cursor.fetchall() + + return {"result": 0, "about": "ok", "output_dict": {mouse_number: {"mouse_number": mouse_list[0][0], "using_member_id": mouse_list[0][1], "device_instance_path": mouse_list[0][2], "device_name": mouse_list[0][3], "detail": mouse_list[0][4], "alt_name": mouse_list[0][5]}}} + else: + cursor.execute("SELECT * FROM mouse_list ORDER BY mouse_number") + mouse_list = cursor.fetchall() + mouse_list_base = {} + for i in mouse_list: + if i[0] == 0: + pass + else: + mouse_list_base[i[0]] = {"mouse_number": i[0], "using_member_id": i[1], "device_instance_path": i[2], "device_name": i[3], "detail": i[4], "alt_name": i[5]} + + return {"result": 0, "about": "ok", "output_dict": mouse_list_base} + + except Exception as error: + self.log(title=f"[ERROR] マウスリストの取得中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + def set_pc_nickname(self, **kwargs): + try: + cursor = self.db.cursor() + + if 'pc_number' in kwargs and 'alt_name' in kwargs: + pc_number = int(kwargs["pc_number"]) + alt_name = kwargs["alt_name"] + cursor.execute("UPDATE pc_list SET alt_name = %s WHERE pc_number = %s", (alt_name, pc_number)) + self.db.commit() + return {"result": 0, "about": "ok"} + else: + return {"result": 1, "about": "syntax_error"} + + except Exception as error: + self.log(title=f"[ERROR] PCのニックネームの設定中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + return {"result": 1, "about": "error", "output_dict": {"error_class_name": str(error.__class__.__name__), "error_args": str(error.args)}} + + finally: + if cursor: + cursor.close() + + +class ReasonModal(discord.ui.Modal): + def __init__(self, title: str, pc_number: str, keyboard_number: str, mouse_number: str, timeout=15) -> None: + super().__init__(title=title, timeout=timeout) + self.reason_input_form = discord.ui.TextInput(label="使用目的を入力してください", style=discord.TextStyle.short, custom_id=f"register_{pc_number}_{keyboard_number}_{mouse_number}") + self.add_item(self.reason_input_form) + + async def on_submit(self, interaction: discord.Interaction) -> None: + custom_id = interaction.data["components"][0]["components"][0]["custom_id"] + custom_id_split = custom_id.split("_") + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "own": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "own": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + register = dislocker.register(discord_user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=self.reason_input_form.value) + + if register["about"] == "ok": + await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["output_dict"]["password"]}\n## PC番号 | {pc_number}\n## キーボード番号 | {keyboard_number_show}\n## マウス番号 | {mouse_number_show}\n## 使用目的 | {self.reason_input_form.value}", ephemeral=True) + await client.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["output_dict"]["name"]} さんがPC {pc_number} の使用を開始しました。\n>>> ## PC番号 | {pc_number}\n## キーボード番号 | {keyboard_number_show}\n## マウス番号 | {mouse_number_show}\n## 使用目的 | {self.reason_input_form.value}') + dislocker.log(title=f"[INFO] PC番号{pc_number} の使用が開始されました。", message=f"名前 | {register["output_dict"]["name"]}, 使用目的 | {self.reason_input_form.value}", flag=0) + elif register["about"] == "pc_already_in_use_by_you": + pc_usage_history = register["pc_usage_history"] + if pc_usage_history["keyboard_number"] == None: + keyboard_number_show = "未認証" + elif pc_usage_history["keyboard_number"] == 0: + keyboard_number_show = "自前" + else: + keyboard_number_show = str(pc_usage_history["keyboard_number"]) + + if pc_usage_history["mouse_number"] == None: + mouse_number_show = "未認証" + elif pc_usage_history["mouse_number"] == 0: + mouse_number_show = "自前" + else: + mouse_number_show = str(pc_usage_history["mouse_number"]) + + await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}", ephemeral=True) + #await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}\n# 使用目的 | {pc_usage_history["use_detail"]}", ephemeral=True) + + elif register["about"] == "pc_already_in_use_by_other": + await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "keyboard_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのキーボードは他のメンバーによって使用されています。\n別のキーボードのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "mouse_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのマウスは他のメンバーによって使用されています。\n別のマウスのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "user_data_not_found": + await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) + else: + await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + + +class Monitor(): + def __init__(self, **kwargs) -> None: + self.search_frequency = kwargs["search_frequency"] + self.allowable_time = kwargs["allowable_time"] + self.fstop_time = kwargs["fstop_time"] + self.init_wait_time = 10 + + def start(self, **kwargs): + search_thread = threading.Thread(target=self.search) + search_thread.start() + + def search(self): + try: + time.sleep(self.init_wait_time) + while True: + cursor = dislocker.db.cursor() + cursor.execute("SELECT * FROM pc_list WHERE password_hash IS NOT NULL") + pc_list = cursor.fetchall() + current_datetime = datetime.now() + fstop_time = self.fstop_time + if current_datetime.time().strftime("%H:%M:%S") == fstop_time: + dislocker.log(title=f"[INFO] 定期のPCの使用停止処理を開始します。", flag=0) + for i in dislocker.pc_list: + stop = dislocker.force_stop(pc_number=i, bot_about="使用停止忘れによるBotによる強制停止。") + result = {"result": "FSTOP"} + dislocker.log(title=f"[SUCCESS] 定期のPCの使用停止処理は完了しました。", flag=0) + else: + if pc_list: + if len(pc_list) == 1: + member_id = pc_list[0][1] + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s AND end_use_time IS NULL ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage = cursor.fetchall() + start_time = pc_usage[0][5] + time_difference = current_datetime - start_time + dislocker.log(title=f"[INFO] 現在確認されているパスワード未使用のユーザー", message=f"レコード | {str(pc_usage)}, 経過時間(Sec) | {time_difference.seconds}/{timedelta(seconds=self.allowable_time).seconds}", flag=0) + if time_difference.seconds >= timedelta(seconds=self.allowable_time).seconds: + cursor.execute("SELECT * FROM club_member WHERE member_id = %s", (member_id,)) + user_info = cursor.fetchall() + stop = dislocker.stop(discord_user_id=user_info[0][3], bot_about="パスワードのタイムアウトでBotによる強制停止。") + + #bot.timeout_notify(pc_number=pc_list[0][0], discord_display_name=user_info[0][1]) + dislocker.log(title=f"[INFO] パスワードのタイムアウト時間に達したため、強制停止されました。", flag=0) + result = {"result": "STOP", "details": str(pc_usage)} + else: + result = {"result": "BUT SAFE", "details": str(pc_usage)} + + + elif len(pc_list) >= 2: + for i in pc_list: + member_id = i[1] + cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s AND end_use_time IS NULL ORDER BY id DESC LIMIT 1", (member_id,)) + pc_usage = cursor.fetchall() + start_time = pc_usage[0][5] + time_difference = current_datetime - start_time + dislocker.log(title=f"[INFO] 現在確認されているパスワード未使用のユーザー", message=f"レコード | {str(pc_usage)}, 経過時間(Sec) | {time_difference.seconds}/{timedelta(seconds=self.allowable_time).seconds}", flag=0) + if time_difference.seconds >= timedelta(seconds=self.allowable_time).seconds: + cursor.execute("SELECT * FROM club_member WHERE member_id = %s", (member_id,)) + user_info = cursor.fetchall() + stop = dislocker.stop(discord_user_id=user_info[0][3], bot_about="タイムアウトでBotによる強制停止。") + + #bot.timeout_notify(pc_number=i[0], discord_display_name=user_info[0][1]) + dislocker.log(title=f"[INFO] パスワードのタイムアウト時間に達したため、強制停止されました。", flag=0) + result = {"result": "STOP", "details": str(pc_usage)} + else: + result = {"result": "BUT SAFE", "details": str(pc_usage)} + + else: + result = {"result": "NONE"} + else: + result = {"result": "NONE"} + + if result["result"] == "NONE": + pass + else: + pass + time.sleep(self.search_frequency) + + + except Exception as error: + dislocker.log(title=f"[ERROR] 自動停止処理中にエラーが発生しました。 {str(error.__class__.__name__)}", message=str(error.args), flag=1) + result = {"result": "error"} + dislocker.db.rollback() + + finally: + if cursor: + cursor.close() + return result + + +dislocker = DL() + +intents = discord.Intents.default() +intents.message_content = True + +client = discord.Client(intents=intents) +tree = discord.app_commands.CommandTree(client) + +@client.event +async def on_ready(): + dislocker.log(title=f"[SUCCESS] DiscordのBotが起動しました。", message=f"{client.user.name} としてログインしています。", flag=1) + await tree.sync() + dislocker_activity = discord.Activity( + name=dislocker.server_config["bot"]["activity"]["name"], + type=discord.ActivityType.competing, + details=dislocker.server_config["bot"]["activity"]["details"], + state=dislocker.server_config["bot"]["activity"]["state"] + ) + await client.change_presence(activity=dislocker_activity) + +@client.event +async def on_message(message): + if message.author.bot: + pass + + elif isinstance(message.channel, discord.DMChannel): + if message.author.id in dislocker.server_config["bot"]["admin_user_id"]: + msg_split = message.content.split() + + if msg_split[0] == "/pcreg": + max_count = 1 + if len(msg_split) == 2: + if msg_split[1].isdecimal(): + max_count = int(msg_split[1]) + + pc_onetime_password_gen = dislocker.pc_onetime_gen(max_count=max_count) + + if pc_onetime_password_gen["result"] == 0: + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"PC登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + elif pc_onetime_password_gen["result"] == 1: + if pc_onetime_password_gen["about"] == "already_exists": + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_onetime_password_gen['output_dict']['error_class_name']}", value=f"{pc_onetime_password_gen['output_dict']['error_args']}") + + await message.channel.send(embed=result_embed) + + elif msg_split[0] == "/devreg": + max_count = 1 + if len(msg_split) == 2: + if msg_split[1].isdecimal(): + max_count = int(msg_split[1]) + + device_onetime_password_gen = dislocker.device_onetime_gen(max_count=max_count) + + if device_onetime_password_gen["result"] == 0: + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"デバイス登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + elif device_onetime_password_gen["result"] == 1: + if device_onetime_password_gen["about"] == "already_exists": + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{device_onetime_password_gen['output_dict']['error_class_name']}", value=f"{device_onetime_password_gen['output_dict']['error_args']}") + + await message.channel.send(embed=result_embed) + + else: + result_embed = discord.Embed(title=":x: 警告", description=f'DMでの操作はサポートされていません。', color=0xC91111) + await message.channel.send(embed=result_embed) + else: + pass + +@client.event +async def on_interaction(interaction: discord.Interaction): + try: + if interaction.data["component_type"] == 2: + await on_button(interaction) + except KeyError: + pass + +async def on_button(interaction: discord.Interaction): + custom_id = interaction.data["custom_id"] + custom_id_split = custom_id.split("_") + dislocker.log(title=f"[INFO] ボタンが押されました。", message=f"custom_id | {custom_id}, DiscordユーザーID | {interaction.user.id}", flag=0) + + if custom_id_split[0] == "pcregister": + keyboard_register_view = discord.ui.View(timeout=15) + pc_number = custom_id_split[1] + keyboard_list = dislocker.get_keyboard_list() + + for i in keyboard_list["output_dict"].keys(): + current_keyboard_list = keyboard_list['output_dict'][i] + if current_keyboard_list['alt_name'] == None: + keyboard_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_keyboard_list['keyboard_number'])} 番", custom_id=f"keyboardregister_{str(pc_number)}_{str(current_keyboard_list['keyboard_number'])}") + else: + keyboard_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_keyboard_list['keyboard_number'])} 番 | ({current_keyboard_list['alt_name']})", custom_id=f"keyboardregister_{str(pc_number)}_{str(current_keyboard_list['keyboard_number'])}") + keyboard_register_view.add_item(keyboard_register_button) + + keyboard_not_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="キーボードは自前", custom_id=f"keyboardregister_{str(pc_number)}_own") + keyboard_register_view.add_item(keyboard_not_register_button) + + await interaction.response.send_message(f"# :keyboard: キーボードのデバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=keyboard_register_view, ephemeral=True) + + elif custom_id_split[0] == "keyboardregister": + mouse_register_view = discord.ui.View(timeout=15) + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_list = dislocker.get_mouse_list() + if keyboard_number == "own": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + for i in mouse_list["output_dict"].keys(): + current_mouse_list = mouse_list['output_dict'][i] + if current_mouse_list['alt_name'] == None: + mouse_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_mouse_list['mouse_number'])} 番", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_{str(current_mouse_list['mouse_number'])}") + else: + mouse_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_mouse_list['mouse_number'])} 番 | ({current_mouse_list['alt_name']})", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_{str(current_mouse_list['mouse_number'])}") + mouse_register_view.add_item(mouse_register_button) + + mouse_not_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="マウスは自前", custom_id=f"mouseregister_{str(pc_number)}_{str(keyboard_number)}_own") + mouse_register_view.add_item(mouse_not_register_button) + + await interaction.response.send_message(f"# :mouse_three_button: マウスのデバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}\n# キーボード番号 | {str(keyboard_number_show)}", view=mouse_register_view, ephemeral=True) + + elif custom_id_split[0] == "mouseregister": + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "own": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "own": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + reason_register_view = discord.ui.View(timeout=15) + for i in dislocker.preset_games: + reason_quick_button = reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(i)}", custom_id=f"quickreasonregister_{str(pc_number)}_{str(keyboard_number)}_{str(mouse_number)}_{str(i)}") + reason_register_view.add_item(reason_quick_button) + reason_button = discord.ui.Button(style=discord.ButtonStyle.primary, label="使用目的を入力する", custom_id=f"reasonregister_{str(pc_number)}_{str(keyboard_number)}_{str(mouse_number)}") + reason_register_view.add_item(reason_button) + + await interaction.response.send_message(f"# :regional_indicator_q: 使用目的を書いてください!\n>>> # PC番号 | {str(pc_number)}\n# キーボード番号 | {str(keyboard_number_show)}\n# マウス番号 | {str(mouse_number_show)}", view=reason_register_view, ephemeral=True) + + elif custom_id_split[0] == "quickreasonregister": + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "own": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "own": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + reason = custom_id_split[4] + + register = dislocker.register(discord_user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=reason) + if register["about"] == "ok": + await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["output_dict"]["password"]}\n## PC番号 | {pc_number}\n## キーボード番号 | {str(keyboard_number_show)}\n## マウス番号 | {str(mouse_number_show)}\n## 使用目的 | {reason}", ephemeral=True) + await client.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["output_dict"]["name"]} さんがPC {pc_number} の使用を開始しました。\n>>> ## PC番号 | {pc_number}\n## 使用目的 | {reason}') + dislocker.log(title=f"[INFO] PC番号{pc_number} の使用が開始されました。", message=f"名前 | {register["output_dict"]["name"]}, 使用目的 | {reason}", flag=0) + elif register["about"] == "pc_already_in_use_by_you": + pc_usage_history = register["pc_usage_history"] + if pc_usage_history["keyboard_number"] == None: + keyboard_number_show = "未認証" + elif pc_usage_history["keyboard_number"] == 0: + keyboard_number_show = "自前" + else: + keyboard_number_show = str(pc_usage_history["keyboard_number"]) + + if pc_usage_history["mouse_number"] == None: + mouse_number_show = "未認証" + elif pc_usage_history["mouse_number"] == 0: + mouse_number_show = "自前" + else: + mouse_number_show = str(pc_usage_history["mouse_number"]) + await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}", ephemeral=True) + #await interaction.response.send_message(f"# :exploding_head: あなたはPCをもう使用されているようです。\n使用状態を解除するには 終了ボタン で使用終了をお知らせください。\n>>> # PC番号 | {pc_usage_history["pc_number"]}\n# キーボード番号 | {keyboard_number_show}\n# マウス番号 | {mouse_number_show}\n# 使用開始時刻 | {pc_usage_history["start_time"]}\n# 使用目的 | {pc_usage_history["use_detail"]}", ephemeral=True) + elif register["about"] == "pc_already_in_use_by_other": + await interaction.response.send_message(f"# :man_gesturing_no: そのPCは他のメンバーによって使用されています。\n別のPC番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "keyboard_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのキーボードは他のメンバーによって使用されています。\n別のキーボードのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "mouse_already_in_use": + await interaction.response.send_message(f"# :man_gesturing_no: そのマウスは他のメンバーによって使用されています。\n別のマウスのデバイス番号を指定して、再度お試しください。", ephemeral=True) + elif register["about"] == "user_data_not_found": + await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) + else: + await interaction.response.send_message("# :skull_crossbones: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + + elif custom_id_split[0] == "reasonregister": + pc_number = custom_id_split[1] + keyboard_number = custom_id_split[2] + mouse_number = custom_id_split[3] + + if keyboard_number == "own": + keyboard_number_show = "自前" + else: + keyboard_number_show = keyboard_number + + if mouse_number == "own": + mouse_number_show = "自前" + else: + mouse_number_show = mouse_number + + reason_input_form = ReasonModal(title="Dislocker | 登録", pc_number=str(pc_number), keyboard_number=str(keyboard_number), mouse_number=str(mouse_number)) + await interaction.response.send_modal(reason_input_form) + + elif custom_id_split[0] == "stop": + pc_stop = dislocker.stop(discord_user_id=interaction.user.id) + stop_view = discord.ui.View(timeout=15) + if pc_stop["about"] == "unused": + await interaction.response.send_message("# :shaking_face: 使用されていないようです...", ephemeral=True) + elif pc_stop["about"] == "user_data_not_found": + await interaction.response.send_message("# :dizzy_face: ユーザーとして登録されていないようです。\n最初にサーバーで登録を行ってください。", ephemeral=True) + elif pc_stop["about"] == "ok": + await interaction.response.send_message(f":white_check_mark: PC番号 {pc_stop["output_dict"]["pc_number"]} の使用が終了されました。", ephemeral=True) + await client.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':negative_squared_cross_mark: {pc_stop["output_dict"]["name"]} さんがPC {pc_stop["output_dict"]["pc_number"]} の使用を終了しました。') + else: + await interaction.response.send_message("# :skull_crossbones: 停止できませんでした。\n内部エラーが発生しています。", ephemeral=True) + + elif custom_id_split[0] == "user" and custom_id_split[1] == "register": + user_register = dislocker.user_register(name=interaction.user.display_name, discord_user_name=interaction.user.name, discord_user_id=interaction.user.id) + if user_register["about"] == "ok": + await interaction.response.send_message(f"# :white_check_mark: ユーザー情報が登録されました。\n>>> ユーザー名:{interaction.user.display_name}", ephemeral=True) + elif user_register["about"] == "already_exists": + await interaction.response.send_message("# :no_entry: 登録できませんでした。\nもう登録されている可能性があります。", ephemeral=True) + else: + await interaction.response.send_message("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) + + +#使用者側のスラッシュコマンド +@tree.command(name="use", description="パソコンの使用登録をします。通常はこのコマンドを使用する必要はありません。") +async def use(interaction: discord.Interaction, pc_number: int, keyboard_number: int, mouse_number: int, detail: str): + register = dislocker.register(discord_user_id=interaction.user.id, name=interaction.user.name, display_name=interaction.user.display_name, pc_number=pc_number, keyboard_number=keyboard_number, mouse_number=mouse_number, detail=detail) + if register["result"] == 0: + await interaction.response.send_message(f":white_check_mark: 使用が開始されました。\n>>> # パスワード | {register["output_dict"]["password"]}\n## PC番号 | {pc_number}\n## 使用目的 | {detail}", ephemeral=True) + dislocker.log(title=f"[INFO] PC番号{pc_number} の使用が開始されました。", message=f"名前 | {register["output_dict"]["name"]}, 使用目的 | {detail}", flag=0) + await client.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(f':white_check_mark: {register["output_dict"]["name"]} さんがPC {pc_number} の使用を開始しました。\n>>> ## PC番号 | {pc_number}\n## 使用目的 | {detail}') + elif register["result"] == 1: + if register["about"] == "pc_already_in_use_by_other": + await interaction.response.send_message(":x: 他の方がそのPCを使用中です。", ephemeral=True) + elif register["about"] == "pc_already_in_use_by_you": + await interaction.response.send_message(f":x: あなたは既にPC {register['pc_usage_history']['pc_number']} を使用中です。\n>>> ## PC番号 | {register['pc_usage_history']['pc_number']}\n## 使用目的 | {register['pc_usage_history']['use_detail']}", ephemeral=True) + elif register["about"] == "keyboard_already_in_use": + await interaction.response.send_message(":x: キーボードは既に使用中です。", ephemeral=True) + elif register["about"] == "mouse_already_in_use": + await interaction.response.send_message(":x: マウスは既に使用中です。", ephemeral=True) + elif register["about"] == "user_data_not_found": + await interaction.response.send_message(":x: ユーザーデータが見つかりませんでした。", ephemeral=True) + elif register["about"] == "error": + await interaction.response.send_message(":x: 内部エラーが発生しました。\nサーバーでエラーが発生しています。管理者に問い合わせてください。", ephemeral=True) + +@tree.command(name="stop", description="パソコンの使用を終了します。通常はこのコマンドを使用する必要はありません。") +async def stop(interaction: discord.Interaction): + stop = dislocker.stop(discord_user_id=interaction.user.id) + if stop["result"] == 0: + await interaction.response.send_message(f":white_check_mark: 使用が終了されました。\n>>> ## PC番号 | {stop['output_dict']['pc_number']}", ephemeral=True) + result_embed = discord.Embed(title=":white_check_mark: 使用停止処理は完了しました。", description=f'PC番号 {stop['output_dict']['pc_number']} 番の使用停止処理が完了しました。', color=0x56FF01) + dislocker.log(title=f"[INFO] PC番号{stop['output_dict']['pc_number']} の使用が終了されました。", message=f"名前 | {stop['output_dict']['name']}", flag=0) + log_embed = discord.Embed(title=f":information_source: PC番号 {stop['output_dict']['pc_number']} の使用は終了されました。", description=f"<@{interaction.user.id}> によるリクエスト", color=0x2286C9) + await client.get_channel(dislocker.server_config["bot"]["log_channel_id"]).send(embed=log_embed) + + elif stop["result"] == 1: + if stop["about"] == "unused": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'あなたはPCを使用されていないようです...', color=0xC91111) + + elif stop["about"] == "user_data_not_found": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'Dislockerのユーザーとして登録されていないようです。\n登録を行ってから、またお試しください。', color=0xC91111) + + elif stop["about"] == "error": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{stop['output_dict']['error_class_name']}", value=f"{stop['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +#管理者側のスラッシュコマンド +@tree.command(name="userreg", description="ユーザーを登録します。") +@discord.app_commands.default_permissions(administrator=True) +async def userreg(interaction: discord.Interaction, discord_user_id: str, discord_user_name: str, name: str): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + user_register = dislocker.user_register(discord_user_id=discord_user_id, discord_user_name=discord_user_name, name=name) + if user_register["result"] == 0: + result_embed = discord.Embed(title=":white_check_mark: ユーザー登録が完了しました。", description=f'続いて、PCの使用登録を行いましょう!', color=0x56FF01) + dislocker.log(title=f"[INFO] ユーザーを登録しました。", message=f"名前 | {name}, Discordユーザー名 | {discord_user_name}, DiscordユーザーID | {discord_user_id}", flag=0) + + elif user_register["result"] == 1: + if user_register["about"] == "already_exists": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'既に登録されているユーザーです。', color=0xC91111) + + elif user_register["about"] == "error": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{user_register['output_dict']['error_class_name']}", value=f"{user_register['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcreg", description="PCをDislockerに登録するためのワンタイムパスワードを発行します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcreg(interaction: discord.Interaction, how_much: int = 1): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + max_count = how_much + + pc_onetime_password_gen = dislocker.pc_onetime_gen(max_count=max_count) + + if pc_onetime_password_gen["result"] == 0: + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"PC登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + elif pc_onetime_password_gen["result"] == 1: + if pc_onetime_password_gen["about"] == "already_exists": + pc_onetime_password = str(pc_onetime_password_gen["output_dict"]["onetime_password"]) + pc_onetime_password_max_count = str(pc_onetime_password_gen["output_dict"]["max_count"]) + pc_onetime_password_current_count = str(pc_onetime_password_gen["output_dict"]["current_count"]) + pc_onetime_password_remaining_times = str(int(pc_onetime_password_max_count) - int(pc_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: PCの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=pc_onetime_password) + result_embed.add_field(name="最大使用回数", value=pc_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=pc_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_onetime_password_gen['output_dict']['error_class_name']}", value=f"{pc_onetime_password_gen['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="devicereg", description="デバイスをDislockerに登録するためのワンタイムパスワードを発行します。") +@discord.app_commands.default_permissions(administrator=True) +async def devicereg(interaction: discord.Interaction, how_much: int): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + max_count = how_much + + device_onetime_password_gen = dislocker.device_onetime_gen(max_count=max_count) + + if device_onetime_password_gen["result"] == 0: + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"デバイス登録時のワンタイムパスワードを発行します。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + elif device_onetime_password_gen["result"] == 1: + if device_onetime_password_gen["about"] == "already_exists": + device_onetime_password = str(device_onetime_password_gen["output_dict"]["onetime_password"]) + device_onetime_password_max_count = str(device_onetime_password_gen["output_dict"]["max_count"]) + device_onetime_password_current_count = str(device_onetime_password_gen["output_dict"]["current_count"]) + device_onetime_password_remaining_times = str(int(device_onetime_password_max_count) - int(device_onetime_password_current_count)) + result_embed = discord.Embed(title=":dizzy_face: デバイスの登録", description=f"ワンタイムパスワードはもう発行されており、有効です。", color=0x2286C9) + result_embed.add_field(name="パスワード", value=device_onetime_password) + result_embed.add_field(name="最大使用回数", value=device_onetime_password_max_count) + result_embed.add_field(name="残り使用回数", value=device_onetime_password_remaining_times) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{device_onetime_password_gen['output_dict']['error_class_name']}", value=f"{device_onetime_password_gen['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + + +@tree.command(name="fstop", description="PCの使用登録を強制的に終了します。") +@discord.app_commands.default_permissions(administrator=True) +async def fstop(interaction: discord.Interaction, pc_number: int, about: str): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + force_stop = dislocker.force_stop(pc_number=pc_number, bot_about=about) + if force_stop["result"] == 0: + result_embed = discord.Embed(title=":white_check_mark: 処理が完了しました。", description=f'PC番号 {str(pc_number)} 番の使用登録は抹消されました。', color=0x56FF01) + + dislocker.log(title=f"[INFO] PC {pc_number} の使用を強制終了しました。", message=f"理由 | {about}", flag=0) + elif force_stop["result"] == 1: + if force_stop["about"] == "not_used": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'指定されたPCは使用されていないようです...', color=0xC91111) + + elif force_stop["about"] == "bot_about_not_found": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'強制停止する理由を入力してください。', color=0xC91111) + + elif force_stop["about"] == "error": + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{force_stop['output_dict']['error_class_name']}", value=f"{force_stop['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="report", description="PCの使用履歴をエクスポートします。") +@discord.app_commands.default_permissions(administrator=True) +async def report(interaction: discord.Interaction): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + report_export = dislocker.report_export() + if report_export["result"] == 0: + await interaction.response.send_message(f":white_check_mark: 使用履歴のレポートです。", file=discord.File(report_export["file_path"]), ephemeral=True) + dislocker.log(title=f"[INFO] PCの使用履歴をエクスポートしました。", message=f"ファイルパス | {report_export['file_path']}", flag=0) + elif report_export["result"] == 1: + if report_export["about"] == "error": + await interaction.response.send_message(":x: 内部エラーが発生しました。\nサーバーでエラーが発生しています。管理者に問い合わせてください。", ephemeral=True) + +@tree.command(name="init", description="操作チャンネルにボタン一式を送信します。") +@discord.app_commands.default_permissions(administrator=True) +async def button_init(interaction: discord.Interaction, text_channel: discord.TextChannel): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_list = dislocker.get_pc_list() + + user_register_button_view = discord.ui.View(timeout=None) + user_register_button = discord.ui.Button(style=discord.ButtonStyle.green, label="ユーザー登録", custom_id="user_register") + user_register_button_view.add_item(user_register_button) + + await client.get_channel(text_channel.id).send(f'# :index_pointing_at_the_viewer: ユーザー登録はお済ですか?', view=user_register_button_view) + + stop_button_view = discord.ui.View(timeout=None) + stop_button = discord.ui.Button(style=discord.ButtonStyle.danger, label="PCの使用を停止", custom_id="stop") + stop_button_view.add_item(stop_button) + + await client.get_channel(text_channel.id).send(f'# :index_pointing_at_the_viewer: 使用を停止しますか?', view=stop_button_view) + + pc_button_view = discord.ui.View(timeout=None) + for i in pc_list["output_dict"].keys(): + current_pc_list = pc_list['output_dict'][i] + if current_pc_list['alt_name'] == None: + pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_pc_list['pc_number'])} 番", custom_id=f"pcregister_{str(current_pc_list['pc_number'])}") + else: + pc_register_button = discord.ui.Button(style=discord.ButtonStyle.primary, label=f"{str(current_pc_list['pc_number'])} 番 | ({current_pc_list['alt_name']})", custom_id=f"pcregister_{str(current_pc_list['pc_number'])}") + pc_button_view.add_item(pc_register_button) + + await client.get_channel(text_channel.id).send(f'# :index_pointing_at_the_viewer: 使いたいPCの番号を選んでください!', view=pc_button_view) + dislocker.log(title=f"[INFO] サーバーで初回処理を実行しました。", flag=0) + + result_embed = discord.Embed(title=":white_check_mark: 初回処理が完了しました。", description=f'指定したテキストチャンネルをご確認ください。', color=0x56FF01) + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="masterpass", description="PCのマスターパスワードを表示します。") +@discord.app_commands.default_permissions(administrator=True) +async def masterpass(interaction: discord.Interaction, pc_number: int): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_master_password_get = dislocker.show_pc_master_password(pc_number=pc_number) + + if pc_master_password_get["result"] == 0: + pc_master_password = pc_master_password_get["output_dict"]["pc_master_password"] + + result_embed = discord.Embed(title=":information_source: マスターパスワード", description=f"PC番号 {str(pc_number)} 番のマスターパスワードを表示します。", color=0x2286C9) + result_embed.add_field(name=f"マスターパスワード", value=f"{str(pc_master_password)}") + + else: + result_embed = discord.Embed(title=":x: 取得に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_master_password_get['output_dict']['error_class_name']}", value=f"{pc_master_password_get['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcinfo", description="PCの情報を表示します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcinfo(interaction: discord.Interaction): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_list = dislocker.get_pc_list() + + if pc_list["result"] == 0: + result_embed = discord.Embed(title=":information_source: 現在のPCリスト", description="PCリストです。", color=0x2286C9) + + for i in pc_list['output_dict'].keys(): + current_pc_list = pc_list['output_dict'][i] + if current_pc_list['alt_name'] == None: + pc_name_title = f'{current_pc_list['pc_number']} 番' + else: + pc_name_title = f'{current_pc_list['pc_number']} 番 ({current_pc_list['alt_name']})' + + if current_pc_list['using_member_id'] == None: + pc_using_value = f'未使用' + else: + discord_user_id = dislocker.get_discord_user_id(current_pc_list['using_member_id']) + pc_using_value = f'<@{discord_user_id}> が使用中' + + result_embed.add_field(name=f'{pc_name_title}', value=f'{pc_using_value}') + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。', color=0xC91111) + result_embed.add_field(name=f"{pc_list['output_dict']['error_class_name']}", value=f"{pc_list['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + +@tree.command(name="pcnickname", description="PCにニックネームを設定します。") +@discord.app_commands.default_permissions(administrator=True) +async def pcnickname(interaction: discord.Interaction, pc_number: int, nickname: str): + if interaction.guild_id in dislocker.server_config["bot"]["server_id"] or interaction.user.id in dislocker.server_config["bot"]["admin_user_id"]: + pc_nickname_set = dislocker.set_pc_nickname(pc_number=pc_number, alt_name=nickname) + if pc_nickname_set["result"] == 0: + result_embed = discord.Embed(title=":white_check_mark: 操作が完了しました。", description=f'PC番号 {str(pc_number)} のニックネームは {str(nickname)} に設定されました。', color=0x56FF01) + + else: + result_embed = discord.Embed(title=":x: 操作に失敗しました。", description=f'サーバーでエラーが発生しています。ニックネームは変更されません。', color=0xC91111) + result_embed.add_field(name=f"{pc_nickname_set['output_dict']['error_class_name']}", value=f"{pc_nickname_set['output_dict']['error_args']}") + + await interaction.response.send_message(embed=result_embed, ephemeral=True) + + +if dislocker.init_result == "ok": + print("Botを起動します...") + monitor = Monitor(search_frequency=dislocker.server_config["bot"]["monitor"]["search_frequency"], allowable_time=dislocker.server_config["bot"]["monitor"]["allowable_time"], fstop_time=dislocker.server_config["bot"]["monitor"]["fstop_time"]) + monitor.start() + client.run(dislocker.server_config["bot"]["token"]) +else: + pass diff --git a/requirements.txt b/requirements.txt index b5e4974..9d4be8d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,8 +1,4 @@ discord.py -flask -flask-login psycopg2-binary -winotify -customtkinter -keyboard -requests \ No newline at end of file +openpyxl +flask \ No newline at end of file diff --git a/requirements_client.txt b/requirements_client.txt index 8c989de..c08283b 100644 --- a/requirements_client.txt +++ b/requirements_client.txt @@ -1,4 +1,5 @@ customtkinter winotify keyboard -requests \ No newline at end of file +requests +pywin32 \ No newline at end of file diff --git a/resource/cover/dislocker_dark.png b/resource/cover/dislocker_dark.png new file mode 100644 index 0000000..4c2b769 Binary files /dev/null and b/resource/cover/dislocker_dark.png differ diff --git a/resource/cover/dislocker_light.png b/resource/cover/dislocker_light.png new file mode 100644 index 0000000..b16de21 Binary files /dev/null and b/resource/cover/dislocker_light.png differ diff --git a/resource/icon/dislocker_label.png b/resource/icon/dislocker_label.png new file mode 100644 index 0000000..a162ef7 Binary files /dev/null and b/resource/icon/dislocker_label.png differ diff --git a/resource/icon/dislocker_label_logo.png b/resource/icon/dislocker_label_logo.png new file mode 100644 index 0000000..ff7917c Binary files /dev/null and b/resource/icon/dislocker_label_logo.png differ diff --git a/resource/icon/dislocker_label_logo_white.png b/resource/icon/dislocker_label_logo_white.png new file mode 100644 index 0000000..03fdff3 Binary files /dev/null and b/resource/icon/dislocker_label_logo_white.png differ diff --git a/resource/icon/dislocker_shutdown.ico b/resource/icon/dislocker_shutdown.ico new file mode 100644 index 0000000..c05d727 Binary files /dev/null and b/resource/icon/dislocker_shutdown.ico differ diff --git a/resource/icon/png/shutdown/128.png b/resource/icon/png/shutdown/128.png new file mode 100644 index 0000000..aaf2e18 Binary files /dev/null and b/resource/icon/png/shutdown/128.png differ diff --git a/resource/icon/png/shutdown/16.png b/resource/icon/png/shutdown/16.png new file mode 100644 index 0000000..03d4583 Binary files /dev/null and b/resource/icon/png/shutdown/16.png differ diff --git a/resource/icon/png/shutdown/256.png b/resource/icon/png/shutdown/256.png new file mode 100644 index 0000000..534913f Binary files /dev/null and b/resource/icon/png/shutdown/256.png differ diff --git a/resource/icon/png/shutdown/32.png b/resource/icon/png/shutdown/32.png new file mode 100644 index 0000000..5897504 Binary files /dev/null and b/resource/icon/png/shutdown/32.png differ diff --git a/resource/icon/png/shutdown/512.png b/resource/icon/png/shutdown/512.png new file mode 100644 index 0000000..605ebb3 Binary files /dev/null and b/resource/icon/png/shutdown/512.png differ diff --git a/resource/icon/png/shutdown/64.png b/resource/icon/png/shutdown/64.png new file mode 100644 index 0000000..9f1262d Binary files /dev/null and b/resource/icon/png/shutdown/64.png differ diff --git a/script/download.cmd b/script/download.cmd new file mode 100644 index 0000000..6644a85 --- /dev/null +++ b/script/download.cmd @@ -0,0 +1,16 @@ +@echo off +set dir=%~dp0 +cd %dir% + +set download_url="" + +curl -L %download_url% -o %dir%\dislocker_client.zip + +mkdir %dir%\temp_ds +tar -xf %dir%\dislocker_client.zip -C %dir%\temp_ds + +mkdir C:\ProgramData\Dislocker +xcopy /e %dir%\temp_ds C:\ProgramData\Dislocker +rmdir /s /q %dir%\temp_ds +del %dir%\dislocker_client.zip +C:\ProgramData\Dislocker\setup.cmd \ No newline at end of file diff --git a/script/setup.cmd b/script/setup.cmd index bfbfa42..5855fb6 100644 --- a/script/setup.cmd +++ b/script/setup.cmd @@ -16,6 +16,11 @@ if %ERRORLEVEL% == 0 ( if %ERRORLEVEL% == 1 ( echo V[gJbg̍쐬ŃG[܂B ) -set /P pc_number=PCԍ -start %dir%dislocker_client.exe setup %pc_number% + +set /P pc_number=PCԍ +set /P onetime=^CpX[h +set /P host_url=zXgURL (Kvȏꍇ̂) + +start %dir%dislocker_client.exe setup %pc_number% %onetime% %host_url% + pause \ No newline at end of file diff --git a/script/update.cmd b/script/update.cmd new file mode 100644 index 0000000..ccb404a --- /dev/null +++ b/script/update.cmd @@ -0,0 +1,19 @@ +@echo off +set dir=%~dp0 +cd %dir% + +set update_package_path="0" +set /P update_package_path=Abvf[gzipt@C̃pX : +if %update_package_path%=="0" (set update_package_path=C:%HOMEPATH%\Downloads\dislocker_client_latest.zip) +set dislocker_dir_path="0" +set /P dislocker_dir_path=Dislocker̃fBNg̃pX : +if %dislocker_dir_path%=="0" (set dislocker_dir_path=C:\Dislocker) +mkdir %dir%\temp_ds +tar -xf %update_package_path% -C %dir%\temp_ds +rmdir /s /q %dislocker_dir_path%\_internal +mkdir %dislocker_dir_path%\_internal +xcopy /e %dir%\temp_ds\_internal %dislocker_dir_path%\_internal +xcopy /Y %dir%\temp_ds\dislocker_client.exe %dislocker_dir_path%\dislocker_client.exe +rmdir /s /q %dir%\temp_ds +echo Abvf[gBDefendeřx߁AxNĂĂB +pause \ No newline at end of file diff --git a/script/update_online.cmd b/script/update_online.cmd new file mode 100644 index 0000000..dd44704 --- /dev/null +++ b/script/update_online.cmd @@ -0,0 +1,24 @@ +@echo off +set dir=%~dp0 +cd %dir% + +set download_url="" + +taskkill /f /t /im dislocker_client_shutdown.exe +taskkill /f /t /im dislocker_client.exe + +curl -L %download_url% -o %dir%\dislocker_client.zip + +mkdir %dir%\temp_ds\ +tar -xf %dir%\dislocker_client.zip -C %dir%\temp_ds\ + +rmdir /s /q C:\ProgramData\Dislocker\_internal\ +xcopy /e %dir%\temp_ds\_internal\ C:\ProgramData\Dislocker\_internal\ +xcopy /Y %dir%\temp_ds\dislocker_client.exe C:\ProgramData\Dislocker\dislocker_client.exe +xcopy /Y %dir%\temp_ds\dislocker_client_shutdown.exe C:\ProgramData\Dislocker\dislocker_client_shutdown.exe +xcopy /Y %dir%\temp_ds\shortcut.vbs C:\ProgramData\Dislocker\shortcut.vbs +xcopy /Y %dir%\temp_ds\setup.cmd C:\ProgramData\Dislocker\setup.cmd +rmdir /s /q %dir%\temp_ds\ +del %dir%\dislocker_client.zip +echo Abvf[gBDefendeřx߁AxNĂĂB +pause \ No newline at end of file