diff --git a/client.py b/client.py index 6428500..a9929f2 100755 --- a/client.py +++ b/client.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +import base64 import json import os import pathlib @@ -13,54 +14,124 @@ from threading import Thread from time import sleep from PIL import Image, ImageTk -from pystray import Icon, Menu -from pystray import MenuItem as Item from requests import post -from websocket import WebSocket +import websocket from compare_json import compare_json from config import get_config from dir_to_json import get_json -from misc import check_network +from misc import check_network, flatten_dirs +from pystray import Icon, Menu +from pystray import MenuItem as Item +from websocket import WebSocket + +try: + import thread +except ImportError: + import _thread as thread _online_icon = Image.open("img/icons/online.png") _offline_icon = Image.open("img/icons/offline.png") _standby_icon = Image.open("img/icons/offline.png") +if not int(os.getenv("VERBOSE", 1)): + def X(*args, **kwargs): + pass + print = X class MunyalClient(Icon): def __init__(self): super(MunyalClient, self).__init__("Munyal") + self.__ws_break = False + self.ws = None self.icon = _standby_icon self.config = get_config() self.stack = [] def is_online(self): + # if not self.ws_online: + # self.icon = _standby_icon + # return False ping = check_network("http://google.com", 443) if ping: self.icon = _online_icon else: self.icon = _offline_icon + print(f"La PC está {'on' if bool(ping) else 'off'}line") + return ping + + def __ws_message(self, ws, message): + print(message) + + def __ws_error(self, ws, error): + print("Error: ", error) + + def __ws_open(self): + print("WebSocket abierto") + thread.start_new_thread(self.listener, ()) def start(self): + websocket.enableTrace(True) + # ws.on_open = self.listener thread_uploader = Thread(target=self.uploader, name="uploader", daemon=True) thread_downloader = Thread(target=self.downloader, name="downloader", daemon=True) + # thread_listener = Thread(target=self.listener, + # name="listener", + # daemon=True) thread_uploader.start() thread_downloader.start() + # thread_listener.start() + self.run(self.__run) self.menu = Menu(Item("Exit", lambda *args: sys.exit(0))) def __run(self, icon): icon.visible = True - sleep(60) - self.stop() + while True: + print("Conectando al websocket") + ws = websocket.WebSocketApp( + "ws://127.0.0.1:12345", + on_message=print, + on_error=print, + on_close=lambda soc: self.__ws_close(ws)) + ws.on_open = lambda soc: self.listener(soc) + ws.run_forever() + sleep(1) - def listener(self): - pass + def __ws_close(self, ws): + print("WebSocket cerrado") + self.__ws_break = True + + def listener(self, ws): + self.ws = ws + + def wrapper(*args): + while True: + print(self.stack) + if self.stack: + try: + data = self.stack[0] + folder = self.config["folder"] + if data["is_file"] and data["action"] == "add": + full_path = os.path.join(folder, data["name"]) + data["file"] = base64.b85encode( + open(full_path, "rb").read()).decode("ascii") + self.ws.send(json.dumps(data)) + self.stack.pop(0) + except Exception as e: + print(e.with_traceback()) + print("Error uploading file, trying again") + if not self.is_online() or self.__ws_break: + self.__ws_break = False + self.ws = None + return + sleep(1) + + thread.start_new_thread(wrapper, ()) def uploader(self): print("Uploader") @@ -75,9 +146,17 @@ class MunyalClient(Icon): if delete: print("Cosas eliminadas:") print(delete) + delete = flatten_dirs(delete, action="delete") + for f in delete: + f["action"] = "delete" + self.stack.extend(delete) if add: print("Cosas agregadas:") print(add) + add = flatten_dirs(add, action="add") + for f in add: + f["action"] = "add" + self.stack.extend(add) last = _actual def __upload(self, path): diff --git a/compare_json.py b/compare_json.py index 34a2833..0890ea9 100644 --- a/compare_json.py +++ b/compare_json.py @@ -30,9 +30,12 @@ def compare_json(json1, json2): if __name__ == "__main__": + import sys + folder_1 = sys.argv[1] + folder_2 = sys.argv[2] try: - json1 = get_json("/home/kirbylife/Munyal") - json2 = get_json("/home/kirbylife/Munyal") + json1 = get_json(folder_1) + json2 = get_json(folder_2) except Exception: print("error outside") json1, json2 = compare_json(json1, json2) diff --git a/dir_to_json.py b/dir_to_json.py index 16d3299..41cf6fd 100644 --- a/dir_to_json.py +++ b/dir_to_json.py @@ -47,6 +47,6 @@ def get_json(path): if __name__ == "__main__": - output = get_json( - "/media/kirbylife/DATOS/Proyectos/PyCharmProjects/Munyal/folder_test") + import sys + output = get_json(sys.argv[1]) print(json.dumps(output, indent=4)) diff --git a/first_test.py b/first_test.py index 38d97ba..6d4fd7a 100644 --- a/first_test.py +++ b/first_test.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from compare_json import compare_json -from dir_to_json import get_json - from copy import deepcopy from time import sleep +from compare_json import compare_json +from dir_to_json import get_json + ORIGINAL = "/home/kirbylife/Proyectos/munyal_test/original" def main(args): @@ -31,12 +31,3 @@ def main(args): if __name__ == '__main__': import sys sys.exit(main(sys.argv)) - - - - - - - - - diff --git a/http_server.py b/http_server.py index d0c94d8..84f6e62 100644 --- a/http_server.py +++ b/http_server.py @@ -6,9 +6,8 @@ from hashlib import md5 from random import randint from time import time -from flask import Flask, jsonify, request - import rethinkdb as r +from flask import Flask, jsonify, request app = Flask(__name__) diff --git a/misc.py b/misc.py index 5f5c65d..876df31 100644 --- a/misc.py +++ b/misc.py @@ -4,13 +4,21 @@ import pickle import sys from tkinter import Button, Label, Toplevel +from requests import get +from requests.exceptions import ConnectionError + from tcping import Ping def check_network(ip, port): - ping = Ping(ip, port, 20) - ping.ping(1) - return ping.result.rows[0].successed == 1 + try: + req = get(f"{ip}").status_code + return req in range(200, 300) + except ConnectionError: + return False + # ping = Ping(ip, port, 20) + # ping.ping(1) + # return ping.result.rows[0].successed == 1 def get_os(): @@ -26,3 +34,21 @@ def alert(window, message, title="Munyal"): button = Button(child, text="Aceptar", command=child.destroy) label.pack() button.pack() + + +def flatten_dirs(content, path="", action=""): + output = [] + for item in content: + if item["is_file"]: + item["name"] = os.path.join(path, item["name"]) + output.append(item) + else: + if item["content"] and action == "add": + output.extend( + flatten_dirs(item["content"], + os.path.join(path, item["name"]), + action=action)) + else: + item["name"] = os.path.join(path, item["name"]) + output.append(item) + return output diff --git a/screen.png b/screen.png new file mode 100644 index 0000000..24cc5b6 Binary files /dev/null and b/screen.png differ diff --git a/second_test.py b/second_test.py index 869acdd..f15444e 100644 --- a/second_test.py +++ b/second_test.py @@ -1,17 +1,18 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +import ftplib +import json +import os +import socket +from copy import deepcopy +from time import sleep + +from requests import post + from compare_json import compare_json from dir_to_json import get_json -from copy import deepcopy -from time import sleep -from requests import post - -import os -import socket -import json -import ftplib def need_deleted(items, route): out = [] diff --git a/temp/compare_json.py b/temp/compare_json.py index 77c1d15..0174999 100644 --- a/temp/compare_json.py +++ b/temp/compare_json.py @@ -5,6 +5,7 @@ import json from dir_to_json import get_json + def compare_json(json1, json2): bckup1, bckup2 = json1[:], json2[:] items1 = list(enumerate(json1)) diff --git a/temp/dir_to_json.py b/temp/dir_to_json.py index 5f59b1a..d05837e 100644 --- a/temp/dir_to_json.py +++ b/temp/dir_to_json.py @@ -1,10 +1,9 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from hashlib import md5 - -import os import json +import os +from hashlib import md5 def md5sum(filename): diff --git a/temp/download_ftp_tree.py b/temp/download_ftp_tree.py index 8b13789..e69de29 100644 --- a/temp/download_ftp_tree.py +++ b/temp/download_ftp_tree.py @@ -1 +0,0 @@ - diff --git a/temp/first_test.py b/temp/first_test.py index 38d97ba..6d4fd7a 100644 --- a/temp/first_test.py +++ b/temp/first_test.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from compare_json import compare_json -from dir_to_json import get_json - from copy import deepcopy from time import sleep +from compare_json import compare_json +from dir_to_json import get_json + ORIGINAL = "/home/kirbylife/Proyectos/munyal_test/original" def main(args): @@ -31,12 +31,3 @@ def main(args): if __name__ == '__main__': import sys sys.exit(main(sys.argv)) - - - - - - - - - diff --git a/temp/http_server.py b/temp/http_server.py index fa9ce25..71bc8ab 100644 --- a/temp/http_server.py +++ b/temp/http_server.py @@ -1,16 +1,12 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from flask import Flask -from flask import request -from flask import jsonify - -import rethinkdb as r - +import json from random import randint from time import time -import json +import rethinkdb as r +from flask import Flask, jsonify, request app = Flask(__name__) diff --git a/temp/second_test.py b/temp/second_test.py index 869acdd..f15444e 100644 --- a/temp/second_test.py +++ b/temp/second_test.py @@ -1,17 +1,18 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +import ftplib +import json +import os +import socket +from copy import deepcopy +from time import sleep + +from requests import post + from compare_json import compare_json from dir_to_json import get_json -from copy import deepcopy -from time import sleep -from requests import post - -import os -import socket -import json -import ftplib def need_deleted(items, route): out = [] diff --git a/test_ws.py b/test_ws.py new file mode 100644 index 0000000..b087860 --- /dev/null +++ b/test_ws.py @@ -0,0 +1,42 @@ +import time + +import websocket + +try: + import thread +except ImportError: + import _thread as thread + + +def on_message(ws, message): + print(message) + + +def on_error(ws, error): + print(error) + + +def on_close(ws): + print("### closed ###") + + +def on_open(ws): + def run(*args): + for i in range(3): + time.sleep(1) + ws.send("Hello %d" % i) + time.sleep(1) + ws.close() + print("thread terminating...") + + thread.start_new_thread(run, ()) + + +if __name__ == "__main__": + websocket.enableTrace(True) + ws = websocket.WebSocketApp("ws://127.0.0.1:12345/", + on_message=on_message, + on_error=on_error, + on_close=on_close) + ws.on_open = on_open + ws.run_forever()