Compare commits

...

33 commits

Author SHA1 Message Date
7fc3ca701c 大幅な仕様変更のためtestingをmainにマージ 2024-08-22 22:46:41 +09:00
66f39eb293 ウィンドウのアイコンを適用できるように 2024-08-22 11:46:52 +09:00
19cf8e195c 多重起動防止の処理をロールバック 2024-08-22 11:18:04 +09:00
9cb5f22cfc ボタンの色を修正
init周りを修正
2024-08-21 13:21:08 +09:00
d7094656a3 アイコンのパスを修正 2024-08-21 13:11:29 +09:00
19afc4a57a issue #7 の解決案(ボタン無効化)を適用 2024-08-21 12:59:45 +09:00
9dc9938732 READMEを更新 2024-08-21 12:16:50 +09:00
04ae26862f clientの動作確認用 2024-08-21 12:16:41 +09:00
111686c257 念のため他のテーブルの型も修正 2024-08-19 22:57:07 +09:00
8a88a1a31f ユーザー登録時に文字数超過のエラーが出ることへの暫定的な対応 2024-08-19 10:01:49 +09:00
8019674b13 Monitorのpc_listのprintを無効化 2024-08-16 13:23:12 +09:00
60d4fc9c81 MonitorのResultがNONEだった時のログを出力しないように 2024-08-16 13:15:10 +09:00
7a1aa6a7db configファイルを明示的にUTF-8で読み書きするように 2024-08-15 22:46:55 +09:00
f7ecdc535f monitorの時間類の設定をconfigファイルへ移動 2024-08-15 22:41:38 +09:00
3073f12e6c 多重起動防止の処理をいったんやめにする 2024-08-14 00:03:47 +09:00
f304346426 initのif文を修正 2024-08-13 14:43:47 +09:00
b5fc778715 fstopに理由を要求するように
使用停止忘れのための停止処理を追加
2024-08-11 15:25:01 +09:00
3aad819485 生成されるconfigファイルの内容を合わせる 2024-08-10 18:47:16 +09:00
c55fd3162b データベースの環境変数をenvファイルに移動 2024-08-10 18:33:48 +09:00
7f92544102 volumeが逆だったので修正 2024-08-10 18:30:12 +09:00
dca3cad736 それぞれのDockerfileとcompose.ymlを追加 2024-08-10 18:27:24 +09:00
a10f5c47e9 Flaskのデバッグモードを明示的に無効化 2024-08-10 18:21:35 +09:00
ba9f227e09 タイムスタンプのバグを修正
自動停止処理が時間をおいて起動するように
2024-08-10 18:10:35 +09:00
b9d9e797d3 環境変数をミスってたので修正 2024-08-10 17:38:09 +09:00
a9d15357c4 PCの使用履歴のシートを除外 2024-08-10 17:37:49 +09:00
2663ad2ff6 ユーザーとして登録されていないときに停止ボタンを押したときに内部エラーと表示される仕様を変更
定期監視の一部仕様変更
2024-08-10 17:32:14 +09:00
425edead34 Dockerで動かす用 2024-08-10 17:06:53 +09:00
c4b4718583 終了処理にself忘れてた 2024-08-09 11:30:03 +09:00
16ea317730 引数の名前修正 2024-08-09 11:09:06 +09:00
8deb85e9fb 停止処理をできるように 2024-08-09 10:49:48 +09:00
b47305439c Riotのデータを削除するように 2024-08-08 00:31:34 +09:00
8e8c052b0c 多重起動防止のための処理追加 2024-08-07 11:37:23 +09:00
b5285c0f21 EAとSteamのデータを削除するように 2024-08-07 10:42:43 +09:00
11 changed files with 370 additions and 121 deletions

4
.gitignore vendored
View file

@ -162,4 +162,6 @@ cython_debug/
config/ config/
db/ db/
test.py test.py
data/
export/

22
Dockerfile_auth Normal file
View file

@ -0,0 +1,22 @@
FROM python:3
USER root
RUN mkdir /dislocker
RUN apt-get update
RUN apt-get -y install locales && \
localedef -f UTF-8 -i ja_JP ja_JP.UTF-8
ENV LANG ja_JP.UTF-8
ENV LANGUAGE ja_JP:ja
ENV LC_ALL ja_JP.UTF-8
ENV TZ JST-9
ENV TERM xterm
RUN apt-get install -y nano less
RUN pip install --upgrade pip
RUN pip install --upgrade setuptools
RUN python -m pip install flask psycopg2-binary requests
WORKDIR /dislocker
CMD python -u ./dislocker_auth.py

