Skip to content

Commit

Permalink
Merge pull request #23 from gridhead/rest
Browse files Browse the repository at this point in the history
Restructure the client-side codebase
  • Loading branch information
gridhead authored Jul 22, 2024
2 parents aca39f9 + 12b3e48 commit 8eb081f
Show file tree
Hide file tree
Showing 14 changed files with 134 additions and 100 deletions.
Empty file removed expedite/bridge/__init__.py
Empty file.
51 changes: 0 additions & 51 deletions expedite/bridge/base.py

This file was deleted.

21 changes: 21 additions & 0 deletions expedite/client/bridge/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
expedite
Copyright (C) 2024 Akashdeep Dhar
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
Any Red Hat trademarks that are incorporated in the codebase or documentation
are not subject to the GNU General Public License and may only be utilized or
replicated with the express permission of Red Hat, Inc.
"""
File renamed without changes.
4 changes: 2 additions & 2 deletions expedite/bridge/main.py → expedite/client/bridge/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
from PySide6.QtGui import QFontDatabase
from PySide6.QtWidgets import QApplication

from expedite.bridge import data # noqa
from expedite.bridge.room import MainWindow
from expedite.client.bridge import data # noqa
from expedite.client.bridge.room import MainWindow


def load_custom_font():
Expand Down
24 changes: 15 additions & 9 deletions expedite/bridge/room.py → expedite/client/bridge/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

import time
from asyncio import ensure_future, get_event_loop, new_event_loop, set_event_loop
from json import dumps, loads
from json import loads
from os.path import basename, getsize
from pathlib import Path
from uuid import uuid4
Expand All @@ -34,10 +34,14 @@
from websockets.exceptions import ConnectionClosed, InvalidURI

from expedite import __versdata__
from expedite.bridge.base import return_detail_text, show_location_dialog, truncate_text
from expedite.bridge.util import ValidateFields
from expedite.bridge.wind import Ui_mainwind
from expedite.client.base import bite_file, ease_size, find_size, fuse_file
from expedite.client.bridge.util import (
ValidateFields,
return_detail_text,
show_location_dialog,
truncate_text,
)
from expedite.client.bridge.wind import Ui_mainwind
from expedite.client.conn import (
collect_confirmation,
collect_connection_from_pairness,
Expand All @@ -54,9 +58,11 @@
deliver_dropping_summon,
deliver_metadata,
deliver_separation_from_mistaken_password,
deliver_suspension_from_expiry,
)
from expedite.client.meet import talk
from expedite.config import standard
from expedite.view import general, warning
from expedite.view import warning


class MainWindow(QMainWindow, Ui_mainwind):
Expand Down Expand Up @@ -181,6 +187,7 @@ def initialize_connection(self):
standard.client_host = self.sockaddr.text()
standard.client_progress = True
self.statarea.showMessage("Please wait while the client connects to the broker")
talk()
ensure_future(self.maintain_connection())

def normal_both_side(self):
Expand All @@ -205,7 +212,7 @@ def show_dialog(self, icon, head, text):
async def maintain_connection(self):
try:
async with connect(standard.client_host) as self.sock:
get_event_loop().call_later(standard.client_time, lambda: ensure_future(self.suspension_from_expiry()))
get_event_loop().call_later(standard.client_time, lambda: ensure_future(self.deliver_suspension_from_expiry_bridge()))
await deliver_connection_to_server(self.sock)
async for mesgcont in self.sock:
if isinstance(mesgcont, str):
Expand Down Expand Up @@ -333,10 +340,9 @@ async def show_collect_contents(self, pack):
self.progbarg.setValue(progress)
self.progbarg.setValue(100)

async def suspension_from_expiry(self):
async def deliver_suspension_from_expiry_bridge(self):
if not standard.client_pair:
general("Attempting to abandon from the network after expiry.")
await self.sock.send(dumps({"call": "rest"}))
await deliver_suspension_from_expiry(self.sock)
await self.sock.close()
warning(standard.client_note["rest"])
self.show_dialog(QMessageBox.Warning, standard.client_note["rest"], standard.client_text["rest"])
29 changes: 29 additions & 0 deletions expedite/bridge/util.py → expedite/client/bridge/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,35 @@

from os.path import exists

from PySide6.QtWidgets import QFileDialog


def show_location_dialog(parent=None, oper: str = "") -> str:
dialog = QFileDialog()
if oper == "dlvr":
client_path = dialog.getOpenFileName(parent, "Select location", "", "All Files (*)")[0]
else:
client_path = dialog.getExistingDirectory(parent, "Select location", "", QFileDialog.ShowDirsOnly)
return client_path


def truncate_text(text: str = "", size: int = 32) -> str:
if len(text) >= 32:
return text[0:size-3] + "..."
else:
return text


def return_detail_text() -> str:
text = """
<b>Expedite v{vers}</b><br/>
<i>A simple encrypted file transfer service for humans</i><br/><br/>
Expedite is a simple encrypted file transfer service that allows for people to share synchronously assets among each other without having to rely on third party file sharing services (and constantly worrying about how their data might be used) or feeling the need of having publicly visible IP addresses (and constantly worrying about script kiddies attacking your computer).<br/><br/>
Expedite Server can be deployed on a virtual private server having an IP address that is discoverable by the Expedite Client users to broker file contents. The transfers facilitated using WebSockets are end-to-end encrypted with the use of 128-bit Advanced Encryption Standard and the server is restricted to logging only unidentifiable activities to the volatile memory.<br/><br/>
Expedite is currently in BETA phase and if you like to direction the project is heading towards, kindly consider helping me out by <a href="{star}">starring</a> the project repository, <a href="{tick}">filing</a> issue tickets for software errors or feature requests, <a href="{pull}">contributing</a> to the codebase of the project or <a href="{help}">sponsoring</a> me to help maintain the servers and to help me keep working on more FOSS projects like these.<br/><br/>
"""
return text


class ValidateFields:
def __init__(self):
Expand Down
File renamed without changes.
31 changes: 2 additions & 29 deletions expedite/client/conn.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,15 @@

import asyncio
import time
from datetime import datetime
from hashlib import sha256
from json import dumps
from typing import Generator, Tuple

from tqdm.asyncio import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from websockets.legacy.client import WebSocketClientProtocol

from expedite.client.auth import decr_metadata, encr_metadata
from expedite.client.base import ease_size, fuse_file, read_file
from expedite.client.excp import PasswordMistaken
from expedite.client.util import facade_exit
from expedite.config import standard
from expedite.view import general, warning

Expand All @@ -57,11 +53,11 @@ async def collect_permission_to_join(iden: str = standard.client_iden) -> bool:
return True


async def deliver_suspension_from_expiry(sock: WebSocketClientProtocol) -> None | bool:
async def deliver_suspension_from_expiry(sock: WebSocketClientProtocol) -> bool:
if not standard.client_pair:
general("Attempting to abandon from the network after expiry.")
await sock.send(dumps({"call": "rest"}))
await facade_exit(sock, False, "rest")
return True
else:
return False

Expand Down Expand Up @@ -108,17 +104,6 @@ async def deliver_contents(sock: WebSocketClientProtocol) -> Generator[Tuple[byt
yield sha256(bite).hexdigest(), len(bite)


async def show_deliver_contents(sock: WebSocketClientProtocol) -> bool:
general(f"Delivering contents for '{standard.client_filename}' ({ease_size(standard.client_filesize)}) to {standard.client_endo}.")
standard.client_movestrt = time.time()
with logging_redirect_tqdm():
with tqdm(total=standard.client_filesize, unit="B", unit_scale=True, unit_divisor=1024, leave=False, initial=0) as prog:
async for dgst, size in deliver_contents(sock):
prog.set_description(f"{datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")} SHA256 {dgst}")
prog.update(size)
return True


async def collect_contents(sock: WebSocketClientProtocol) -> Generator[Tuple[bytes, int], None, None]:
for _ in range(standard.client_chks - 1):
mesgcont = await sock.recv()
Expand All @@ -128,18 +113,6 @@ async def collect_contents(sock: WebSocketClientProtocol) -> Generator[Tuple[byt
yield sha256(mesgcont).hexdigest(), len(mesgcont) - 16


async def show_collect_contents(sock: WebSocketClientProtocol, pack: bytes = b"") -> bool:
general(f"Collecting contents for '{standard.client_filename}' ({ease_size(standard.client_filesize)}) from {standard.client_endo}.")
standard.client_movestrt = time.time()
fuse_file(pack)
with logging_redirect_tqdm():
with tqdm(total=standard.client_filesize, unit="B", unit_scale=True, unit_divisor=1024, leave=False, initial=len(pack)) as prog:
async for dgst, size in collect_contents(sock):
prog.set_description(f"{datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")} SHA256 {dgst}")
prog.update(size)
return True


async def deliver_digest_checks(sock: WebSocketClientProtocol) -> bool:
general("Delivering contents digest for confirmation.")
await sock.send(dumps({"call": "hash", "data": standard.client_hash.hexdigest()}))
Expand Down
21 changes: 21 additions & 0 deletions expedite/client/prompt/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
expedite
Copyright (C) 2024 Akashdeep Dhar
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
Any Red Hat trademarks that are incorporated in the codebase or documentation
are not subject to the GNU General Public License and may only be utilized or
replicated with the express permission of Red Hat, Inc.
"""
4 changes: 2 additions & 2 deletions expedite/client/main.py → expedite/client/prompt/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
from expedite import __versdata__
from expedite.client.base import bite_file, find_name, find_size
from expedite.client.meet import talk
from expedite.client.room import oper
from expedite.client.util import facade_exit
from expedite.client.prompt.room import oper
from expedite.client.prompt.util import facade_exit
from expedite.config import standard


