py-ftpchat 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ftpchat/__init__.py +1 -0
- ftpchat/client/__init__.py +1 -0
- ftpchat/client/core.py +121 -0
- ftpchat/client/terminal.py +196 -0
- ftpchat/protocol.py +64 -0
- ftpchat/server/__init__.py +1 -0
- ftpchat/server/app.py +70 -0
- ftpchat/server/cli.py +42 -0
- ftpchat/web/__init__.py +2 -0
- ftpchat/web/gateway.py +346 -0
- py_ftpchat-0.2.0.dist-info/METADATA +97 -0
- py_ftpchat-0.2.0.dist-info/RECORD +16 -0
- py_ftpchat-0.2.0.dist-info/WHEEL +5 -0
- py_ftpchat-0.2.0.dist-info/entry_points.txt +4 -0
- py_ftpchat-0.2.0.dist-info/licenses/LICENSE +21 -0
- py_ftpchat-0.2.0.dist-info/top_level.txt +1 -0
ftpchat/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""FTP chat: a messenger where messages are files on an FTP server."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""FTP client core: the messenger logic over ftplib."""
|
ftpchat/client/core.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ftplib
|
|
4
|
+
import io
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from ..protocol import Message, encode, filename, parse, safe_part, seq_of_filename
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _recursive_mkdir(ftp: ftplib.FTP, path: str) -> None:
|
|
11
|
+
parts = [p for p in path.split("/") if p]
|
|
12
|
+
current = ""
|
|
13
|
+
for part in parts:
|
|
14
|
+
current = f"{current}/{part}".lstrip("/")
|
|
15
|
+
try:
|
|
16
|
+
ftp.mkd(current)
|
|
17
|
+
except ftplib.error_perm:
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _read_text(ftp: ftplib.FTP, path: str) -> bytes:
|
|
22
|
+
buffer = io.BytesIO()
|
|
23
|
+
ftp.retrbinary(f"RETR {path}", buffer.write)
|
|
24
|
+
return buffer.getvalue()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class FtpChat:
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
host: str,
|
|
31
|
+
port: int = 2121,
|
|
32
|
+
user: str = "",
|
|
33
|
+
password: str = "",
|
|
34
|
+
timeout: float = 5.0,
|
|
35
|
+
) -> None:
|
|
36
|
+
self.ftp = ftplib.FTP()
|
|
37
|
+
self.ftp.connect(host, port, timeout=timeout)
|
|
38
|
+
self.ftp.login(user, password)
|
|
39
|
+
self.user = safe_part(user)
|
|
40
|
+
|
|
41
|
+
def inbox_path(self, user: str | None = None) -> str:
|
|
42
|
+
return f"users/{safe_part(user or self.user)}/inbox"
|
|
43
|
+
|
|
44
|
+
def outbox_path(self, user: str | None = None) -> str:
|
|
45
|
+
return f"users/{safe_part(user or self.user)}/outbox"
|
|
46
|
+
|
|
47
|
+
def inbox_of(self, user: str) -> str:
|
|
48
|
+
return self.inbox_path(user)
|
|
49
|
+
|
|
50
|
+
def add_user(self, user: str) -> None:
|
|
51
|
+
for path in (self.inbox_of(user), f"users/{safe_part(user)}/outbox"):
|
|
52
|
+
_recursive_mkdir(self.ftp, path)
|
|
53
|
+
|
|
54
|
+
def send_dm(self, to: str, text: str) -> int:
|
|
55
|
+
to = safe_part(to)
|
|
56
|
+
self.add_user(to)
|
|
57
|
+
seq = int(time.time() * 1000)
|
|
58
|
+
payload = encode(self.user, text, recipient=to, at_ms=seq)
|
|
59
|
+
self.ftp.storbinary(f"STOR {self.inbox_of(to)}/{filename(seq, self.user)}", io.BytesIO(payload))
|
|
60
|
+
self.ftp.storbinary(f"STOR {self.outbox_path()}/{filename(seq, self.user)}", io.BytesIO(payload))
|
|
61
|
+
return seq
|
|
62
|
+
|
|
63
|
+
def send_room(self, room: str, text: str) -> int:
|
|
64
|
+
room = safe_part(room)
|
|
65
|
+
path = f"rooms/{room}"
|
|
66
|
+
_recursive_mkdir(self.ftp, path)
|
|
67
|
+
seq = int(time.time() * 1000)
|
|
68
|
+
payload = encode(self.user, text, room=room, at_ms=seq)
|
|
69
|
+
self.ftp.storbinary(f"STOR {path}/{filename(seq, self.user)}", io.BytesIO(payload))
|
|
70
|
+
self.ftp.storbinary(f"STOR {self.outbox_path()}/{filename(seq, self.user)}", io.BytesIO(payload))
|
|
71
|
+
return seq
|
|
72
|
+
|
|
73
|
+
def _list_messages(self, path: str) -> list[Message]:
|
|
74
|
+
try:
|
|
75
|
+
names = self.ftp.nlst(path)
|
|
76
|
+
except ftplib.error_perm:
|
|
77
|
+
return []
|
|
78
|
+
messages: list[Message] = []
|
|
79
|
+
for name in names:
|
|
80
|
+
seq = seq_of_filename(name)
|
|
81
|
+
if seq <= 0:
|
|
82
|
+
continue
|
|
83
|
+
try:
|
|
84
|
+
raw = _read_text(self.ftp, f"{path}/{name}")
|
|
85
|
+
except ftplib.error_perm:
|
|
86
|
+
continue
|
|
87
|
+
messages.append(parse(seq, raw))
|
|
88
|
+
messages.sort(key=lambda m: m.seq)
|
|
89
|
+
return messages
|
|
90
|
+
|
|
91
|
+
def list_inbox(self) -> list[Message]:
|
|
92
|
+
return self._list_messages(self.inbox_path())
|
|
93
|
+
|
|
94
|
+
def list_outbox(self) -> list[Message]:
|
|
95
|
+
return self._list_messages(self.outbox_path())
|
|
96
|
+
|
|
97
|
+
def list_room(self, room: str) -> list[Message]:
|
|
98
|
+
return self._list_messages(f"rooms/{safe_part(room)}")
|
|
99
|
+
|
|
100
|
+
def list_rooms(self) -> list[str]:
|
|
101
|
+
try:
|
|
102
|
+
names = self.ftp.nlst("rooms")
|
|
103
|
+
except ftplib.error_perm:
|
|
104
|
+
return []
|
|
105
|
+
return [n for n in names if n and not n.startswith(".")]
|
|
106
|
+
|
|
107
|
+
def list_users(self) -> list[str]:
|
|
108
|
+
try:
|
|
109
|
+
names = self.ftp.nlst("users")
|
|
110
|
+
except ftplib.error_perm:
|
|
111
|
+
return []
|
|
112
|
+
return [n for n in names if n and not n.startswith(".")]
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
try:
|
|
116
|
+
self.ftp.quit()
|
|
117
|
+
except (ftplib.error_perm, OSError):
|
|
118
|
+
try:
|
|
119
|
+
self.ftp.close()
|
|
120
|
+
except OSError:
|
|
121
|
+
pass
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from ..protocol import Message
|
|
9
|
+
from .core import FtpChat
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Pr(threading.Thread):
|
|
13
|
+
def __init__(self, chat: FtpChat) -> None:
|
|
14
|
+
super().__init__(daemon=True)
|
|
15
|
+
self.chat = chat
|
|
16
|
+
self._print_lock = threading.Lock()
|
|
17
|
+
self._max: int = 0
|
|
18
|
+
self._scope = "room:general"
|
|
19
|
+
self._stop = threading.Event()
|
|
20
|
+
|
|
21
|
+
def out(self, line: str) -> None:
|
|
22
|
+
with self._print_lock:
|
|
23
|
+
print(line, flush=True)
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def _hm(seq: int) -> str:
|
|
27
|
+
return time.strftime("%H:%M:%S", time.localtime(seq / 1000)) if seq else "--:--:--"
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def _fmt(msg: Message) -> str:
|
|
31
|
+
if msg.room:
|
|
32
|
+
return f"[{Pr._hm(msg.seq)}] room#{msg.room} <{msg.sender}> {msg.text}"
|
|
33
|
+
return f"[{Pr._hm(msg.seq)}] {msg.sender}: {msg.text}"
|
|
34
|
+
|
|
35
|
+
def set_scope(self, scope: str) -> None:
|
|
36
|
+
self._max = 0
|
|
37
|
+
self._scope = scope
|
|
38
|
+
|
|
39
|
+
def _fetch(self) -> list[Message]:
|
|
40
|
+
scope = self._scope
|
|
41
|
+
if scope.startswith("room:"):
|
|
42
|
+
return self.chat.list_room(scope.split(":", 1)[1])
|
|
43
|
+
if scope.startswith("dm:"):
|
|
44
|
+
return self.chat.list_inbox()
|
|
45
|
+
return []
|
|
46
|
+
|
|
47
|
+
def snapshot(self) -> None:
|
|
48
|
+
msgs = self._fetch()
|
|
49
|
+
for m in msgs:
|
|
50
|
+
self.out(Pr._fmt(m))
|
|
51
|
+
self._max = max((m.seq for m in msgs), default=self._max)
|
|
52
|
+
|
|
53
|
+
def poll_once(self) -> None:
|
|
54
|
+
try:
|
|
55
|
+
msgs = self._fetch()
|
|
56
|
+
except Exception as exc: # noqa: BLE001
|
|
57
|
+
self.out(f"! poll failed: {exc}")
|
|
58
|
+
return
|
|
59
|
+
new_max = self._max
|
|
60
|
+
for m in msgs:
|
|
61
|
+
if m.seq > new_max:
|
|
62
|
+
self.out(Pr._fmt(m) + " <new>")
|
|
63
|
+
new_max = m.seq
|
|
64
|
+
self._max = new_max
|
|
65
|
+
|
|
66
|
+
def run(self) -> None:
|
|
67
|
+
while not self._stop.wait(2.0):
|
|
68
|
+
self.poll_once()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class TerminalApp:
|
|
72
|
+
def __init__(self, args) -> None:
|
|
73
|
+
self.args = args
|
|
74
|
+
self.chat = FtpChat(args.host, args.port, args.user, args.password)
|
|
75
|
+
self.room = "general"
|
|
76
|
+
self.dm_to: str | None = None
|
|
77
|
+
self.pr = Pr(self.chat)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def scope(self) -> str:
|
|
81
|
+
return f"room:{self.room}" if self.room else f"dm:{self.dm_to}"
|
|
82
|
+
|
|
83
|
+
def run(self) -> None:
|
|
84
|
+
self.pr.start()
|
|
85
|
+
self.pr.snapshot()
|
|
86
|
+
self.pr.out(f"connected as {self.chat.user}; scope: {self.scope}")
|
|
87
|
+
self.pr.out("/r <room> | /to <user> | /inbox | /outbox | /users | /rooms | /refresh | /quit")
|
|
88
|
+
try:
|
|
89
|
+
while True:
|
|
90
|
+
line = input("> ").strip()
|
|
91
|
+
if not line:
|
|
92
|
+
continue
|
|
93
|
+
if line.startswith("/"):
|
|
94
|
+
if not self._cmd(line):
|
|
95
|
+
break
|
|
96
|
+
else:
|
|
97
|
+
self._send(line)
|
|
98
|
+
except (KeyboardInterrupt, EOFError):
|
|
99
|
+
self.pr.out("bye")
|
|
100
|
+
finally:
|
|
101
|
+
self.pr._stop.set()
|
|
102
|
+
self.chat.close()
|
|
103
|
+
|
|
104
|
+
def _send(self, text: str) -> None:
|
|
105
|
+
try:
|
|
106
|
+
if self.room:
|
|
107
|
+
self.chat.send_room(self.room, text)
|
|
108
|
+
elif self.dm_to:
|
|
109
|
+
self.chat.send_dm(self.dm_to, text)
|
|
110
|
+
self.pr.out(f"[{Pr._hm(int(time.time() * 1000))}] -> {self.dm_to}: {text}")
|
|
111
|
+
else:
|
|
112
|
+
self.pr.out("! pick scope: /r <room> or /to <user>")
|
|
113
|
+
except Exception as exc: # noqa: BLE001
|
|
114
|
+
self.pr.out(f"! send failed: {exc}")
|
|
115
|
+
|
|
116
|
+
def _cmd(self, line: str) -> bool:
|
|
117
|
+
parts = line.split()
|
|
118
|
+
cmd, rest = parts[0], " ".join(parts[1:])
|
|
119
|
+
try:
|
|
120
|
+
if cmd in ("/q", "/quit", "/exit"):
|
|
121
|
+
self.pr.out("bye")
|
|
122
|
+
return False
|
|
123
|
+
if cmd in ("/r", "/room"):
|
|
124
|
+
self.room = rest or self.room
|
|
125
|
+
self.dm_to = None
|
|
126
|
+
self.pr.set_scope(self.scope)
|
|
127
|
+
self.pr.snapshot()
|
|
128
|
+
self.pr.out(f"now on room '{self.room}'")
|
|
129
|
+
elif cmd == "/to":
|
|
130
|
+
self.dm_to = rest or None
|
|
131
|
+
if self.dm_to:
|
|
132
|
+
self.chat.add_user(self.dm_to)
|
|
133
|
+
self.room = ""
|
|
134
|
+
self.pr.set_scope(self.scope)
|
|
135
|
+
self.pr.snapshot()
|
|
136
|
+
self.pr.out(f"dm with {self.dm_to}" if self.dm_to else "dm off")
|
|
137
|
+
elif cmd == "/inbox":
|
|
138
|
+
msgs = self.chat.list_inbox()
|
|
139
|
+
if not msgs:
|
|
140
|
+
self.pr.out("inbox empty")
|
|
141
|
+
for m in msgs:
|
|
142
|
+
self.pr.out(Pr._fmt(m))
|
|
143
|
+
elif cmd == "/outbox":
|
|
144
|
+
msgs = self.chat.list_outbox()
|
|
145
|
+
if not msgs:
|
|
146
|
+
self.pr.out("outbox empty")
|
|
147
|
+
for m in msgs:
|
|
148
|
+
r = m.recipient or m.room
|
|
149
|
+
self.pr.out(f"[{Pr._hm(m.seq)}] -> {r}: {m.text}")
|
|
150
|
+
elif cmd == "/users":
|
|
151
|
+
users = self.chat.list_users()
|
|
152
|
+
self.pr.out("users: " + (", ".join(users) if users else "none yet"))
|
|
153
|
+
elif cmd == "/rooms":
|
|
154
|
+
rooms = self.chat.list_rooms()
|
|
155
|
+
self.pr.out("rooms: " + (", ".join(rooms) if rooms else "none yet"))
|
|
156
|
+
elif cmd == "/refresh":
|
|
157
|
+
self.pr.snapshot()
|
|
158
|
+
elif cmd == "/help":
|
|
159
|
+
self.pr.out("/r <room> | /to <user> | /inbox | /outbox | /users | /rooms | /refresh | /quit")
|
|
160
|
+
else:
|
|
161
|
+
self.pr.out(f"! unknown: {cmd}")
|
|
162
|
+
except Exception as exc: # noqa: BLE001
|
|
163
|
+
self.pr.out(f"! {exc}")
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _use_utf8() -> None:
|
|
168
|
+
for stream in (sys.stdout, sys.stderr):
|
|
169
|
+
if hasattr(stream, "reconfigure"):
|
|
170
|
+
try:
|
|
171
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
172
|
+
except (OSError, ValueError):
|
|
173
|
+
pass
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
177
|
+
parser = argparse.ArgumentParser(prog="ftpchat", description="FTP messenger: terminal client.")
|
|
178
|
+
parser.add_argument("--host", default="127.0.0.1", help="FTP server host")
|
|
179
|
+
parser.add_argument("--port", type=int, default=2121, help="FTP server port")
|
|
180
|
+
parser.add_argument("--user", required=True, help="your username")
|
|
181
|
+
parser.add_argument("--password", default="", help="your password")
|
|
182
|
+
return parser
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def main(argv: list[str] | None = None) -> None:
|
|
186
|
+
_use_utf8()
|
|
187
|
+
args = _build_parser().parse_args(argv)
|
|
188
|
+
try:
|
|
189
|
+
TerminalApp(args).run()
|
|
190
|
+
except Exception as exc: # noqa: BLE001
|
|
191
|
+
print(f"! cannot connect: {exc}")
|
|
192
|
+
sys.exit(1)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
if __name__ == "__main__":
|
|
196
|
+
main()
|
ftpchat/protocol.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Message:
|
|
9
|
+
seq: int
|
|
10
|
+
sender: str
|
|
11
|
+
recipient: str | None
|
|
12
|
+
room: str | None
|
|
13
|
+
at_ms: int
|
|
14
|
+
text: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def encode(
|
|
18
|
+
sender: str,
|
|
19
|
+
text: str,
|
|
20
|
+
recipient: str | None = None,
|
|
21
|
+
room: str | None = None,
|
|
22
|
+
at_ms: int | None = None,
|
|
23
|
+
) -> bytes:
|
|
24
|
+
at_ms = int(at_ms) if at_ms is not None else int(time.time() * 1000)
|
|
25
|
+
lines = [f"from: {sender}", f"at: {at_ms}"]
|
|
26
|
+
if recipient:
|
|
27
|
+
lines.append(f"to: {recipient}")
|
|
28
|
+
if room:
|
|
29
|
+
lines.append(f"room: {room}")
|
|
30
|
+
return ("\n".join(lines) + "\n\n" + text).encode("utf-8")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse(seq: int, raw: bytes) -> Message:
|
|
34
|
+
text_part = raw.decode("utf-8", "replace")
|
|
35
|
+
heads, _, body = text_part.partition("\n\n")
|
|
36
|
+
headers: dict[str, str] = {}
|
|
37
|
+
for line in heads.splitlines():
|
|
38
|
+
if ":" in line:
|
|
39
|
+
key, _, value = line.partition(":")
|
|
40
|
+
headers[key.strip()] = value.strip()
|
|
41
|
+
return Message(
|
|
42
|
+
seq=seq,
|
|
43
|
+
sender=headers.get("from", "?"),
|
|
44
|
+
recipient=headers.get("to"),
|
|
45
|
+
room=headers.get("room"),
|
|
46
|
+
at_ms=int(headers.get("at") or 0),
|
|
47
|
+
text=body.strip("\ufeff\n"),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def filename(at_ms: int, sender: str) -> str:
|
|
52
|
+
return f"{at_ms}-{sender}.txt"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def seq_of_filename(name: str) -> int:
|
|
56
|
+
try:
|
|
57
|
+
return int(name.split("-", 1)[0])
|
|
58
|
+
except ValueError:
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def safe_part(name: str, max_len: int = 32) -> str:
|
|
63
|
+
cleaned = "".join(ch for ch in name if ch.isalnum() or ch in "_-")
|
|
64
|
+
return cleaned[:max_len].strip("-_") or "guest"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""FTP server side of ftpchat."""
|
ftpchat/server/app.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from pyftpdlib.authorizers import DummyAuthorizer
|
|
6
|
+
from pyftpdlib.handlers import FTPHandler
|
|
7
|
+
from pyftpdlib.servers import ThreadedFTPServer
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _ensure_user_tree(root: str, user: str) -> None:
|
|
11
|
+
os.makedirs(os.path.join(root, "users", user, "inbox"), exist_ok=True)
|
|
12
|
+
os.makedirs(os.path.join(root, "users", user, "outbox"), exist_ok=True)
|
|
13
|
+
os.makedirs(os.path.join(root, "rooms"), exist_ok=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MessengerAuthorizer(DummyAuthorizer):
|
|
17
|
+
def __init__(self, root: str, auto_register: bool = True) -> None:
|
|
18
|
+
super().__init__()
|
|
19
|
+
self.root = root
|
|
20
|
+
self.auto_register = auto_register
|
|
21
|
+
|
|
22
|
+
def validate_authentication(self, username: str, password: str, handler) -> bool:
|
|
23
|
+
if username not in self.user_table:
|
|
24
|
+
if not self.auto_register:
|
|
25
|
+
raise KeyError("unknown user")
|
|
26
|
+
self.add_user(
|
|
27
|
+
username,
|
|
28
|
+
password,
|
|
29
|
+
self.root,
|
|
30
|
+
perm="elradfmwMT",
|
|
31
|
+
msg_login=f"welcome to ftpchat, {username}",
|
|
32
|
+
)
|
|
33
|
+
_ensure_user_tree(self.root, username)
|
|
34
|
+
return super().validate_authentication(username, password, handler)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MessengerHandler(FTPHandler):
|
|
38
|
+
authorizer: MessengerAuthorizer
|
|
39
|
+
|
|
40
|
+
def on_login(self, username: str) -> None:
|
|
41
|
+
_ensure_user_tree(self.authorizer.root, username)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class MessengerServer:
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
host: str = "0.0.0.0",
|
|
48
|
+
port: int = 2121,
|
|
49
|
+
root: str = ".",
|
|
50
|
+
auto_register: bool = True,
|
|
51
|
+
) -> None:
|
|
52
|
+
os.makedirs(root, exist_ok=True)
|
|
53
|
+
os.makedirs(os.path.join(root, "rooms"), exist_ok=True)
|
|
54
|
+
authorizer = MessengerAuthorizer(root, auto_register)
|
|
55
|
+
MessengerHandler.authorizer = authorizer
|
|
56
|
+
self.server = ThreadedFTPServer((host, port), MessengerHandler)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def port(self) -> int:
|
|
60
|
+
return self.server.socket.getsockname()[1]
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def host(self) -> str:
|
|
64
|
+
return self.server.socket.getsockname()[0]
|
|
65
|
+
|
|
66
|
+
def serve_forever(self, poll_interval: float = 0.5) -> None:
|
|
67
|
+
self.server.serve_forever(timeout=poll_interval)
|
|
68
|
+
|
|
69
|
+
def close(self) -> None:
|
|
70
|
+
self.server.close_all()
|
ftpchat/server/cli.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _use_utf8() -> None:
|
|
8
|
+
for stream in (sys.stdout, sys.stderr):
|
|
9
|
+
if hasattr(stream, "reconfigure"):
|
|
10
|
+
try:
|
|
11
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
12
|
+
except (OSError, ValueError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
17
|
+
parser = argparse.ArgumentParser(prog="ftpchat-server", description="FTP chat server: messages are files.")
|
|
18
|
+
parser.add_argument("--host", default="0.0.0.0", help="bind address (default: 0.0.0.0)")
|
|
19
|
+
parser.add_argument("--port", type=int, default=2121, help="FTP port (default: 2121)")
|
|
20
|
+
parser.add_argument("--root", default=".ftpchat", help="storage directory (default: .ftpchat)")
|
|
21
|
+
parser.add_argument("--no-auto-register", action="store_false", dest="auto_register", help="reject unknown users")
|
|
22
|
+
return parser
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv: list[str] | None = None) -> None:
|
|
26
|
+
_use_utf8()
|
|
27
|
+
args = _build_parser().parse_args(argv)
|
|
28
|
+
from .app import MessengerServer
|
|
29
|
+
|
|
30
|
+
server = MessengerServer(
|
|
31
|
+
host=args.host,
|
|
32
|
+
port=args.port,
|
|
33
|
+
root=args.root,
|
|
34
|
+
auto_register=args.auto_register,
|
|
35
|
+
)
|
|
36
|
+
print(f"ftpchat server on {args.host}:{server.port}, storage: {args.root}", flush=True)
|
|
37
|
+
try:
|
|
38
|
+
server.serve_forever()
|
|
39
|
+
except KeyboardInterrupt:
|
|
40
|
+
print("\nstop")
|
|
41
|
+
finally:
|
|
42
|
+
server.close()
|
ftpchat/web/__init__.py
ADDED
ftpchat/web/gateway.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import ftplib
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import socket
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
11
|
+
from urllib.parse import parse_qs, urlparse
|
|
12
|
+
|
|
13
|
+
from ..protocol import filename, safe_part, seq_of_filename
|
|
14
|
+
|
|
15
|
+
GATEWAY_USER = "web"
|
|
16
|
+
GATEWAY_PASSWORD = "web"
|
|
17
|
+
ROOM = "general"
|
|
18
|
+
|
|
19
|
+
PAGE = """<!doctype html>
|
|
20
|
+
<html lang="ru">
|
|
21
|
+
<head>
|
|
22
|
+
<meta charset="utf-8">
|
|
23
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
24
|
+
<title>FTP Chat</title>
|
|
25
|
+
<style>
|
|
26
|
+
:root { --bg:#0d1117; --panel:#161b22; --line:#30363d; --txt:#e6edf3; --dim:#8b949e;
|
|
27
|
+
--me:#1f6feb; --them:#21262d; --acc:#58a6ff; }
|
|
28
|
+
* { box-sizing:border-box; }
|
|
29
|
+
body { margin:0; font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;
|
|
30
|
+
background:var(--bg); color:var(--txt); height:100vh; display:flex; flex-direction:column; }
|
|
31
|
+
header { padding:10px 14px; background:var(--panel); border-bottom:1px solid var(--line);
|
|
32
|
+
display:flex; align-items:center; justify-content:space-between; gap:8px; }
|
|
33
|
+
header h1 { font-size:16px; margin:0; color:var(--acc); }
|
|
34
|
+
header span { font-size:12px; color:var(--dim); }
|
|
35
|
+
#nick { background:transparent; border:1px solid var(--line); color:var(--txt);
|
|
36
|
+
border-radius:6px; padding:4px 8px; font-size:13px; width:120px; }
|
|
37
|
+
#log { flex:1; overflow-y:auto; padding:12px; display:flex; flex-direction:column; gap:6px; }
|
|
38
|
+
.msg { max-width:78%; padding:7px 10px; border-radius:12px; font-size:14px; line-height:1.35;
|
|
39
|
+
overflow-wrap:anywhere; }
|
|
40
|
+
.msg.me { align-self:flex-end; background:var(--me); }
|
|
41
|
+
.msg.them { align-self:flex-start; background:var(--them); }
|
|
42
|
+
.msg .meta { font-size:11px; color:var(--dim); display:block; margin-bottom:2px; }
|
|
43
|
+
.msg.me .meta { color:#c9dcff; }
|
|
44
|
+
.sys { align-self:center; font-size:12px; color:var(--dim); }
|
|
45
|
+
footer { display:flex; gap:8px; padding:10px 14px; background:var(--panel);
|
|
46
|
+
border-top:1px solid var(--line); }
|
|
47
|
+
#text { flex:1; background:#0d1117; border:1px solid var(--line); color:var(--txt);
|
|
48
|
+
border-radius:8px; padding:9px 12px; font-size:14px; }
|
|
49
|
+
#send { background:var(--me); border:none; color:#fff; border-radius:8px; padding:0 18px;
|
|
50
|
+
font-size:14px; cursor:pointer; }
|
|
51
|
+
#send:active { opacity:.8; }
|
|
52
|
+
</style>
|
|
53
|
+
</head>
|
|
54
|
+
<body>
|
|
55
|
+
<header>
|
|
56
|
+
<h1>FTP Chat <span id="room"></span></h1>
|
|
57
|
+
<input id="nick" placeholder="никнейм" autocomplete="off">
|
|
58
|
+
</header>
|
|
59
|
+
<div id="log"></div>
|
|
60
|
+
<footer>
|
|
61
|
+
<input id="text" placeholder="написать сообщение..." autocomplete="off">
|
|
62
|
+
<button id="send">Отправить</button>
|
|
63
|
+
</footer>
|
|
64
|
+
<script>
|
|
65
|
+
const log = () => document.getElementById('log');
|
|
66
|
+
const roomEl = () => document.getElementById('room');
|
|
67
|
+
const nickEl = () => document.getElementById('nick');
|
|
68
|
+
const textEl = () => document.getElementById('text');
|
|
69
|
+
let nick = localStorage.getItem('ftpchat.nick') || '';
|
|
70
|
+
nickEl().value = nick;
|
|
71
|
+
roomEl().textContent = '#' + '""" + ROOM + """';
|
|
72
|
+
|
|
73
|
+
function say(text) {
|
|
74
|
+
const d = document.createElement('div');
|
|
75
|
+
d.className = 'sys';
|
|
76
|
+
d.textContent = text;
|
|
77
|
+
log().appendChild(d);
|
|
78
|
+
log().scrollTop = log().scrollHeight;
|
|
79
|
+
}
|
|
80
|
+
function addMessage(m) {
|
|
81
|
+
const isMe = m.sender === nick;
|
|
82
|
+
const d = document.createElement('div');
|
|
83
|
+
d.className = 'msg ' + (isMe ? 'me' : 'them');
|
|
84
|
+
const meta = document.createElement('span');
|
|
85
|
+
meta.className = 'meta';
|
|
86
|
+
const t = new Date(m.seq).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
|
|
87
|
+
meta.textContent = (isMe ? 'вы' : m.sender) + ' · ' + t;
|
|
88
|
+
const body = document.createElement('span');
|
|
89
|
+
body.textContent = m.text;
|
|
90
|
+
d.appendChild(meta);
|
|
91
|
+
d.appendChild(body);
|
|
92
|
+
log().appendChild(d);
|
|
93
|
+
log().scrollTop = log().scrollHeight;
|
|
94
|
+
}
|
|
95
|
+
let lastSeq = 0;
|
|
96
|
+
async function poll() {
|
|
97
|
+
try {
|
|
98
|
+
const r = await fetch('/api/messages?after=' + lastSeq);
|
|
99
|
+
const data = await r.json();
|
|
100
|
+
for (const m of data.messages) addMessage(m);
|
|
101
|
+
lastSeq = data.seq || lastSeq;
|
|
102
|
+
} catch (e) { /* server briefly down, retry */ }
|
|
103
|
+
}
|
|
104
|
+
async function send() {
|
|
105
|
+
const text = textEl().value.trim();
|
|
106
|
+
if (!text) return;
|
|
107
|
+
nick = nickEl().value.trim();
|
|
108
|
+
if (!nick) { nickEl().focus(); return; }
|
|
109
|
+
localStorage.setItem('ftpchat.nick', nick);
|
|
110
|
+
textEl().value = '';
|
|
111
|
+
try {
|
|
112
|
+
await fetch('/api/send', {
|
|
113
|
+
method: 'POST',
|
|
114
|
+
headers: {'Content-Type':'application/json'},
|
|
115
|
+
body: JSON.stringify({nick: nick, text: text})
|
|
116
|
+
});
|
|
117
|
+
} catch (e) { say('ошибка отправки'); }
|
|
118
|
+
}
|
|
119
|
+
document.getElementById('send').onclick = send;
|
|
120
|
+
textEl().addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
|
|
121
|
+
nickEl().addEventListener('change', () => localStorage.setItem('ftpchat.nick', nickEl().value.trim()));
|
|
122
|
+
setInterval(poll, 2000);
|
|
123
|
+
poll();
|
|
124
|
+
</script>
|
|
125
|
+
</body>
|
|
126
|
+
</html>
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class GatewayHandler(BaseHTTPRequestHandler):
|
|
131
|
+
gateway: WebGateway
|
|
132
|
+
server_version = "FTPChat/0.2"
|
|
133
|
+
|
|
134
|
+
def log_message(self, fmt: str, *args) -> None: # keep the console quiet
|
|
135
|
+
pass
|
|
136
|
+
|
|
137
|
+
def _json(self, code: int, payload: dict) -> None:
|
|
138
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
139
|
+
self.send_response(code)
|
|
140
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
141
|
+
self.send_header("Content-Length", str(len(body)))
|
|
142
|
+
self.end_headers()
|
|
143
|
+
self.wfile.write(body)
|
|
144
|
+
|
|
145
|
+
def _ftp(self) -> ftplib.FTP:
|
|
146
|
+
ftp = ftplib.FTP()
|
|
147
|
+
ftp.connect(self.gateway.ftp_host, self.gateway.ftp_port, timeout=5)
|
|
148
|
+
ftp.login(self.gateway.user, self.gateway.password)
|
|
149
|
+
return ftp
|
|
150
|
+
|
|
151
|
+
def _recursive_mkdir(self, ftp: ftplib.FTP, path: str) -> None:
|
|
152
|
+
current = ""
|
|
153
|
+
for part in [p for p in path.split("/") if p]:
|
|
154
|
+
current = f"{current}/{part}".lstrip("/")
|
|
155
|
+
try:
|
|
156
|
+
ftp.mkd(current)
|
|
157
|
+
except ftplib.error_perm:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
def _room_files(self) -> list[dict]:
|
|
161
|
+
ftp = self._ftp()
|
|
162
|
+
try:
|
|
163
|
+
try:
|
|
164
|
+
names = ftp.nlst(f"rooms/{ROOM}")
|
|
165
|
+
except ftplib.error_perm:
|
|
166
|
+
return []
|
|
167
|
+
messages = []
|
|
168
|
+
for name in names:
|
|
169
|
+
seq = seq_of_filename(name)
|
|
170
|
+
if seq <= 0:
|
|
171
|
+
continue
|
|
172
|
+
buf = io.BytesIO()
|
|
173
|
+
try:
|
|
174
|
+
ftp.retrbinary(f"RETR rooms/{ROOM}/{name}", buf.write)
|
|
175
|
+
except ftplib.error_perm:
|
|
176
|
+
continue
|
|
177
|
+
blocks = buf.getvalue().decode("utf-8", "replace").split("\n\n", 1)
|
|
178
|
+
head = {
|
|
179
|
+
k.strip(): v.strip()
|
|
180
|
+
for line in blocks[0].splitlines()
|
|
181
|
+
if ":" in line
|
|
182
|
+
for k, _, v in [line.partition(":")]
|
|
183
|
+
}
|
|
184
|
+
sender = head.get("from", "?")
|
|
185
|
+
try:
|
|
186
|
+
at = int(head.get("at") or seq)
|
|
187
|
+
except ValueError:
|
|
188
|
+
at = seq
|
|
189
|
+
text = blocks[1].strip("\ufeff\n") if len(blocks) > 1 else ""
|
|
190
|
+
messages.append({"seq": at, "sender": sender, "text": text})
|
|
191
|
+
messages.sort(key=lambda m: m["seq"])
|
|
192
|
+
return messages
|
|
193
|
+
finally:
|
|
194
|
+
try:
|
|
195
|
+
ftp.quit()
|
|
196
|
+
except (ftplib.error_perm, OSError):
|
|
197
|
+
ftp.close()
|
|
198
|
+
|
|
199
|
+
def do_GET(self) -> None:
|
|
200
|
+
url = urlparse(self.path)
|
|
201
|
+
if url.path == "/":
|
|
202
|
+
body = PAGE.encode("utf-8")
|
|
203
|
+
self.send_response(200)
|
|
204
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
205
|
+
self.send_header("Content-Length", str(len(body)))
|
|
206
|
+
self.end_headers()
|
|
207
|
+
self.wfile.write(body)
|
|
208
|
+
return
|
|
209
|
+
if url.path == "/api/messages":
|
|
210
|
+
params = parse_qs(url.query)
|
|
211
|
+
after = int(params.get("after", ["0"])[0] or 0)
|
|
212
|
+
try:
|
|
213
|
+
all_msgs = self._room_files()
|
|
214
|
+
except ftplib.all_errors as exc:
|
|
215
|
+
self._json(503, {"error": f"ftp unavailable: {exc}"})
|
|
216
|
+
return
|
|
217
|
+
messages = [m for m in all_msgs if m["seq"] > after]
|
|
218
|
+
self._json(200, {"messages": messages, "seq": max((m["seq"] for m in all_msgs), default=0)})
|
|
219
|
+
return
|
|
220
|
+
self._json(404, {"error": "not found"})
|
|
221
|
+
|
|
222
|
+
def do_POST(self) -> None:
|
|
223
|
+
url = urlparse(self.path)
|
|
224
|
+
if url.path != "/api/send":
|
|
225
|
+
self._json(404, {"error": "not found"})
|
|
226
|
+
return
|
|
227
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
228
|
+
try:
|
|
229
|
+
data = json.loads(self.rfile.read(length).decode("utf-8"))
|
|
230
|
+
nick = safe_part(data.get("nick") or "guest")
|
|
231
|
+
text = str(data.get("text") or "").strip()
|
|
232
|
+
except (ValueError, TypeError):
|
|
233
|
+
self._json(400, {"error": "bad json"})
|
|
234
|
+
return
|
|
235
|
+
if not text or len(text) > 4000:
|
|
236
|
+
self._json(400, {"error": "empty or too long"})
|
|
237
|
+
return
|
|
238
|
+
seq = int(time.time() * 1000)
|
|
239
|
+
ftp: ftplib.FTP | None = None
|
|
240
|
+
try:
|
|
241
|
+
ftp = self._ftp()
|
|
242
|
+
self._recursive_mkdir(ftp, f"rooms/{ROOM}")
|
|
243
|
+
payload = (
|
|
244
|
+
f"from: {nick}\nat: {seq}\nroom: {ROOM}\n\n{text}"
|
|
245
|
+
).encode()
|
|
246
|
+
ftp.storbinary(f"STOR rooms/{ROOM}/{filename(seq, nick)}", io.BytesIO(payload))
|
|
247
|
+
except ftplib.all_errors as exc:
|
|
248
|
+
self._json(503, {"error": f"ftp error: {exc}"})
|
|
249
|
+
return
|
|
250
|
+
finally:
|
|
251
|
+
if ftp is not None:
|
|
252
|
+
try:
|
|
253
|
+
ftp.quit()
|
|
254
|
+
except (ftplib.error_perm, OSError):
|
|
255
|
+
ftp.close()
|
|
256
|
+
self._json(200, {"ok": True, "seq": seq})
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class WebGateway:
|
|
260
|
+
def __init__(
|
|
261
|
+
self,
|
|
262
|
+
ftp_host: str = "127.0.0.1",
|
|
263
|
+
ftp_port: int = 2121,
|
|
264
|
+
web_port: int = 8080,
|
|
265
|
+
web_host: str = "0.0.0.0",
|
|
266
|
+
user: str = GATEWAY_USER,
|
|
267
|
+
password: str = GATEWAY_PASSWORD,
|
|
268
|
+
) -> None:
|
|
269
|
+
self.ftp_host = ftp_host
|
|
270
|
+
self.ftp_port = ftp_port
|
|
271
|
+
self.user = user
|
|
272
|
+
self.password = password
|
|
273
|
+
self.httpd = ThreadingHTTPServer((web_host, web_port), GatewayHandler)
|
|
274
|
+
GatewayHandler.gateway = self
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def port(self) -> int:
|
|
278
|
+
return self.httpd.server_address[1]
|
|
279
|
+
|
|
280
|
+
def close(self) -> None:
|
|
281
|
+
self.httpd.shutdown()
|
|
282
|
+
self.httpd.server_close()
|
|
283
|
+
|
|
284
|
+
def serve_forever(self) -> None:
|
|
285
|
+
self.httpd.serve_forever()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _local_ips() -> list[str]:
|
|
289
|
+
ips: set[str] = set()
|
|
290
|
+
try:
|
|
291
|
+
hostname = socket.gethostname()
|
|
292
|
+
for info in socket.getaddrinfo(hostname, None, socket.AF_INET):
|
|
293
|
+
addr = info[4][0]
|
|
294
|
+
if not addr.startswith("127."):
|
|
295
|
+
ips.add(addr)
|
|
296
|
+
except OSError:
|
|
297
|
+
pass
|
|
298
|
+
try:
|
|
299
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
300
|
+
s.connect(("8.8.8.8", 80))
|
|
301
|
+
ips.add(s.getsockname()[0])
|
|
302
|
+
s.close()
|
|
303
|
+
except OSError:
|
|
304
|
+
pass
|
|
305
|
+
return sorted(ips)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def main(argv: list[str] | None = None) -> None:
|
|
309
|
+
parser = argparse.ArgumentParser(prog="ftpchat-web", description="FTP chat: browser gateway (starts FTP + HTTP).")
|
|
310
|
+
parser.add_argument("--web-port", type=int, default=8080, help="browser port (default: 8080)")
|
|
311
|
+
parser.add_argument("--ftp-port", type=int, default=2121, help="FTP port (default: 2121)")
|
|
312
|
+
parser.add_argument("--host", default="0.0.0.0", help="bind address (default: 0.0.0.0)")
|
|
313
|
+
parser.add_argument("--root", default=".ftpchat", help="storage directory (default: .ftpchat)")
|
|
314
|
+
args = parser.parse_args(argv)
|
|
315
|
+
|
|
316
|
+
ftp_server, gateway = _start_host(args)
|
|
317
|
+
|
|
318
|
+
print(f"ftp (store): 127.0.0.1:{ftp_server.port}", flush=True)
|
|
319
|
+
addrs = _local_ips() or ["<local-ip>"]
|
|
320
|
+
for addr in addrs:
|
|
321
|
+
print(f"browser: http://{addr}:{gateway.port}", flush=True)
|
|
322
|
+
print(f"terminal: ftpchat --host <local-ip> --port {ftp_server.port} --user name", flush=True)
|
|
323
|
+
try:
|
|
324
|
+
while True:
|
|
325
|
+
time.sleep(3600)
|
|
326
|
+
except KeyboardInterrupt:
|
|
327
|
+
print("\nstop")
|
|
328
|
+
finally:
|
|
329
|
+
ftp_server.close()
|
|
330
|
+
gateway.close()
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _start_host(args) -> tuple[object, WebGateway]:
|
|
334
|
+
from ..server.app import MessengerServer
|
|
335
|
+
|
|
336
|
+
ftp_server = MessengerServer(host=args.host, port=args.ftp_port, root=args.root)
|
|
337
|
+
gateway = WebGateway(ftp_host="127.0.0.1", ftp_port=ftp_server.port, web_port=args.web_port, web_host=args.host)
|
|
338
|
+
threading.Thread(target=ftp_server.serve_forever, kwargs={"poll_interval": 0.5}, daemon=True).start()
|
|
339
|
+
threading.Thread(target=gateway.serve_forever, daemon=True).start()
|
|
340
|
+
return ftp_server, gateway
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
if __name__ == "__main__":
|
|
344
|
+
import sys
|
|
345
|
+
|
|
346
|
+
sys.exit(main())
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: py-ftpchat
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A messenger where messages are literally files on an FTP server. Terminal client + browser gateway on one LAN host.
|
|
5
|
+
Author: ftpchat contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: ftp,messenger,chat,networking,browser,lan
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Communications :: Chat
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Provides-Extra: server
|
|
15
|
+
Requires-Dist: pyftpdlib>=1.5; extra == "server"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# FTP Chat
|
|
19
|
+
|
|
20
|
+
A messenger where messages are literally **files on an FTP server**. One
|
|
21
|
+
device on the LAN hosts the chat; every other device joins from a **browser**
|
|
22
|
+
(or the terminal client) — everything on the wire is FTP into that store.
|
|
23
|
+
|
|
24
|
+
## How it works
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
browser on phone/PC terminal client
|
|
28
|
+
│ HTTP/JSON │ ftplib
|
|
29
|
+
▼ ▼
|
|
30
|
+
ftpchat-web (HTTP gateway) ftpchat (terminal)
|
|
31
|
+
│ FTP (ftplib -> localhost) │
|
|
32
|
+
▼ ▼
|
|
33
|
+
┌────────────────────────┐
|
|
34
|
+
│ pyftpdlib FTP server │ storage = files:
|
|
35
|
+
│ rooms/general/*.txt │ rooms/general/<ms>-<nick>.txt
|
|
36
|
+
│ users/<name>/*.txt │
|
|
37
|
+
└────────────────────────┘
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The host runs **one process** (`ftpchat-web`) that starts the FTP server and
|
|
41
|
+
the browser gateway. The gateway itself speaks FTP to the local FTP server, so
|
|
42
|
+
even the browser traffic becomes FTP file reads/writes.
|
|
43
|
+
|
|
44
|
+
## Run (host PC)
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
pip install -e ".[server]"
|
|
48
|
+
ftpchat-web
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
It prints the addresses to use, e.g.:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
ftp (store): 127.0.0.1:2121
|
|
55
|
+
browser: http://192.168.0.5:8080
|
|
56
|
+
terminal: ftpchat --host <local-ip> --port 2121 --user name
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
* **Browser**: open `http://<host-ip>:8080` on any device in the network —
|
|
60
|
+
type a nickname and chat. No apps, no installs.
|
|
61
|
+
* **Terminal client**: `ftpchat --host <host-ip> --user alice` (auto-registers
|
|
62
|
+
on first login). Commands: `/r <room>` `/to <user>` `/inbox` `/outbox`
|
|
63
|
+
`/users` `/rooms` `/refresh` `/quit`.
|
|
64
|
+
|
|
65
|
+
Windows: double-click `ftpchat-web.bat` (from the launcher) to run the host.
|
|
66
|
+
|
|
67
|
+
## Storage
|
|
68
|
+
|
|
69
|
+
Messages are plain files named `<milliseconds>-<nick>.txt`:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
from: phone
|
|
73
|
+
at: 1789234637227
|
|
74
|
+
room: general
|
|
75
|
+
|
|
76
|
+
привет с браузера
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Inspect the host folder (default `.ftpchat/rooms/general/`) to see every
|
|
80
|
+
message as a file; edit/delete files there if you like.
|
|
81
|
+
|
|
82
|
+
## Notes / security
|
|
83
|
+
|
|
84
|
+
* Toy for a trusted LAN. New FTP users auto-register with any password, and the
|
|
85
|
+
authorizer hands everyone full access to the shared tree.
|
|
86
|
+
* No TLS on FTP or HTTP. Do not expose to the internet.
|
|
87
|
+
* Message text goes through FTP storage; the web page renders it with
|
|
88
|
+
`textContent` (no HTML injection).
|
|
89
|
+
* Polling: browsers poll the gateway every 2 s, terminal polls the FTP store
|
|
90
|
+
every 2 s.
|
|
91
|
+
|
|
92
|
+
## Tests
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
pip install -e ".[server]" pytest
|
|
96
|
+
pytest # 20 tests: protocol, FTP core, web gateway
|
|
97
|
+
```
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
ftpchat/__init__.py,sha256=3hlYV-2L5g7EC4cDWwb9XaYYZrdV-WcDLcKgEDziX-s,70
|
|
2
|
+
ftpchat/protocol.py,sha256=DajKseEOwF0FWe9B_FmXFmSVslAevpVbc-pz3Alulgs,1630
|
|
3
|
+
ftpchat/client/__init__.py,sha256=QyOv7Qevl2-2t_2PwYL5_iE9RaIiShDL6-GMBh3i8xM,55
|
|
4
|
+
ftpchat/client/core.py,sha256=5VNi7y2v7uSvKRZZida98P_ZwyeIRawIv28-c74pyMk,3900
|
|
5
|
+
ftpchat/client/terminal.py,sha256=3LyJijxQYorQ6fAXV6CGDgdftW0nrg9L2SjcN0rxRQE,6665
|
|
6
|
+
ftpchat/server/__init__.py,sha256=k542GtUMEH8caX8kTEjgWJMhnWs62s7gasI3HvqSK7Y,33
|
|
7
|
+
ftpchat/server/app.py,sha256=h0bsgYWb6ckncHbAup1ZgVKFpI8LMF1cQKy9Qp_afco,2253
|
|
8
|
+
ftpchat/server/cli.py,sha256=iikuXOzhGkCg15vYFXw35PJo6Vx59HIe-ihKsEug_oQ,1431
|
|
9
|
+
ftpchat/web/__init__.py,sha256=0Z13ffuvsU9u-IIBBwUhD27wnns4_S2pMKnFH1tMcqo,155
|
|
10
|
+
ftpchat/web/gateway.py,sha256=Rd_f-rcgOcdke7m0incJC8Xls_sciS6kM1DJutgzoww,12674
|
|
11
|
+
py_ftpchat-0.2.0.dist-info/licenses/LICENSE,sha256=OHT5E6joJedbu6YzxmMd3v-oUOrWVdrePVngwwLYwuQ,1074
|
|
12
|
+
py_ftpchat-0.2.0.dist-info/METADATA,sha256=XbnxXrb8jIDrRRVJ11q0vNOo_odwwrYIX4m1kUEYu08,3325
|
|
13
|
+
py_ftpchat-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
14
|
+
py_ftpchat-0.2.0.dist-info/entry_points.txt,sha256=pOphU0UuWYFRaXwWqu14aaNJwcmF-AN-k3qycp5nLQQ,137
|
|
15
|
+
py_ftpchat-0.2.0.dist-info/top_level.txt,sha256=PkEOqbziWsa3Sc0zM9DYxSXIaZw5ysGtknI01aiGUbk,8
|
|
16
|
+
py_ftpchat-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 arbuztratil-design
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ftpchat
|