diff --git a/server/WikiSpot_module.py b/server/WikiSpot_module.py new file mode 100644 index 0000000..f3ab907 --- /dev/null +++ b/server/WikiSpot_module.py @@ -0,0 +1,58 @@ +import requests, json, uuid + + +class Server: + def __init__(self, server_ip="0.0.0.0"): + self.device_id = None + self.server = None + self.client_id = uuid.uuid4().hex[24:] + try: + r = requests.get(f"http://{server_ip}:8000/discovery") + if r.text.strip('"') == "Success": + self.server = server_ip + rr = requests.get(f"http://{server_ip}:8000/devices_list") + self.device_id = dict(rr.json()[0])["connected_id"] + except Exception as error: + print(f"Program experienced a ERROR\nError: {error}") + self.server = None + + def get_sensors(self, server_id=None): + if not server_id: + cache = self.device_id + else: + cache = server_id + if self.server: + r = requests.get(f"http://{self.server}:8000/{cache}/sensors") + return dict(r.json()) + else: + raise Exception("Module was not inicialized/server was not found") + + def update_sensors(self, name, value, ID=None): + if not name and not value: + raise Exception("Invalid values were passed") + r = requests.post(f"http://{self.server}:8000/{ID if ID else self.device_id}/update_sensor") + return r.text + + def update_server(self, version, update_all=True): + if update_all: + r = requests.get(f"http://{self.server}:8000/admin/get/update-{version}") + else: + r = requests.get(f"http://{self.server}:8000/admin/get/update_one-{version}") + return r.text + + def get_versions(self): + return requests.get(f"http://{self.server}:8000/admin/get/get_updates").text + + def post_message(self, message): + r = requests.post(f"http://{self.server}:8000/messages/post", json={"m_sender": self.client_id, + "message": str(message)}) + return r.text + + def get_messages(self, timestamp=""): + r = requests.get(f"http://{self.server}:8000/messages/get", data={"timestamp": timestamp}) + return r.text + + def upload_file(self, file_path, save_path): + with open(file_path, "r") as cache: + r = requests.get(f"http://{self.server}:8000/messages/get", files={"uploaded_file": cache, "patch": save_path}) + return r.text diff --git a/server/files.zip b/server/files.zip new file mode 100644 index 0000000..3deb1bb Binary files /dev/null and b/server/files.zip differ diff --git a/server/filesystem.json b/server/filesystem.json index 780816d..886da53 100644 --- a/server/filesystem.json +++ b/server/filesystem.json @@ -3,8 +3,8 @@ "location": "49.14178021389778,18.353783098441415", "description": { "title": "legionrpi", - "description_s": "krátky popis, ktorý bude zobrazený iba v náhladovom okne", - "description_l": "dlhší popis zariadenia, ktorý bude zobrazený po otvorení", + "description_s": "kr\u00e1tky popis, ktor\u00fd bude zobrazen\u00fd iba v n\u00e1hladovom okne", + "description_l": "dlh\u0161\u00ed popis zariadenia, ktor\u00fd bude zobrazen\u00fd po otvoren\u00ed", "photo_s": "test.jpg", "photo_b": "test.png" }, @@ -13,10 +13,11 @@ "name": "test", "format": ".jpg", "description": "toto je jpg test file" - }, { + }, + { "name": "test2", "format": ".txt", "description": "toto je txt test file" } ] -} +} \ No newline at end of file diff --git a/server/log.txt b/server/log.txt index a8deb2b..bcdce9b 100644 --- a/server/log.txt +++ b/server/log.txt @@ -85,7 +85,7 @@ Response from server: "SUCCESS\nUpdate from version 0.6 to 0.6 was sucesfull\n" 2021-04-06 18:52:52.010837 -> Warning: 192.168.1.231 disconnected/is not available 2021-04-06 18:53:06.029220 -> Warning: 192.168.1.232 disconnected/is not available -2021-04-06 19:52:34.214066 -> Warning: Device Address(host='10.42.0.238', port=18381) is creating new sensor data. +2021-04-06 19:52:34.214066 -> Warning: Device Address(host='10.42.0.238', port=18381) is creating new sensor data. SENSOR: ['vlhkost', '40'] 2021-04-06 20:58:51.194511 -> Warning: Address(host='10.42.0.238', port=11244) created new sensor. SENSOR: name='Teplota' value='18' @@ -162,4 +162,41 @@ 2021-04-22 10:16:02.865022 -> Warning: Address(host='192.168.1.99', port=43644) created new sensor. SENSOR: name='test2' value='eeeh' 2021-04-23 11:22:54.684617 -> Warning: 192.168.1.231 disconnected/is not available -2021-04-23 11:36:58.295015 -> Warning: 192.168.1.231 disconnected/is not available \ No newline at end of file +2021-04-23 11:36:58.295015 -> Warning: 192.168.1.231 disconnected/is not available +2021-04-23 18:13:09.497747 -> Warning: Address(host='192.168.1.28', port=45062) created new sensor. + SENSOR: name='teplota' value='26°C' +2021-04-23 20:25:12.224311 -> ERROR: Address(host='192.168.1.28', port=48898) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-23 20:25:14.287622 -> ERROR: Address(host='192.168.1.28', port=48898) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 11:54:17.948411 -> ERROR: Sensor data download from 1 failed. + ERROR: 1 is not in list +2021-04-24 11:54:21.952522 -> ERROR: Sensor data download from 1 failed. + ERROR: 1 is not in list +2021-04-24 18:38:26.095820 -> ERROR: Address(host='192.168.1.7', port=32928) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:38:28.128341 -> ERROR: Address(host='192.168.1.7', port=33038) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:41:06.944584 -> ERROR: Address(host='192.168.1.7', port=33612) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:41:08.942270 -> ERROR: Address(host='192.168.1.7', port=33612) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:41:08.961718 -> ERROR: Address(host='192.168.1.7', port=33612) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:41:11.001168 -> ERROR: Address(host='192.168.1.7', port=33996) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:46:18.062541 -> ERROR: Address(host='192.168.1.7', port=34856) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-24 18:46:20.103101 -> ERROR: Address(host='192.168.1.7', port=35128) tried to access file (_[{(V,a,r,i,a,b,l,e, ,m,i,s,s,i,n,g)}]_) on id 1 that does not exist. +2021-04-26 14:51:30.981645 -> Warning: Address(host='192.168.1.99', port=41106) created new sensor. + SENSOR: name='string' value='string' +2021-04-27 11:03:50.711031 -> Warning: Address(host='192.168.1.99', port=38418) created new sensor. + SENSOR: name='string' value='string' +2021-04-27 11:04:00.123540 -> Warning: Address(host='192.168.1.99', port=38426) created new sensor. + SENSOR: name='test' value='012' +2021-04-27 11:04:13.492698 -> ERROR: Sensor data download from 1 failed. + ERROR: 1 is not in list +2021-04-27 11:04:56.073021 -> ERROR: Sensor data download from 1 failed. + ERROR: 1 is not in list +2021-04-27 19:13:46.323037 -> Warning: Address(host='192.168.1.99', port=44312) created new sensor. + SENSOR: name='string' value='string' +2021-04-27 19:13:53.203502 -> Warning: Address(host='192.168.1.99', port=44322) created new sensor. + SENSOR: name='test' value='0' +2021-05-02 20:06:54.398494 -> Warning: Address(host='192.168.1.99', port=52808) created new sensor. + SENSOR: name='test' value='0' +2021-05-02 20:38:09.342482 -> Warning: Address(host='192.168.1.99', port=53404) created new sensor. + SENSOR: name='[translate]-tempeature' value='16' +2021-05-02 20:38:31.096100 -> Warning: Address(host='192.168.1.99', port=53422) created new sensor. + SENSOR: name='tempeature' value='16' +2021-05-04 16:11:47.026867 -> Warning: 192.168.1.231 disconnected/is not available \ No newline at end of file diff --git a/server/main.py b/server/main.py index 87002b4..f42b3d3 100644 --- a/server/main.py +++ b/server/main.py @@ -12,6 +12,20 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel +devs = { + "Matej Justus": { + "git": "https://github.com/UntriexTv", "mail": "maco.justus@gmail.com"}, + "Benjamin Kojda": { + "git": "https://github.com/Tucan444", "mail": "ben4442004@gmail.com" + }, + "Jakub Ďuriš": { + "git": "https://github.com/ff0082", "mail": "jakub1.duris@gmail.com" + }, + "Samuel Šubika": { + "git": "https://github.com/JustSteel", "mail": "SteelSamko2000@gmail.com"} +} + + check = engine.Scan() check.check_to_go() if check.state_list["error"]: @@ -168,7 +182,7 @@ def get_file(IDx: int, file: str, request: Request): return f"ERROR: {file} does not exist." log.message(f"Downloaded {file} from {server_ip}") if ".txt" in file: - with open(f"cache/{IDx}/{file}", "wb", encoding='utf-8') as save: + with open(f"cache/{IDx}/{file}", "wb") as save: save.write(bytes(r.content)) else: with open(f"cache/{IDx}/{file}", "wb") as save: @@ -176,16 +190,21 @@ def get_file(IDx: int, file: str, request: Request): return FileResponse(f"cache/{IDx}/{file}") -@app.post("/update_sensor") -def update_sensors(data: Sensor, request: Request): +@app.post("/{IDx}/update_sensor") +def update_sensors(data: Sensor, request: Request, IDx: int): global sensors - if data.name in sensors: - log.message(f"{request.client.host} updated sensor {data.name} with value {data.value}") - sensors[data.name] = data.value + if IDx == ID: + if data.name in sensors: + log.message(f"{request.client.host} updated sensor {data.name} with value {data.value}") + sensors[data.name] = data.value + else: + log.warning(f"{request.client} created new sensor.\n SENSOR: {data}") + sensors[data.name] = data.value + return f"Successfuly made new sensor" else: - log.warning(f"{request.client} created new sensor.\n SENSOR: {data}") - sensors[data.name] = data.value - return f"Successfuly made" + r = requests.post(f"""http://{heartbeat_table["IP"][heartbeat_table["ID"].index(IDx)]}:8000/{IDx}/update_sensor""", + json={"name": data.name, "value": data.value}) + return r.text @app.get("/compare/{file}") @@ -215,6 +234,7 @@ def admin_get(command: str): if "update-" in command: state = [] version = command.split("-")[1] + return "success" for rpi in heartbeat_table["IP"]: if rpi != IP: r = requests.get(f"""http://{rpi}:8000/admin/get/update_one-{version}""") @@ -224,17 +244,17 @@ def admin_get(command: str): log.warning(f"""{rpi} failed to update. Manual update may be needed for proper working of network. Response from server: {r.text}""") state.append({rpi: r.text.strip('"').split("\\n")}) - # Todo Remove development comments - # subprocess.check_output(f"""python3 system.py update -version {version}""") + subprocess.check_output(f"""python3 system.py update -version {version}""") log.message(f"All devices in network should be updated to {version}") state.append({IP: "updated"}) return state if "update_one-" in command: + return "success" state = subprocess.check_output(["python3", "system.py", "update", "-version", f"""{command.split("-")[1]}"""]) log.warning(state.decode("utf-8")) return state.decode("utf-8") - if command == "settings": - return settings + if command == "heartbeat_table": + return heartbeat_table if command == "filesystem": return filesystem @@ -242,24 +262,22 @@ def admin_get(command: str): @app.post("/admin/{id_server}/upload_file") async def create_upload_file(id_server: int, uploaded_file: UploadFile = File(...), patch: str = ""): file_location = f"{patch}{uploaded_file.filename}" + print(f"file location: {file_location}") if id_server == ID: with open(file_location, "wb+") as file_object: file_object.write(uploaded_file.file.read()) else: with open(f"cache/{uploaded_file.filename}", "wb+") as file_object: file_object.write(uploaded_file.file.read()) - file = open(f"cache/{uploaded_file.filename}", "r") + file = open(f"cache/{uploaded_file.filename}", "rb") requests.post(f"""http://{heartbeat_table["IP"][heartbeat_table["ID"].index(id_server)]}:8000/admin/{id_server}/upload_file""", files={"uploaded_file": file, "patch": patch}) file.close() return {"info": f"""file '{uploaded_file.filename}' saved at '{id_server}/{file_location}'"""} -# Todo upload of update file and settings - - @app.get("/messages/get") -def get_messages(timestamp: str): +def get_messages(timestamp: str = None): if timestamp: for position, message in enumerate(reversed(messages)): if float(message["timestamp"]) <= float(timestamp): @@ -277,6 +295,11 @@ def register(): return [uuid.uuid4().hex[24:], messages[:9]] +@app.get("/discovery") +def discovery(): + return "Success" + + @app.post("/messages/post") def post_messages(data: Message): log.debug(f"Message was posted. Sender: {data.m_sender}\n MESSAGE: {data.message}") @@ -289,15 +312,11 @@ def post_messages(data: Message): return "Empty message/sender" -@app.get("/debug") -def debug_esp(): - return "test successful" - - def send_heartbeat(ip, id): global heartbeat_table log.message(f"""sending heartbeat to {ip}({"offline" if id in offline else "online"})""") cache_request = requests.post(f"http://{ip}:8000/heartbeat", data=json.dumps(heartbeat_table)) + print(cache_request.text) heartbeat_table = dict(cache_request.json()[0]) log.debug(json.dumps(cache_request.json(), indent=4)) @@ -346,6 +365,9 @@ def mainloop(): print(f"""Starting WikiSpot V{update.get_version()["version"]}""") print("GitHub: https://github.com/Tucan444/Mabasej_Team") +print("Developers of this project: ") +for dev in devs: + print(f"""{dev}, GitHub: {devs[dev]["git"]}, mail: {devs[dev]["mail"]}""") thread_1 = threading.Thread(target=mainloop, daemon=True) thread_1.start() diff --git a/server/settings.json b/server/settings.json index 3ef59d2..fd1c669 100644 --- a/server/settings.json +++ b/server/settings.json @@ -9,18 +9,18 @@ "max_mess": 20, "log": { "save_error": true, - "print_error": true, + "print_error": false, "save_warning": true, - "print_warning": true, + "print_warning": false, "save_message": false, - "print_message": true, - "enable_debug": true + "print_message": false, + "enable_debug": false }, "heartbeat_table": { - "ID": [], - "IP": [], - "location": [], - "file_system": [], - "last_heartbeat": [] + "ID": [1], + "IP": ["10.61.42.92"], + "location": [""], + "file_system": [""], + "last_heartbeat": [5] } } \ No newline at end of file diff --git a/server/temp.py b/server/temp.py new file mode 100644 index 0000000..bd42e20 --- /dev/null +++ b/server/temp.py @@ -0,0 +1,8 @@ +meno = input("zadajte meno: ") +priezvisko = input("zadajte priezvisko: ") + +print(f"Ahoj {meno} {priezvisko} vitaj v programe") +print("-"*24) +print("Ahoj " + meno + " " + priezvisko + " vitaj v programe") +print("-"*24) +print("Ahoj {} {} vitaj v programe".format(meno, priezvisko)) diff --git a/server/test.json b/server/test.json new file mode 100644 index 0000000..4147ba3 --- /dev/null +++ b/server/test.json @@ -0,0 +1,28 @@ +{ + "ID": 0, + "location": "49.14178021389778,18.353783098441415", + "description": { + "title": "legionrpi", + "description_s": "kr\u00e1tky popis, ktor\u00fd bude zobrazen\u00fd iba v n\u00e1hladovom okne", + "description_l": "dlh\u0161\u00ed popis zariadenia, ktor\u00fd bude zobrazen\u00fd po otvoren\u00ed", + "photo_s": "test.jpg", + "photo_b": "test.png" + }, + "files": [ + { + "name": "test", + "format": ".jpg", + "description": "toto je jpg test file" + }, + { + "name": "test2", + "format": ".txt", + "description": "toto je txt test file" + }, + { + "name": "Wikispot", + "format": "docx", + "description": "Test" + } + ] +} \ No newline at end of file diff --git a/server/test.py b/server/test.py index 628105c..5948dc6 100644 --- a/server/test.py +++ b/server/test.py @@ -1,6 +1,83 @@ -import requests +import socket +import multiprocessing +import subprocess +import os -file = open("files/test.jpg", "r") -r = requests.post(f"""http://192.168.1.99:8000/admin/1/upload_file""", - files={"uploaded_file": file, "patch": ""}) -print(r.text) \ No newline at end of file + +def pinger(job_q, results_q): + """ + Do Ping + :param job_q: + :param results_q: + :return: + """ + DEVNULL = open(os.devnull, 'w') + while True: + + ip = job_q.get() + + if ip is None: + break + + results_q.put(ip) + + +def get_my_ip(): + """ + Find my IP address + :return: + """ + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + ip = s.getsockname()[0] + s.close() + return ip + + +def map_network(pool_size=255): + """ + Maps the network + :param pool_size: amount of parallel ping processes + :return: list of valid ip addresses + """ + + ip_list = list() + my_ip = get_my_ip() + + # get my IP and compose a base like 192.168.1.xxx + ip_parts = get_my_ip().split('.') + base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.' + + # prepare the jobs queue + jobs = multiprocessing.Queue() + results = multiprocessing.Queue() + + pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)] + + for p in pool: + p.start() + + # cue hte ping processes + for i in range(1, 255): + jobs.put(base_ip + '{0}'.format(i)) + + for p in pool: + jobs.put(None) + + for p in pool: + p.join() + + # collect he results + while not results.empty(): + ip = results.get() + if ip != my_ip: + ip_list.append(ip) + + return ip_list + + +if __name__ == '__main__': + + print('Mapping...') + lst = map_network() + print(lst) diff --git a/server/test/setup app.py b/server/test/setup app.py new file mode 100644 index 0000000..4ad5a8a --- /dev/null +++ b/server/test/setup app.py @@ -0,0 +1,331 @@ +import tkinter +from tkinter.filedialog import askopenfilename +import requests +import json +import tkinter.messagebox +import os + +window = tkinter.Tk() +window.title("WikiSpot Editor") +sellected = None +sellected_index = None +filename = None +textn1 = None +textn2 = None +textn3 = None +ip = "127.0.0.1" +data = None +rpi_active = [] + + +# commands + +def save_changes(): + data[sellected_index]["description"]["title"] = text1.get() + data[sellected_index]["location"] = text2.get() + data[sellected_index]["description"]["description_s"] + data[sellected_index]["description"]["description_l"] + + +def update_server_refresh(text_window, description): + text_window.configure(state="normal") + text_window.delete('1.0', "end") + text_window.insert("end", description) + text_window.configure(state="disable") + + +def update_server_func(version, servers_all=True): + if servers_all: + if tkinter.messagebox.askyesno(title="Warning", message=f"WikiSpot Network will update to\n V{version}"): + r = requests.get(f"http://{ip}:8000/admin/get/update-{version}") + tkinter.messagebox.showinfo(title="Done", message=r.text) + + else: + if tkinter.messagebox.askyesno(title="Warning", message=f"WikiSpot Server will update to\n V{version}"): + r = requests.get(f"http://{ip}:8000/admin/get/update-one-{version}") + tkinter.messagebox.showinfo(title="Done", message=r.text) + + +def update_server(): + r = requests.get(f"http://{ip}:8000/admin/get/get_updates") + versions = json.loads(r.text) + versions_server = list(versions[1].keys()) + window_update_server = tkinter.Toplevel() + window_update_server.title("server update") + variable = tkinter.StringVar(window_update_server) + variable.set(versions_server[-1]) # default value + version_menu = tkinter.OptionMenu(window_update_server, variable, *versions_server) + label1 = tkinter.Label(window_update_server, text="WikiSpot verison: ") + label2 = tkinter.Label(window_update_server, text=versions[0]["version"]) + label3 = tkinter.Label(window_update_server, text="Versions") + label4 = tkinter.Label(window_update_server, text="Release news") + b1 = tkinter.Button(window_update_server, text="Update all", command=lambda: update_server_func(variable.get())) + b2 = tkinter.Button(window_update_server, text="Update one", command=lambda: update_server_func(variable.get(), servers_all=False)) + b3 = tkinter.Button(window_update_server, text="Exit", command=lambda: window_update_server.destroy()) + text = tkinter.Text(window_update_server, width=50, height=10) + text.insert("end", versions[1][variable.get()]["change_list"]) + variable.trace("w", lambda *args: update_server_refresh(text, versions[1][variable.get()]["change_list"])) + label1.grid(row=0, column=0) + label2.grid(row=0, column=1) + label3.grid(row=1, column=0) + label4.grid(row=2, column=0) + version_menu.grid(row=1, column=1) + text.grid(row=2, column=1) + b1.grid(row=3, column=0) + b2.grid(row=3, column=1) + b3.grid(row=3, column=2) + window_update_server.mainloop() + + + + +def upload_new_file(name, window, file_format, description, *patch: str): + global data + if " " in name: + tkinter.messagebox.showerror(title="Error", message="File name needs to be without spaces.\nApp on mobile will " + "change `_` to space.") + else: + data[sellected_index]["files"].append({ + "name": name, + "format": file_format, + "description": description.get("1.0", "end").replace("\n", "") + }) + print("saving") + with open("./test.json", "w", encoding='utf-8') as fp: + json.dump(dict(data[sellected_index]), fp, indent=2) + with open("test.json", "rb") as fp: + requests.post(f"http://{ip}:8000/admin/{sellected}/upload_file", files={"uploaded_file": fp}) + os.remove("test.json") + if patch: + with open(patch[0], "rb") as fp: + requests.post(f"http://{ip}:8000/admin/{sellected}/upload_file", files={"uploaded_file": fp, "patch": "files/"}, params={"patch": "files/"}) + window.destroy() + + +def new_file(*itnpu): + global filename, sellected + window_new = tkinter.Toplevel() + window_new.title("New File") + if sellected not in rpi_active: + tkinter.messagebox.showerror(title="Error", message="Server is not selected!") + window_new.destroy() + else: + filename = askopenfilename() + while not filename: + if not tkinter.messagebox.askretrycancel(title="Warning", message="File not selected."): + window_new.destroy() + break + filename = askopenfilename() + if filename: + label1 = tkinter.Label(window_new, text="FileName") + label2 = tkinter.Label(window_new, text="FileExtension") + label3 = tkinter.Label(window_new, text="Description") + label4 = tkinter.Label(window_new, text=str(filename.split("/")[-1].split(".")[0])) + label5 = tkinter.Label(window_new, text=str(filename.split("/")[-1].split(".")[1])) + in3 = tkinter.Text(window_new, height=8, width=40) + b1 = tkinter.Button(window_new, text="UPLOAD", command=lambda: upload_new_file( + str(filename.split("/")[-1].split(".")[0]), window_new, + str(filename.split("/")[-1].split(".")[1]), in3, filename), width=40, height=2) + b2 = tkinter.Button(window_new, text="EXIT", command=window_new.destroy, height=2) + label1.grid(row=0, column=0) + label2.grid(row=1, column=0) + label3.grid(row=2, column=0) + label4.grid(row=0, column=1) + label5.grid(row=1, column=1) + in3.grid(row=2, column=1) + b1.grid(row=3, column=1) + b2.grid(row=3, column=0) + window_new.mainloop() + + +def edit_file(file_name): + window_edit = tkinter.Toplevel() + window_edit.title("edit_file") + try: + for file in data[sellected_index]["files"]: + if file["name"] == file_name: + sellected_file_index = data[sellected_index]["files"].index(file) + break + else: + sellected_file_index = None + label1 = tkinter.Label(window_edit, text="Name\n(you can change name and\nformat only by uploading\nnew file)") + label2 = tkinter.Label(window_edit, text="Format") + label3 = tkinter.Label(window_edit, text="Description") + label4 = tkinter.Label(window_edit, text=data[sellected_index]["files"][sellected_file_index]["name"]) + label5 = tkinter.Label(window_edit, text=data[sellected_index]["files"][sellected_file_index]["format"]) + text = tkinter.Text(window_edit, height=8, width=40) + text.insert("end", data[sellected_index]["files"][sellected_file_index]["description"]) + button1 = tkinter.Button(window_edit, text="Exit", command=lambda: window_edit.destroy()) + button2 = tkinter.Button(window_edit, text="Save", command=lambda: upload_new_file( + data[sellected_index]["files"][sellected_file_index]["name"], window_edit, + data[sellected_index]["files"][sellected_file_index]["format"], text)) + button3 = tkinter.Button(window_edit, text="Remove", command=lambda: upload_new_file( + data[sellected_index]["files"][sellected_file_index]["name"], window_edit, "_REMOVE_", text)) + label1.grid(row=0, column=0) + label2.grid(row=1, column=0) + label3.grid(row=2, column=0) + label4.grid(row=0, column=1) + label5.grid(row=1, column=1) + text.grid(row=2, column=1) + button1.grid(row=3, column=0) + button2.grid(row=3, column=1) + button3.grid(row=3, column=2) + window_edit.mainloop() + except TypeError: + tkinter.messagebox.showerror(title="Error", message="No file sellected!\n" + "Select server and then file you want to edit.") + window_edit.destroy() + + + +def update_inputs(self): + global sellected, sellected_index, data + try: + if int(list_rpi.selection_get()) in rpi_active: + sellected = int(list_rpi.selection_get()) + for rpi in data: + if rpi["ID"] == sellected: + sellected_index = data.index(rpi) + text1.set(data[sellected_index]["ID"]) + text2.set(data[sellected_index]["location"]) + list2.clipboard_clear() + list2.delete(0, "end") + for file in data[sellected_index]["files"]: + list2.insert("end", file["name"]) + except ValueError or tkinter.TclError: + print(f"Exception: list_rpi sellection = {list_rpi.selection_get()}") + + +def update_listbox(): + global data, rpi_active + r = requests.get(f"http://{ip}:8000/devices_list") + data = json.loads(r.text) + del data[0] + print(data) + list_rpi.delete(0, "end") + rpi_active.clear() + for rpi in data: + list_rpi.insert("end", rpi["ID"]) + rpi_active.append(rpi["ID"]) + # for rpi in zoznam: + # list_rpi.insert("end", rpi) + + +def clear_listbox(): + list_rpi.delete(0, "end") + + +def cmd1(): + print(list_rpi.selection_get()) + + +# menu +menu = tkinter.Menu(window) +menu.master.config(menu=menu) + +# file +menu_submenu1 = tkinter.Menu(menu, tearoff=0) +menu.add_cascade(label="File", menu=menu_submenu1) +menu_submenu1.add_command(label="refresh", command=update_listbox) +menu_submenu1.add_separator() +menu_submenu1.add_command(label="exit", command=exit) + +# about +menu_submenu2 = tkinter.Menu(menu, tearoff=0) +menu.add_cascade(label="About", menu=menu_submenu2) +menu_submenu2.add_command(label="Check server updates", command=update_server) +menu_submenu2.add_command(label="Check app updates", command=update_listbox) +menu_submenu2.add_separator() +menu_submenu2.add_command(label="About WikiSpot", command=exit) +menu_submenu2.add_command(label="About Editor", command=exit) + + +# labels + +l1 = tkinter.Label(window, text='label1') +l1.grid(row=0, column=0) + +l2 = tkinter.Label(window, text='label2') +l2.grid(row=0, column=2) + +l3 = tkinter.Label(window, text='label3') +l3.grid(row=1, column=0) + +l4 = tkinter.Label(window, text='label4') +l4.grid(row=1, column=2) + +l5 = tkinter.Label(window, text='Servers:') +l5.grid(row=2, column=0) + +l6 = tkinter.Label(window, text='Files: ') +l6.grid(row=2, column=5) + +# entries + +text1 = tkinter.StringVar() +en1 = tkinter.Entry(window, textvariable=text1) +en1.grid(row=0, column=1) + +text2 = tkinter.StringVar() +en2 = tkinter.Entry(window, textvariable=text2) +en2.grid(row=0, column=3) + +text3 = tkinter.StringVar() +en3 = tkinter.Entry(window, textvariable=text3) +en3.grid(row=1, column=1) + +text4 = tkinter.StringVar() +en4 = tkinter.Entry(window, textvariable=text4) +en4.grid(row=1, column=3) + +# listbox + +list_rpi = tkinter.Listbox(window, height=6, width=35) +list_rpi.grid(row=3, column=0, rowspan=6, columnspan=2) +list_rpi.bind("<>", update_inputs) + +list2 = tkinter.Listbox(window, height=6, width=35) +list2.grid(row=3, column=5, rowspan=6, columnspan=2) +# list_rpi.bind("<>", update_inputs) + +# scrollbar + +sb1 = tkinter.Scrollbar(window) +sb1.grid(row=2, column=2, rowspan=6) + +list_rpi.configure(yscrollcommand=sb1.set) +sb1.configure(command=list_rpi.yview) + +sb2 = tkinter.Scrollbar(window) +sb2.grid(row=2, column=7, rowspan=6) + +list2.configure(yscrollcommand=sb2.set) +sb2.configure(command=list2.yview) + +# buttons + +btn1 = tkinter.Button(window, text="exit", width=12, command=update_listbox) +btn1.grid(row=6, column=3) + +btn2 = tkinter.Button(window, text="add server", width=12, command=clear_listbox) +btn2.grid(row=3, column=3) + +btn3 = tkinter.Button(window, text="place", width=12, command=new_file) +btn3.grid(row=4, column=3) + +btn4 = tkinter.Button(window, text="place", width=12, command=lambda: edit_file(list2.selection_get())) +btn4.grid(row=5, column=3) + +btn5 = tkinter.Button(window, text="save", width=12, command=update_listbox) +btn5.grid(row=6, column=4) + +btn5 = tkinter.Button(window, text="new file", width=12, command=new_file) +btn5.grid(row=3, column=4) + +btn5 = tkinter.Button(window, text="edit file", width=12, command=new_file) +btn5.grid(row=4, column=4) + +btn5 = tkinter.Button(window, text="place", width=12, command=lambda: window.destroy()) +btn5.grid(row=5, column=4) +update_listbox() +window.mainloop()