Expand Down
39 changes: 34 additions & 5 deletions expedite/client/room.py → expedite/client/prompt/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,44 @@


import sys
import time
from asyncio import ensure_future, get_event_loop
from datetime import datetime
from json import loads

from tqdm.asyncio import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from websockets import connect
from websockets.exceptions import ConnectionClosed
from websockets.legacy.client import WebSocketClientProtocol

from expedite.client.base import ease_size, fuse_file
from expedite.client.conn import (
collect_confirmation,
collect_connection_from_pairness,
collect_contents,
collect_digest_checks,
collect_dropping_summon,
collect_metadata,
collect_permission_to_join,
collect_separation_from_mistaken_password,
deliver_confirmation,
deliver_connection_to_server,
deliver_contents,
deliver_digest_checks,
deliver_dropping_summon,
deliver_metadata,
deliver_separation_from_mistaken_password,
deliver_suspension_from_expiry,
facade_exit,
show_collect_contents,
show_deliver_contents,
)
from expedite.client.prompt.util import deliver_suspension_from_expiry_prompt, facade_exit
from expedite.config import standard
from expedite.view import general


async def oper():
try:
async with connect(standard.client_host) as sock:
get_event_loop().call_later(standard.client_time, lambda: ensure_future(deliver_suspension_from_expiry(sock)))
get_event_loop().call_later(standard.client_time, lambda: ensure_future(deliver_suspension_from_expiry_prompt(sock)))
await deliver_connection_to_server(sock)
async for mesgcont in sock:
if isinstance(mesgcont, str):
Expand Down Expand Up @@ -104,3 +110,26 @@ async def oper():
except ConnectionClosed:
await facade_exit(sock, False, "dprt")
sys.exit(standard.client_exit)


