Compare commits
55 commits
Author | SHA1 | Date | |
---|---|---|---|
84d1b0cb59 | |||
9389441262 | |||
45d6b9f3c8 | |||
45b1b767ac | |||
8658955998 | |||
8ade781d4b | |||
cf47a5b2ad | |||
c08afa08c3 | |||
5a709197e7 | |||
487dfbd96d | |||
7fc3ca701c | |||
66f39eb293 | |||
19cf8e195c | |||
9cb5f22cfc | |||
d7094656a3 | |||
19afc4a57a | |||
9dc9938732 | |||
04ae26862f | |||
111686c257 | |||
8a88a1a31f | |||
8019674b13 | |||
60d4fc9c81 | |||
7a1aa6a7db | |||
f7ecdc535f | |||
3073f12e6c | |||
f304346426 | |||
b5fc778715 | |||
3aad819485 | |||
c55fd3162b | |||
7f92544102 | |||
dca3cad736 | |||
a10f5c47e9 | |||
ba9f227e09 | |||
b9d9e797d3 | |||
a9d15357c4 | |||
2663ad2ff6 | |||
425edead34 | |||
c4b4718583 | |||
16ea317730 | |||
8deb85e9fb | |||
b47305439c | |||
8e8c052b0c | |||
b5285c0f21 | |||
3bf7918bb4 | |||
a8f9ad0ec6 | |||
95e8855c27 | |||
a9109dba0a | |||
e48a0fc3c2 | |||
2edd37fbfd | |||
765a0bd2ba | |||
348fa96759 | |||
5a1ac0e3c1 | |||
5653b79906 | |||
db9afe38f2 | |||
1cc6d1d60f |
19 changed files with 527 additions and 398 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
@ -162,4 +162,7 @@ cython_debug/
|
||||||
|
|
||||||
config/
|
config/
|
||||||
db/
|
db/
|
||||||
test.py
|
test.py
|
||||||
|
data/
|
||||||
|
export/
|
||||||
|
temp/
|
22
Dockerfile_auth
Normal file
22
Dockerfile_auth
Normal 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
22
Dockerfile_bot
Normal 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
|
|
@ -1,2 +1,9 @@
|
||||||
# Dislocker
|
# Dislocker
|
||||||
|
課題研究用リポジトリ
|
||||||
|
# 環境構築
|
||||||
|
## サーバー側
|
||||||
|
基本的にはDocker上での起動を推奨します。
|
||||||
|
このリポジトリをクローンし、`docker compose up -d`で起動すると一式のコンテナが起動します。
|
||||||
|
データベースだけを起動したい場合は、ファイルに`compose_db.yml`を指定してください。
|
||||||
|
## クライアント側
|
||||||
|
pyinstallerでビルドしたものを、起動してください。
|
||||||
|
|
45
compose.yml
Normal file
45
compose.yml
Normal 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
18
compose_db.yml
Normal 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:
|
270
dislocker.py
270
dislocker.py
|
@ -35,18 +35,32 @@ class DL():
|
||||||
},
|
},
|
||||||
"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 !!!!)"
|
"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") 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 ファイルを読み込みました。")
|
||||||
|
|
||||||
|
@ -62,11 +76,14 @@ 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]
|
||||||
|
self.preset_games = self.server_config["bot"]["preset_games"]
|
||||||
|
|
||||||
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')")
|
||||||
|
@ -83,7 +100,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()
|
||||||
|
@ -149,10 +166,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"]))
|
||||||
|
@ -167,10 +184,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"]))
|
||||||
|
@ -178,10 +195,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"]))
|
||||||
|
@ -203,20 +220,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"}
|
||||||
|
@ -354,23 +383,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"}
|
||||||
|
@ -401,6 +436,13 @@ class Bot(discord.Client):
|
||||||
|
|
||||||
async def on_ready(self):
|
async def on_ready(self):
|
||||||
print("DiscordのBotが起動しました。")
|
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):
|
async def on_interaction(self, interaction:discord.Interaction):
|
||||||
try:
|
try:
|
||||||
|
@ -496,7 +538,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":
|
||||||
|
@ -577,6 +619,8 @@ class Bot(discord.Client):
|
||||||
for i in range(1, 11):
|
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_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_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)
|
||||||
|
|
||||||
await interaction.response.send_message(f"# :keyboard: デバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=device_register_view, ephemeral=True)
|
await interaction.response.send_message(f"# :keyboard: デバイス番号を選んでください!\n>>> # PC番号 | {str(pc_number)}", view=device_register_view, ephemeral=True)
|
||||||
|
|
||||||
|
@ -584,6 +628,9 @@ class Bot(discord.Client):
|
||||||
pc_number = custom_id_split[1]
|
pc_number = custom_id_split[1]
|
||||||
device_number = custom_id_split[2]
|
device_number = custom_id_split[2]
|
||||||
reason_register_view = View(timeout=15)
|
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_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)
|
reason_register_view.add_item(reason_button)
|
||||||
|
|
||||||
|
@ -592,8 +639,35 @@ class Bot(discord.Client):
|
||||||
elif custom_id_split[0] == "reasonregister":
|
elif custom_id_split[0] == "reasonregister":
|
||||||
pc_number = custom_id_split[1]
|
pc_number = custom_id_split[1]
|
||||||
device_number = custom_id_split[2]
|
device_number = custom_id_split[2]
|
||||||
reason_input_form = Reason(title="Dislocker | 登録", pc_number=str(pc_number), device_number=str(device_number))
|
|
||||||
await interaction.response.send_modal(reason_input_form)
|
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)
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
|
||||||
elif custom_id_split[0] == "stop":
|
elif custom_id_split[0] == "stop":
|
||||||
print("STOP running")
|
print("STOP running")
|
||||||
|
@ -602,6 +676,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"]} の使用を終了しました。')
|
||||||
|
@ -619,74 +695,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
|
|
||||||
if time_difference >= timedelta(seconds=self.allowable_time):
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
if time_difference >= timedelta(seconds=self.allowable_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,))
|
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:
|
||||||
|
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エラー内容")
|
||||||
|
@ -717,6 +807,12 @@ class Reason(Modal):
|
||||||
custom_id_split = custom_id.split("_")
|
custom_id_split = custom_id.split("_")
|
||||||
pc_number = custom_id_split[1]
|
pc_number = custom_id_split[1]
|
||||||
device_number = custom_id_split[2]
|
device_number = custom_id_split[2]
|
||||||
|
|
||||||
|
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=self.reason_input_form.value)
|
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"])
|
print(register["result"])
|
||||||
|
|
||||||
|
@ -740,8 +836,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
|
|
@ -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)
|
|
@ -11,14 +11,17 @@ import string
|
||||||
import random
|
import random
|
||||||
import tkinter
|
import tkinter
|
||||||
import threading
|
import threading
|
||||||
import signal
|
|
||||||
import sys
|
import sys
|
||||||
|
import shutil
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
app_name = "Dislocker"
|
app_name = "Dislocker"
|
||||||
dislocker_dir = os.getcwd()
|
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):
|
||||||
|
@ -30,7 +33,8 @@ if not os.path.isfile(client_config_path):
|
||||||
"auth_host_url": "http://localhost",
|
"auth_host_url": "http://localhost",
|
||||||
"pc_number": 1,
|
"pc_number": 1,
|
||||||
"master_password_hash": "",
|
"master_password_hash": "",
|
||||||
"testing": 0
|
"testing": 0,
|
||||||
|
"eraser": 1
|
||||||
}
|
}
|
||||||
|
|
||||||
elif os.path.isfile(client_config_path):
|
elif os.path.isfile(client_config_path):
|
||||||
|
@ -38,22 +42,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:
|
||||||
|
@ -72,6 +92,46 @@ class App(customtkinter.CTk):
|
||||||
self.toast()
|
self.toast()
|
||||||
self.destroy()
|
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):
|
def block_key(self):
|
||||||
block_keys = ['ctrl', 'alt', 'windows', 'shift', 'delete']
|
block_keys = ['ctrl', 'alt', 'windows', 'shift', 'delete']
|
||||||
for i in block_keys:
|
for i in block_keys:
|
||||||
|
@ -86,7 +146,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='ご協力ありがとうございます!',
|
||||||
|
@ -108,8 +167,9 @@ 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 = 400
|
self.window_height = 320
|
||||||
self.screen_width = self.winfo_screenwidth()
|
self.screen_width = self.winfo_screenwidth()
|
||||||
self.screen_height = self.winfo_screenheight()
|
self.screen_height = self.winfo_screenheight()
|
||||||
self.center_x = int(self.screen_width/2 - self.window_width/2)
|
self.center_x = int(self.screen_width/2 - self.window_width/2)
|
||||||
|
@ -123,11 +183,13 @@ class Lock(customtkinter.CTkToplevel):
|
||||||
|
|
||||||
self.emoji_font = customtkinter.CTkFont(family="Segoe UI Emoji", size=32)
|
self.emoji_font = customtkinter.CTkFont(family="Segoe UI Emoji", size=32)
|
||||||
self.title_font = customtkinter.CTkFont(family="meiryo", size=32, weight="bold")
|
self.title_font = customtkinter.CTkFont(family="meiryo", size=32, weight="bold")
|
||||||
|
self.pc_number_font = customtkinter.CTkFont(family="meiryo", size=64, weight="bold")
|
||||||
self.title_small_font = customtkinter.CTkFont(family="meiryo", size=16)
|
self.title_small_font = customtkinter.CTkFont(family="meiryo", size=16)
|
||||||
self.general_font = customtkinter.CTkFont(family="meiryo", size=18)
|
self.general_font = customtkinter.CTkFont(family="meiryo", size=18)
|
||||||
self.general_small_font = customtkinter.CTkFont(family="meiryo", size=12)
|
self.general_small_font = customtkinter.CTkFont(family="meiryo", size=12)
|
||||||
self.textbox_font = customtkinter.CTkFont(family="meiryo", size=14)
|
self.textbox_font = customtkinter.CTkFont(family="meiryo", size=14)
|
||||||
self.button_font = customtkinter.CTkFont(family="meiryo", size=14)
|
self.button_font = customtkinter.CTkFont(family="meiryo", size=14)
|
||||||
|
|
||||||
|
|
||||||
self.msg_title_frame = customtkinter.CTkFrame(self, corner_radius=0, fg_color='transparent')
|
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=0, padx=10, pady=10, sticky="nsew")
|
||||||
|
@ -135,7 +197,7 @@ class Lock(customtkinter.CTkToplevel):
|
||||||
self.icon_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text='😎', font=self.emoji_font, justify="left")
|
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.grid(row=0, column=0, padx=10, sticky="w")
|
||||||
|
|
||||||
self.msg_title_1 = customtkinter.CTkLabel(self.msg_title_frame, text='ちょっと待って!!', font=self.title_font, justify="left")
|
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.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 = customtkinter.CTkLabel(self.msg_title_frame, text="本当にあなたですか?", font=self.title_small_font, justify="left")
|
||||||
|
@ -168,11 +230,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
|
||||||
|
@ -198,8 +260,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("マスターパスワードで認証を試行します。")
|
||||||
|
@ -209,6 +282,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("認証サーバーにアクセスします。")
|
||||||
|
@ -227,9 +305,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()))
|
||||||
|
@ -241,13 +318,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):
|
||||||
|
@ -270,7 +348,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)
|
||||||
|
@ -282,17 +360,74 @@ class Help(customtkinter.CTkToplevel):
|
||||||
|
|
||||||
def handler_close(self):
|
def handler_close(self):
|
||||||
self.destroy()
|
self.destroy()
|
||||||
|
|
||||||
class Monitor():
|
|
||||||
|
class Stop():
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def start(self):
|
def run(self):
|
||||||
monitor_thread = threading.Thread(target=self.run)
|
stop_thread = threading.Thread(target=self.stop)
|
||||||
monitor_thread.start()
|
stop_thread.run()
|
||||||
|
|
||||||
def signal_handler(self):
|
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)}")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
shutdown_command = subprocess.run(['shutdown', '/s', '/t', '1'])
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
print("停止処理を実行。")
|
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")
|
||||||
|
else:
|
||||||
|
print("削除処理をスキップ。")
|
||||||
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"])
|
||||||
|
@ -303,19 +438,10 @@ class Monitor():
|
||||||
print("停止処理は成功しました。")
|
print("停止処理は成功しました。")
|
||||||
else:
|
else:
|
||||||
print("内部エラーにより停止処理に失敗しました。")
|
print("内部エラーにより停止処理に失敗しました。")
|
||||||
result_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"内部エラーにより停止処理に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。")
|
|
||||||
except:
|
except:
|
||||||
print("ネットワークエラーにより停止処理に失敗しました。")
|
print("ネットワークエラーにより停止処理に失敗しました。")
|
||||||
result_msgbox = tkinter.messagebox.showwarning(title=f"{app_name} | エラー", message=f"ネットワークエラーにより停止処理に失敗しました。\nDiscordサーバーの指示に従って、停止処理を自身で行ってください。")
|
|
||||||
finally:
|
finally:
|
||||||
self.shutdown()
|
self.shutdown()
|
||||||
|
|
||||||
def shutdown(self):
|
|
||||||
logout_command = subprocess.run(['shutdown', '/s', '/t', '1'])
|
|
||||||
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
signal.signal(signal.SIGTERM, self.signal_handler)
|
|
||||||
|
|
||||||
|
|
||||||
def master_password_gen():
|
def master_password_gen():
|
||||||
|
@ -330,15 +456,30 @@ 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:
|
||||||
|
print("多重起動エラー。")
|
||||||
|
elif init_result == 2:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
stop = Stop()
|
||||||
|
stop.run()
|
||||||
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)
|
||||||
|
|
1
docs/pyinstaller.txt
Normal file
1
docs/pyinstaller.txt
Normal file
|
@ -0,0 +1 @@
|
||||||
|
pyinstaller .\dislocker_client.py --noconsole --icon .\resource\icon\dislocker.ico --add-data ".\resource:resource"
|
21
script/setup.cmd
Normal file
21
script/setup.cmd
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
@echo off
|
||||||
|
set dir=%~dp0
|
||||||
|
cd %dir%
|
||||||
|
schtasks /create /tn "Dislocker_Client" /tr "%dir%dislocker_client.exe" /sc onlogon /ru "%USERNAME%" /rl highest /f
|
||||||
|
if %ERRORLEVEL% == 0 (
|
||||||
|
echo タスクスケジューラーの設定は完了しました。
|
||||||
|
)
|
||||||
|
if %ERRORLEVEL% == 1 (
|
||||||
|
echo タスクスケジューラーの設定でエラーが発生しました。
|
||||||
|
)
|
||||||
|
Cscript "%dir%shortcut.vbs" "%dir%" "%dir%" "dislocker_client.exe" "stop" "シャットダウンと停止処理"
|
||||||
|
if %ERRORLEVEL% == 0 (
|
||||||
|
Cscript "%dir%shortcut.vbs" "%USERPROFILE%/Desktop" "%dir%" "dislocker_client.exe" "stop" "シャットダウンと停止処理"
|
||||||
|
echo ショートカットの作成は完了しました。
|
||||||
|
)
|
||||||
|
if %ERRORLEVEL% == 1 (
|
||||||
|
echo ショートカットの作成でエラーが発生しました。
|
||||||
|
)
|
||||||
|
set /P pc_number=PC番号を入力
|
||||||
|
start %dir%dislocker_client.exe setup %pc_number%
|
||||||
|
pause
|
8
script/shortcut.vbs
Normal file
8
script/shortcut.vbs
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
Set WshShell = CreateObject("WScript.Shell")
|
||||||
|
Set args = Wscript.Arguments
|
||||||
|
Set Shortcut = WshShell.CreateShortcut(args(0) & "\シャットダウンと終了処理.lnk")
|
||||||
|
Shortcut.TargetPath = args(1) & args(2)
|
||||||
|
Shortcut.Arguments = args(3)
|
||||||
|
Shortcut.WorkingDirectory = args(1)
|
||||||
|
Shortcut.Save
|
||||||
|
WScript.Quit(0)
|
|
@ -1,77 +0,0 @@
|
||||||
import psycopg2
|
|
||||||
import csv
|
|
||||||
from psycopg2 import sql
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
def format_datetime(value):
|
|
||||||
if isinstance(value, datetime):
|
|
||||||
return value.strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
return value
|
|
||||||
|
|
||||||
def export_table_to_csv(host, port, database, user, password, main_table, related_table, related_column, csv_file_path):
|
|
||||||
try:
|
|
||||||
# データベースに接続
|
|
||||||
conn = psycopg2.connect(
|
|
||||||
host=host,
|
|
||||||
port=port,
|
|
||||||
database=database,
|
|
||||||
user=user,
|
|
||||||
password=password
|
|
||||||
)
|
|
||||||
|
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
# メインテーブルの列情報を取得(user_idを除く)
|
|
||||||
cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table)))
|
|
||||||
main_columns = [desc[0] for desc in cur.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}.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)
|
|
||||||
)
|
|
||||||
|
|
||||||
cur.execute(query)
|
|
||||||
|
|
||||||
# 列名を再構成(nameを2番目に配置)
|
|
||||||
column_names = [main_columns[0], 'name'] + main_columns[1:]
|
|
||||||
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
with open(csv_file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
|
|
||||||
csvwriter = csv.writer(csvfile)
|
|
||||||
csvwriter.writerow(column_names)
|
|
||||||
|
|
||||||
for row in rows:
|
|
||||||
# nameを2番目に移動
|
|
||||||
formatted_row = [format_datetime(row[0])] + [row[-1]] + [format_datetime(field) if field is not None else '' for field in row[1:-1]]
|
|
||||||
csvwriter.writerow(formatted_row)
|
|
||||||
|
|
||||||
print(f"テーブル '{main_table}' の内容を '{csv_file_path}' に出力しました。")
|
|
||||||
|
|
||||||
except (Exception, psycopg2.Error) as error:
|
|
||||||
print("エラーが発生しました:", error)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
if conn:
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
print("データベース接続を閉じました。")
|
|
||||||
|
|
||||||
# 使用例
|
|
||||||
host = "192.168.1.220"
|
|
||||||
port = "12245"
|
|
||||||
database = "dislocker"
|
|
||||||
user = "suti7"
|
|
||||||
password = "Testing1234"
|
|
||||||
main_table = "pc_usage_history"
|
|
||||||
related_table = "club_member"
|
|
||||||
related_column = "name" # 例: 登録者の名前を表示したい場合
|
|
||||||
csv_file_path = "output.csv"
|
|
||||||
|
|
||||||
export_table_to_csv(host, port, database, user, password, main_table, related_table, related_column, csv_file_path)
|
|
22
temp/kill.py
22
temp/kill.py
|
@ -1,22 +0,0 @@
|
||||||
import wmi
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
async def watcher():
|
|
||||||
c=wmi.WMI()
|
|
||||||
cre_process_watcher=c.Win32_Process.watch_for("creation")
|
|
||||||
del_process_watcher=c.Win32_Process.watch_for("deletion")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
new_cre_process=cre_process_watcher()
|
|
||||||
new_del_process=del_process_watcher()
|
|
||||||
print(new_cre_process.Caption+" has been created")
|
|
||||||
print(new_del_process.Caption+" has been deleted ")
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
kill_task = asyncio.TaskGroup(watcher())
|
|
||||||
print('hello world')
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
print('1sec')
|
|
||||||
await kill_task
|
|
||||||
|
|
||||||
asyncio.run(main())
|
|
|
@ -1,16 +0,0 @@
|
||||||
import random
|
|
||||||
import string
|
|
||||||
# パスワードをファイルから読み込む
|
|
||||||
|
|
||||||
with open('password.txt', 'r') as f:
|
|
||||||
secret = f.read()
|
|
||||||
|
|
||||||
check=int(input("password :"))
|
|
||||||
|
|
||||||
if check==int(secret):
|
|
||||||
print("ok")
|
|
||||||
secret=0
|
|
||||||
with open('password.txt', 'w') as file:
|
|
||||||
file.write('')
|
|
||||||
else:
|
|
||||||
print("out")
|
|
|
@ -1,9 +0,0 @@
|
||||||
import os
|
|
||||||
|
|
||||||
# PowerShellコマンドを実行する関数
|
|
||||||
def run_powershell_command(command):
|
|
||||||
# PowerShellコマンドを実行
|
|
||||||
os.system(f"powershell -Command {command}")
|
|
||||||
|
|
||||||
# 例としてGet-Dateコマンドを実行して現在の日時を取得
|
|
||||||
run_powershell_command("Get-Date")
|
|
41
temp/test.py
41
temp/test.py
|
@ -1,41 +0,0 @@
|
||||||
|
|
||||||
import discord
|
|
||||||
import string
|
|
||||||
import random
|
|
||||||
|
|
||||||
# Intentsの設定
|
|
||||||
intents = discord.Intents.default()
|
|
||||||
intents.message_content = True
|
|
||||||
|
|
||||||
# 接続に必要なオブジェクトを生成
|
|
||||||
client = discord.Client(intents=intents)
|
|
||||||
|
|
||||||
# 起動時に動作する処理
|
|
||||||
@client.event
|
|
||||||
async def on_ready():
|
|
||||||
# 起動したらターミナルにログイン通知が表示される
|
|
||||||
print('ログインしました')
|
|
||||||
|
|
||||||
# メッセージ受信時に動作する処理
|
|
||||||
@client.event
|
|
||||||
async def on_message(message):
|
|
||||||
# メッセージ送信者がBotだった場合は無視する
|
|
||||||
if message.author.bot:
|
|
||||||
return
|
|
||||||
# 「/neko」と発言したら「にゃーん」が返る処理
|
|
||||||
if message.content == "/neko":
|
|
||||||
await message.channel.send('にゃーん')
|
|
||||||
|
|
||||||
if message.content == '/password':
|
|
||||||
secret=password_generator_n(4)
|
|
||||||
await message.channel.send(str(secret))
|
|
||||||
with open('password.txt', 'a') as file:
|
|
||||||
file.write(secret)
|
|
||||||
|
|
||||||
def password_generator_n(length):
|
|
||||||
numbers = string.digits # (1)
|
|
||||||
password = ''.join(random.choice(numbers) for _ in range(length)) # (2)
|
|
||||||
return password
|
|
||||||
|
|
||||||
# Botの起動とDiscordサーバーへの接続
|
|
||||||
client.run('MTI0NzA1Mzc1NzUxOTM2NDEyNw.Gh5gIt.kz1acBMxphff9mEZLLWrEdEoVD4RJwgBW5P14o')
|
|
97
temp/xcel.py
97
temp/xcel.py
|
@ -1,97 +0,0 @@
|
||||||
import psycopg2
|
|
||||||
import csv
|
|
||||||
from psycopg2 import sql
|
|
||||||
from datetime import datetime
|
|
||||||
from openpyxl import Workbook
|
|
||||||
from openpyxl.utils import get_column_letter
|
|
||||||
|
|
||||||
def format_datetime(value):
|
|
||||||
if isinstance(value, datetime):
|
|
||||||
return value.strftime('%Y-%m-%d %H:%M:%S')
|
|
||||||
return value
|
|
||||||
|
|
||||||
def export_table_to_excel(host, port, database, user, password, main_table, related_table, excel_file_path):
|
|
||||||
try:
|
|
||||||
conn = psycopg2.connect(
|
|
||||||
host=host,
|
|
||||||
port=port,
|
|
||||||
database=database,
|
|
||||||
user=user,
|
|
||||||
password=password
|
|
||||||
)
|
|
||||||
|
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
# メインテーブルの列情報を取得(member_idを除く)
|
|
||||||
cur.execute(sql.SQL("SELECT * FROM {} LIMIT 0").format(sql.Identifier(main_table)))
|
|
||||||
main_columns = [desc[0] for desc in cur.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}.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)
|
|
||||||
)
|
|
||||||
|
|
||||||
cur.execute(query)
|
|
||||||
|
|
||||||
# 列名を再構成(nameを2番目に配置)
|
|
||||||
column_names = [main_columns[0], 'name'] + main_columns[1:]
|
|
||||||
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
# Excelワークブックを作成
|
|
||||||
wb = Workbook()
|
|
||||||
ws = wb.active
|
|
||||||
|
|
||||||
# 列名を書き込み
|
|
||||||
ws.append(column_names)
|
|
||||||
|
|
||||||
# データを書き込み
|
|
||||||
for row in rows:
|
|
||||||
# nameを2番目に移動
|
|
||||||
formatted_row = [format_datetime(row[0])] + [row[-1]] + [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)
|
|
||||||
|
|
||||||
print(f"テーブル '{main_table}' の内容を '{excel_file_path}' に出力しました。")
|
|
||||||
|
|
||||||
except (Exception, psycopg2.Error) as error:
|
|
||||||
print("エラーが発生しました:", error)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
if conn:
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
print("データベース接続を閉じました。")
|
|
||||||
|
|
||||||
# 使用例
|
|
||||||
host = "192.168.1.220"
|
|
||||||
port = "12245"
|
|
||||||
database = "dislocker"
|
|
||||||
user = "suti7"
|
|
||||||
password = "Testing1234"
|
|
||||||
main_table = "pc_usage_history"
|
|
||||||
related_table = "club_member"
|
|
||||||
excel_file_path = "output.xlsx"
|
|
||||||
|
|
||||||
export_table_to_excel(host, port, database, user, password, main_table, related_table, excel_file_path)
|
|
Loading…
Reference in a new issue