22
Dockerfile_bot Normal file
View file

@ -0,0 +1,22 @@
FROM python:3
USER root
RUN mkdir /dislocker
RUN apt-get update
RUN apt-get -y install locales && \
localedef -f UTF-8 -i ja_JP ja_JP.UTF-8
ENV LANG ja_JP.UTF-8
ENV LANGUAGE ja_JP:ja
ENV LC_ALL ja_JP.UTF-8
ENV TZ JST-9
ENV TERM xterm
RUN apt-get install -y nano less
RUN pip install --upgrade pip
RUN pip install --upgrade setuptools
RUN python -m pip install discord.py psycopg2-binary requests openpyxl
WORKDIR /dislocker
CMD python -u ./dislocker.py

View file

@ -1,2 +1,9 @@
# Dislocker # Dislocker
課題研究用リポジトリ
# 環境構築
## サーバー側
基本的にはDocker上での起動を推奨します。
このリポジトリをクローンし、`docker compose up -d`で起動すると一式のコンテナが起動します。
データベースだけを起動したい場合は、ファイルに`compose_db.yml`を指定してください。
## クライアント側
pyinstallerでビルドしたものを、起動してください。

45
compose.yml Normal file
View file

@ -0,0 +1,45 @@
services:
bot:
build:
context: "./"
dockerfile: "Dockerfile_bot"
restart: always
environment:
- TZ=Asia/Tokyo
depends_on:
- db
volumes:
- ./:/dislocker
networks:
- dislocker_network
auth:
build:
context: "./"
dockerfile: "Dockerfile_auth"
restart: always
environment:
- TZ=Asia/Tokyo
volumes:
- ./:/dislocker
ports:
- 12244:5000
networks:
- dislocker_network
db:
image: postgres:alpine3.20
restart: always
environment:
- TZ=Asia/Tokyo
volumes:
- ./data/db:/var/lib/postgresql/data
ports:
- 12245:5432
env_file:
- ./data/.env
networks:
- dislocker_network
networks:
dislocker_network:

18
compose_db.yml Normal file
View file

@ -0,0 +1,18 @@
services:
db:
image: postgres:alpine3.20
restart: always
environment:
- TZ=Asia/Tokyo
- POSTGRES_DB=dislocker
- POSTGRES_USER=dislocker
- POSTGRES_PASSWORD=Password
volumes:
- ./data/db:/var/lib/postgresql/data
ports:
- 12245:5432
networks:
- dislocker_network
networks:
dislocker_network:

View file

