Compare commits

..

No commits in common. "7fc3ca701c4810e1c1e3c9265057d05af3839e72" and "3bf7918bb467ea37cfeed1babf2963dca0c9c481" have entirely different histories.

11 changed files with 123 additions and 372 deletions

4
.gitignore vendored
View file

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

View file

@ -1,22 +0,0 @@
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

View file

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

View file

@ -1,45 +0,0 @@
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:

View file

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

View file

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

View file

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

View file

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

View file

@ -1,40 +0,0 @@
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")