added a way to push files

master
kirbylife 2020-12-08 14:45:42 -06:00
parent 3c84622d6d
commit de5af9391b
15 changed files with 196 additions and 68 deletions

View File

@ -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):

View File

@ -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)

View File

@ -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))

View File

@ -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))

View File

@ -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__)

32
misc.py
View File

@ -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

BIN
screen.png 100644

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

View File

@ -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 = []

View File

@ -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))

View File

@ -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):

View File

@ -1 +0,0 @@

View File

@ -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))

View File

@ -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__)

View File

@ -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 = []

42
test_ws.py 100644
View File

@ -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()