@ -43,16 +43,21 @@ class DL():
}, },
"log_channel_id" : "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", "log_channel_id" : "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)",
"config_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 !!!!)" "config_public_channel_id": "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)",
"monitor": {
"search_frequency": 1,
"allowable_time": 180,
"fstop_time": "21:00:00"
}
} }
} }
with open(self.server_config_path, "w") as w: with open(self.server_config_path, "w", encoding="utf-8") as w:
json.dump(self.server_config, w, indent=4) json.dump(self.server_config, w, indent=4, ensure_ascii=False)
elif os.path.isfile(self.server_config_path): elif os.path.isfile(self.server_config_path):
with open(self.server_config_path, "r") as r: with open(self.server_config_path, "r", encoding="utf-8") as r:
self.server_config = json.load(r) self.server_config = json.load(r)
print("config ファイルを読み込みました。") print("config ファイルを読み込みました。")
@ -68,11 +73,13 @@ class DL():
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']}") 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() cursor = self.db.cursor()
self.pc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
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() find_club_member_table = cursor.fetchall()
print(find_club_member_table) print(find_club_member_table)
if find_club_member_table[0][0] == False: if find_club_member_table[0][0] == False:
cursor.execute("CREATE TABLE club_member (id SERIAL NOT NULL, name VARCHAR(30) NOT NULL, discord_username VARCHAR(32) NOT NULL, discord_userid VARCHAR(18) NOT NULL, PRIMARY KEY (id))") 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))")
self.db.commit() 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')")
@ -89,7 +96,7 @@ class DL():
find_pc_usage_history_table = cursor.fetchall() find_pc_usage_history_table = cursor.fetchall()
print(find_pc_usage_history_table) print(find_pc_usage_history_table)
if find_pc_usage_history_table[0][0] == False: 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(30), 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, 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))")
self.db.commit() self.db.commit()
cursor.close() cursor.close()
@ -155,10 +162,10 @@ class Bot(discord.Client):
result = {"result": "pc_already_in_use_by_other"} result = {"result": "pc_already_in_use_by_other"}
else: else:
if user_info["detail"] == None: 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, current_timestamp)", (user_record[0][0], user_info["pc_number"], user_info["device_number"])) 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: else:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, current_timestamp, %s)", (user_record[0][0], user_info["pc_number"], user_info["device_number"], user_info["detail"])) 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 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"])) cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"]))
@ -173,10 +180,10 @@ class Bot(discord.Client):
result = {"result": "pc_already_in_use_by_other"} result = {"result": "pc_already_in_use_by_other"}
else: else:
if user_info["detail"] == None: 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, current_timestamp)", (user_record[0][0], user_info["pc_number"], user_info["device_number"])) 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: else:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, current_timestamp, %s)", (user_record[0][0], user_info["pc_number"], user_info["device_number"], user_info["detail"])) 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 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"])) cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"]))
@ -184,10 +191,10 @@ class Bot(discord.Client):
result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])} result = {"result": "ok", "password": str(password), "name": str(user_record[0][1])}
else: else:
if user_info["detail"] == None: 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, current_timestamp)", (user_record[0][0], user_info["pc_number"], user_info["device_number"])) 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: else:
cursor.execute("INSERT INTO pc_usage_history (member_id, pc_number, device_number, start_use_time, use_detail) VALUES (%s, %s, %s, current_timestamp, %s)", (user_record[0][0], user_info["pc_number"], user_info["device_number"], user_info["detail"])) 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 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"])) cursor.execute("UPDATE pc_list SET password_hash = %s WHERE pc_number = %s", (password_hash, user_info["pc_number"]))
@ -209,20 +216,32 @@ class Bot(discord.Client):
def stop(self, **kwargs): def stop(self, **kwargs):
try: try:
discord_user_id = str(kwargs["user_id"]) discord_user_id = str(kwargs["user_id"])
if "bot_about" in kwargs:
bot_about = kwargs["bot_about"]
else:
bot_about = None
cursor = dislocker.db.cursor() cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,)) cursor.execute("SELECT * FROM club_member WHERE discord_userid = %s", (discord_user_id,))
user_record = cursor.fetchall() user_record = cursor.fetchall()
cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (user_record[0][0],)) if user_record:
pc_usage_history_record = cursor.fetchall() cursor.execute("SELECT * FROM pc_usage_history WHERE member_id= %s ORDER BY id DESC LIMIT 1", (user_record[0][0],))
if pc_usage_history_record: pc_usage_history_record = cursor.fetchall()
if not pc_usage_history_record[0][5] == None: if pc_usage_history_record:
result = {"result": "unused"} 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],))
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])}
else: else:
cursor.execute("UPDATE pc_usage_history SET end_use_time = current_timestamp WHERE id = %s", (pc_usage_history_record[0][0],)) result = {"result": "unused"}
cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],)) else:
cursor.execute("UPDATE pc_list SET password_hash = NULL WHERE pc_number = %s", (pc_usage_history_record[0][2],)) result = {"result": "user_data_not_found"}
dislocker.db.commit()
result = {"result": "ok", "pc_number": str(pc_usage_history_record[0][2]), "name": str(user_record[0][1])}
except: except:
print("停止処理にエラーが発生しました。") print("停止処理にエラーが発生しました。")
result = {"result": "error"} result = {"result": "error"}
@ -360,23 +379,29 @@ class Bot(discord.Client):
def force_stop(self, **kwargs): def force_stop(self, **kwargs):
try: try:
pc_number = kwargs["pc_number"] pc_number = kwargs["pc_number"]
cursor = dislocker.db.cursor() if "bot_about" in kwargs:
cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,)) bot_about = kwargs["bot_about"]
pc_list_record = cursor.fetchall() cursor = dislocker.db.cursor()
if not pc_list_record[0][1] == None: cursor.execute("SELECT * FROM pc_list WHERE pc_number = %s", (pc_number,))
cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_number,)) pc_list_record = cursor.fetchall()
if not pc_list_record[0][1] == None:
if not pc_list_record[0][2] == None: cursor.execute("UPDATE pc_list SET using_user_id = NULL WHERE pc_number = %s", (pc_number,))
cursor.execute("UPDATE pc_list SET password_hash = 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)) 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() 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],)) 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() dislocker.db.commit()
result = {"result": "ok"} result = {"result": "ok"}
else:
result = {"result": "not_used"}
else: else:
result = {"result": "not_used"} bot_about = None
result = {"result": "bot_about_not_found"}
except: except:
result = {"result": "error"} result = {"result": "error"}
@ -509,7 +534,7 @@ class Bot(discord.Client):
await message.channel.send("# :warning: 登録を解除できませんでした。\n使用を停止したいPC番号を指定してください。\n-# /fstop PC番号") await message.channel.send("# :warning: 登録を解除できませんでした。\n使用を停止したいPC番号を指定してください。\n-# /fstop PC番号")
elif len(msg_split) == 2: elif len(msg_split) == 2:
if msg_split[1].isdigit(): if msg_split[1].isdigit():
fstop = self.force_stop(pc_number=msg_split[1]) fstop = self.force_stop(pc_number=msg_split[1], bot_about="管理者による強制停止。")
if fstop["result"] == "ok": if fstop["result"] == "ok":
await message.channel.send(f"# :white_check_mark: PC番号 {msg_split[1]} の使用登録を解除しました。") await message.channel.send(f"# :white_check_mark: PC番号 {msg_split[1]} の使用登録を解除しました。")
elif fstop["result"] == "not_used": elif fstop["result"] == "not_used":
@ -615,6 +640,8 @@ class Bot(discord.Client):
stop_view = View(timeout=15) stop_view = View(timeout=15)
if pc_stop["result"] == "unused": if pc_stop["result"] == "unused":
await interaction.response.send_message("# :shaking_face: 使用されていないようです...", ephemeral=True) 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": elif pc_stop["result"] == "ok":
await interaction.response.send_message(f":white_check_mark: PC番号 {pc_stop["pc_number"]} の使用が終了されました。", ephemeral=True) 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"]} の使用を終了しました。') 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"]} の使用を終了しました。')
@ -632,81 +659,88 @@ class Bot(discord.Client):
await interaction.response.send_message("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True) await interaction.response.send_message("# :no_entry: 登録できませんでした。\n内部エラーが発生しています。", ephemeral=True)
class Monitor(): class Monitor():
def __init__(self) -> None: def __init__(self, **kwargs) -> None:
pass 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): def start(self, **kwargs):
self.serach_time = kwargs["search_time"] search_thread = threading.Thread(target=self.search)
self.allowable_time = kwargs["allowable_time"] search_thread.start()
serach_thread = threading.Thread(target=self.search)
serach_thread.start()
def search(self): def search(self):
try: try:
time.sleep(self.init_wait_time)
while True: while True:
cursor = dislocker.db.cursor() cursor = dislocker.db.cursor()
cursor.execute("SELECT * FROM pc_list WHERE password_hash IS NOT NULL") cursor.execute("SELECT * FROM pc_list WHERE password_hash IS NOT NULL")
pc_list = cursor.fetchall() pc_list = cursor.fetchall()
print(pc_list) current_datetime = datetime.now()
print(len(pc_list)) fstop_time = self.fstop_time
if pc_list: if current_datetime.time().strftime("%H:%M:%S") == fstop_time:
if len(pc_list) == 1: for i in dislocker.pc_list:
user_id = pc_list[0][1] stop = bot.force_stop(pc_number=i, bot_about="使用停止忘れによるBotによる強制停止。")
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,)) result = {"result": "FSTOP"}
pc_usage = cursor.fetchall() else:
print(pc_usage) if pc_list:
start_time = pc_usage[0][4] if len(pc_list) == 1:
print(start_time) user_id = pc_list[0][1]
print(type(start_time))
current_time = datetime.now()
time_difference = current_time - start_time
print(current_time, 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.timeout_notify(pc_number=pc_list[0][0], discord_display_name=user_info[0][1])
time.sleep(1)
else:
result = {"result": "BUT SAFE"}
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,)) 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() pc_usage = cursor.fetchall()
print(pc_usage) print(pc_usage)
start_time = pc_usage[0][4] start_time = pc_usage[0][4]
print(start_time) print(start_time)
print(type(start_time)) print(type(start_time))
current_time = datetime.now() time_difference = current_datetime - start_time
time_difference = current_time - start_time print(current_datetime, start_time)
print(time_difference.seconds, timedelta(seconds=self.allowable_time).seconds) print(time_difference.seconds, timedelta(seconds=self.allowable_time).seconds)
if 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,)) cursor.execute("SELECT * FROM club_member WHERE id = %s", (user_id,))
user_info = cursor.fetchall() user_info = cursor.fetchall()
stop = bot.stop(user_id=user_info[0][3]) 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]) bot.timeout_notify(pc_number=pc_list[0][0], discord_display_name=user_info[0][1])
time.sleep(0.1) result = {"result": "STOP", "details": str(pc_usage)}
else: else:
result = {"result": "BUT SAFE"} 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: else:
result = {"result": "NONE"} result = {"result": "NONE"}
if result["result"] == "NONE":
pass
else: else:
result = {"result": "NONE"} print(current_datetime)
print(result["result"])
time.sleep(self.search_frequency)
cursor.close()
print(result["result"])
time.sleep(self.serach_time)
except Exception as error: except Exception as error:
print("自動停止処理中にエラーが発生しました。\nエラー内容") print("自動停止処理中にエラーが発生しました。\nエラー内容")
@ -760,8 +794,8 @@ if dislocker.init_result == "ok":
intents = discord.Intents.default() intents = discord.Intents.default()
intents.message_content = True intents.message_content = True
bot = Bot(intents=intents) bot = Bot(intents=intents)
monitor = Monitor() 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(search_time=10, allowable_time=300) monitor.start()
bot.run(dislocker.server_config['bot']['token']) bot.run(dislocker.server_config['bot']['token'])
else: else:
pass pass