async def show_deliver_contents(sock: WebSocketClientProtocol) -> bool:
general(f"Delivering contents for '{standard.client_filename}' ({ease_size(standard.client_filesize)}) to {standard.client_endo}.")
standard.client_movestrt = time.time()
with logging_redirect_tqdm():
with tqdm(total=standard.client_filesize, unit="B", unit_scale=True, unit_divisor=1024, leave=False, initial=0) as prog:
async for dgst, size in deliver_contents(sock):
prog.set_description(f"{datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")} SHA256 {dgst}")
prog.update(size)
return True


async def show_collect_contents(sock: WebSocketClientProtocol, pack: bytes = b"") -> bool:
general(f"Collecting contents for '{standard.client_filename}' ({ease_size(standard.client_filesize)}) from {standard.client_endo}.")
standard.client_movestrt = time.time()
fuse_file(pack)
with logging_redirect_tqdm():
with tqdm(total=standard.client_filesize, unit="B", unit_scale=True, unit_divisor=1024, leave=False, initial=len(pack)) as prog:
async for dgst, size in collect_contents(sock):
prog.set_description(f"{datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")} SHA256 {dgst}")
prog.update(size)
return True
6 changes: 6 additions & 0 deletions expedite/client/util.py → expedite/client/prompt/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

from websockets.legacy.client import WebSocketClientProtocol

from expedite.client.conn import deliver_suspension_from_expiry
from expedite.config import standard
from expedite.view import failure, general, success, warning

Expand All @@ -42,3 +43,8 @@ async def facade_exit(sock: WebSocketClientProtocol = None, cond: bool = True, n
failure(f"{plan} fail after {(time.time() - standard.client_strt):.2f} seconds.")
standard.client_exit = 1
general("Exiting.")


async def deliver_suspension_from_expiry_prompt(sock: WebSocketClientProtocol):
if await deliver_suspension_from_expiry(sock):
await facade_exit(sock, False, "rest")
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,5 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry.scripts]
ed-server = "expedite.server.main:main"
ed-client = "expedite.client.main:main"
ed-bridge = "expedite.bridge.main:main"
ed-prompt = "expedite.client.prompt.main:main"
ed-bridge = "expedite.client.bridge.main:main"

0 comments on commit 8eb081f

Please sign in to comment.