View file

@ -19,8 +19,15 @@ if not os.path.isfile(server_config_path):
}, },
"bot": { "bot": {
"token": "TYPE HERE BOTS TOKEN KEY", "token": "TYPE HERE BOTS TOKEN KEY",
"activity": {
"name": "Dislocker",
"details": "ロック中...",
"type": "playing",
"state": "ロック中..."
},
"log_channel_id" : "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)", "log_channel_id" : "TYPE HERE CHANNEL ID (YOU MUST USE INT !!!!)",
"config_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 !!!!)"
} }
} }
with open(server_config_path, "w") as w: with open(server_config_path, "w") as w:
@ -115,4 +122,4 @@ def stop():
if __name__ == '__main__': if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True) app.run(host="0.0.0.0", port=5000, debug=False)

View file

@ -20,6 +20,7 @@ dislocker_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(dislocker_dir) os.chdir(dislocker_dir)
resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource")
config_dir_path = "./config/" config_dir_path = "./config/"
client_config_path = config_dir_path + "client.json" client_config_path = config_dir_path + "client.json"
if not os.path.isfile(client_config_path): if not os.path.isfile(client_config_path):
@ -39,22 +40,38 @@ elif os.path.isfile(client_config_path):
client_config = json.load(r) client_config = json.load(r)
def init(**kwargs): def init(**kwargs):
master_password = master_password_gen() sp_startupinfo = subprocess.STARTUPINFO()
msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 初回起動を検出", message=f"初回起動のようです。\nマスターパスワードを記録しておいてください。\nこれ以降二度と表示されることはないでしょう。\n\n{master_password["password"]}\n\nまた、認証先サーバーの接続先を指定してください。ロックを解除できなくなります。") sp_startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
client_config["master_password_hash"] = master_password["password_hash"] sp_startupinfo.wShowWindow = subprocess.SW_HIDE
client_config["initial"] = 0 task_exist = subprocess.run('tasklist /fi "IMAGENAME eq dislocker_client.exe"', startupinfo=sp_startupinfo, stdout=subprocess.PIPE, text=True)
if "pc_number" in kwargs: if 'dislocker_client.exe' in task_exist.stdout:
client_config["pc_number"] = int(kwargs["pc_number"]) task_count = task_exist.stdout.count("dislocker_client.exe")
if task_count == 1:
pass
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 "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
else: else:
client_config["pc_number"] = 1 return 0
with open(client_config_path, "w") as w:
json.dump(client_config, w, indent=4)
class App(customtkinter.CTk): class App(customtkinter.CTk):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.title(f"{app_name} | ロック中") self.title(f"{app_name} | ロック中")
self.iconbitmap(default=resource_path + '\\icon\\dislocker.ico')
if client_config["testing"] == 1: if client_config["testing"] == 1:
pass pass
else: else:
@ -73,7 +90,7 @@ class App(customtkinter.CTk):
self.toast() self.toast()
self.destroy() self.destroy()
def delete_appdata(**kwargs): def delete_appdata(self, **kwargs):
process_name = kwargs["process_name"] process_name = kwargs["process_name"]
dir_path = kwargs["dir_path"] dir_path = kwargs["dir_path"]
@ -118,7 +135,6 @@ class App(customtkinter.CTk):
print(unlock) print(unlock)
def toast(self): def toast(self):
resource_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource")
success = Notification( success = Notification(
app_id='Dislocker', app_id='Dislocker',
title='ご協力ありがとうございます!', title='ご協力ありがとうございます!',
@ -140,6 +156,7 @@ class Lock(customtkinter.CTkToplevel):
else: else:
self.title(f'{app_name} | PC番号 {client_config["pc_number"]} | ロックされています') 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 = 600
self.window_height = 320 self.window_height = 320
self.screen_width = self.winfo_screenwidth() self.screen_width = self.winfo_screenwidth()
@ -202,11 +219,11 @@ class Lock(customtkinter.CTkToplevel):
self.signin_button = customtkinter.CTkButton(self.button_frame, text='サインイン', command=self.auth_start, font=self.button_font) 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.signin_button.grid(row=0, column=2, padx=10, sticky="e")
self.logout_button = customtkinter.CTkButton(self.button_frame, text='サインアウト', command=self.logout, font=self.button_font) self.signout_button = customtkinter.CTkButton(self.button_frame, text='サインアウト', command=self.signout, font=self.button_font)
self.logout_button.grid(row=0, column=1, padx=10, sticky="e") self.signout_button.grid(row=0, column=1, padx=10, sticky="e")
self.signin_button = customtkinter.CTkButton(self.button_frame, text='ヘルプ', command=self.help_dummy, font=self.button_font) self.help_button = customtkinter.CTkButton(self.button_frame, text='ヘルプ', command=self.help_dummy, font=self.button_font)
self.signin_button.grid(row=0, column=0, padx=10, sticky="w") self.help_button.grid(row=0, column=0, padx=10, sticky="w")
self.keyboard_listener_thread = threading.Thread(target=self.keyboard_listener) self.keyboard_listener_thread = threading.Thread(target=self.keyboard_listener)
self.keyboard_listener_thread.daemon = True self.keyboard_listener_thread.daemon = True
@ -232,8 +249,19 @@ class Lock(customtkinter.CTkToplevel):
auth_thread.daemon = True auth_thread.daemon = True
auth_thread.start() 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): def auth(self):
self.button_disable()
password = str(self.password_entry.get()) password = str(self.password_entry.get())
if len(password) == 10: if len(password) == 10:
print("マスターパスワードで認証を試行します。") print("マスターパスワードで認証を試行します。")
@ -243,6 +271,11 @@ class Lock(customtkinter.CTkToplevel):
self.exit() self.exit()
else: else:
print("マスターパスワードで認証できませんでした。") 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("認証サーバーにアクセスします。") print("認証サーバーにアクセスします。")
@ -261,9 +294,8 @@ class Lock(customtkinter.CTkToplevel):
self.withdraw() self.withdraw()
msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 誤ったパスワード", message=f"パスワードが間違っています!") msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | 誤ったパスワード", message=f"パスワードが間違っています!")
self.msg_subtitle_1.configure(text='パスワードが間違っています! ') self.msg_subtitle_1.configure(text='パスワードが間違っています! ')
self.button_enable()
self.deiconify() self.deiconify()
except: except:
print("認証サーバーにアクセスできません。マスターパスワードで認証を試行します。") print("認証サーバーにアクセスできません。マスターパスワードで認証を試行します。")
master_password_hash = self.hash_genarate(str(self.password_entry.get())) master_password_hash = self.hash_genarate(str(self.password_entry.get()))
@ -275,13 +307,14 @@ class Lock(customtkinter.CTkToplevel):
self.withdraw() self.withdraw()
msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | ネットワークエラー", message=f"認証サーバーにアクセスできませんでした。\n続行するには、マスターパスワードを入力してください。") msgbox = tkinter.messagebox.showinfo(title=f"{app_name} | ネットワークエラー", message=f"認証サーバーにアクセスできませんでした。\n続行するには、マスターパスワードを入力してください。")
self.msg_subtitle_1.configure(text='ネットワークエラーが発生しています。\n続行するには、マスターパスワードを入力して下さい。 ') self.msg_subtitle_1.configure(text='ネットワークエラーが発生しています。\n続行するには、マスターパスワードを入力して下さい。 ')
self.button_enable()
self.deiconify() self.deiconify()
def logout(self): def signout(self):
app.unlock_taskmgr() app.unlock_taskmgr()
self.destroy() self.destroy()
logout_command = subprocess.run(['shutdown', '/l', '/f']) signout_command = subprocess.run(['shutdown', '/l', '/f'])
print(logout_command) print(signout_command)
def handler_close(self): def handler_close(self):
@ -304,7 +337,7 @@ class Help(customtkinter.CTkToplevel):
self.title(f'{app_name} | ヘルプ | テストモード') self.title(f'{app_name} | ヘルプ | テストモード')
else: else:
self.title(f'{app_name} | ヘルプ') self.title(f'{app_name} | ヘルプ')
self.iconbitmap("./resource/icon/dislocker.ico") self.iconbitmap(default=resource_path + '\\icon\\dislocker.ico')
self.geometry("600x400") self.geometry("600x400")
self.resizable(height=False, width=False) self.resizable(height=False, width=False)
self.attributes('-topmost', True) self.attributes('-topmost', True)
@ -332,6 +365,9 @@ class Monitor():
epic_del = app.delete_appdata(process_name="EpicGamesLauncher.exe", dir_path=f"{appdata_local}\\EpicGamesLauncher\\Saved") 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") 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") 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")
stop_url = client_config["auth_host_url"] + "/stop" stop_url = client_config["auth_host_url"] + "/stop"
stop_json = { stop_json = {
"pc_number": int(client_config["pc_number"]) "pc_number": int(client_config["pc_number"])
@ -350,7 +386,7 @@ class Monitor():
self.shutdown() self.shutdown()
def shutdown(self): def shutdown(self):
logout_command = subprocess.run(['shutdown', '/s', '/t', '1']) shutdown_command = subprocess.run(['shutdown', '/s', '/t', '1'])
def run(self): def run(self):
@ -369,15 +405,31 @@ if __name__ == '__main__':
args = sys.argv args = sys.argv
if len(args) >= 2: if len(args) >= 2:
if args[1] == "stop": if args[1] == "stop":
monitor = Monitor() init_result = init()
monitor.signal_handler() if init_result == 1:
warning_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | 多重起動エラー", message=f"もう終了処理を行っています。\nPCがシャットダウンするまで、もう少しお待ちください。")
elif init_result == 2:
pass
else:
app = App()
monitor = Monitor()
monitor.signal_handler()
elif args[1] == "setup": elif args[1] == "setup":
init(pc_number=args[2]) init_result = init(pc_number=args[2])
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: else:
print("引数エラー。") print("引数エラー。")
else: else:
if client_config["initial"] == 1: init_result = init()
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: else:
app = App() app = App()
app.protocol("WM_DELETE_WINDOW", app.handler_close) app.protocol("WM_DELETE_WINDOW", app.handler_close)

View file

@ -1 +1 @@
pyinstaller .\dislocker_client.py --noconsole --icon .\dislocker.ico --add-data ".\resource:resource" pyinstaller .\dislocker_client.py --noconsole --icon .\resource\icon\dislocker.ico --add-data ".\resource:resource"

40
temp/client_playground.py Normal file
View file

@ -0,0 +1,40 @@
import os
import subprocess
import shutil
def delete_appdata(**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} を終了しました。")
# ディレクトリの削除
shutil.rmtree(dir_path)
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
appdata_local = os.path.expandvars("%LOCALAPPDATA%")
appdata_roaming = os.path.expandvars("%APPDATA%")
print(appdata_local, appdata_roaming)
print(f"{appdata_local}\\Steam")
steam_del = delete_appdata(process_name="steam.exe", dir_path=f"{appdata_local}\\Steam")