py-ftpchat 0.2.0__tar.gz
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.
- py_ftpchat-0.2.0/LICENSE +21 -0
- py_ftpchat-0.2.0/PKG-INFO +97 -0
- py_ftpchat-0.2.0/README.md +80 -0
- py_ftpchat-0.2.0/pyproject.toml +34 -0
- py_ftpchat-0.2.0/setup.cfg +4 -0
- py_ftpchat-0.2.0/src/ftpchat/__init__.py +1 -0
- py_ftpchat-0.2.0/src/ftpchat/client/__init__.py +1 -0
- py_ftpchat-0.2.0/src/ftpchat/client/core.py +121 -0
- py_ftpchat-0.2.0/src/ftpchat/client/terminal.py +196 -0
- py_ftpchat-0.2.0/src/ftpchat/protocol.py +64 -0
- py_ftpchat-0.2.0/src/ftpchat/server/__init__.py +1 -0
- py_ftpchat-0.2.0/src/ftpchat/server/app.py +70 -0
- py_ftpchat-0.2.0/src/ftpchat/server/cli.py +42 -0
- py_ftpchat-0.2.0/src/ftpchat/web/__init__.py +2 -0
- py_ftpchat-0.2.0/src/ftpchat/web/gateway.py +346 -0
- py_ftpchat-0.2.0/src/py_ftpchat.egg-info/PKG-INFO +97 -0
- py_ftpchat-0.2.0/src/py_ftpchat.egg-info/SOURCES.txt +20 -0
- py_ftpchat-0.2.0/src/py_ftpchat.egg-info/dependency_links.txt +1 -0
- py_ftpchat-0.2.0/src/py_ftpchat.egg-info/entry_points.txt +4 -0
- py_ftpchat-0.2.0/src/py_ftpchat.egg-info/requires.txt +3 -0
- py_ftpchat-0.2.0/src/py_ftpchat.egg-info/top_level.txt +1 -0
- py_ftpchat-0.2.0/tests/test_ftpchat.py +241 -0
py_ftpchat-0.2.0/LICENSE
ADDED
|
@@ -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,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,80 @@
|
|
|
1
|
+
# FTP Chat
|
|
2
|
+
|
|
3
|
+
A messenger where messages are literally **files on an FTP server**. One
|
|
4
|
+
device on the LAN hosts the chat; every other device joins from a **browser**
|
|
5
|
+
(or the terminal client) — everything on the wire is FTP into that store.
|
|
6
|
+
|
|
7
|
+
## How it works
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
browser on phone/PC terminal client
|
|
11
|
+
│ HTTP/JSON │ ftplib
|
|
12
|
+
▼ ▼
|
|
13
|
+
ftpchat-web (HTTP gateway) ftpchat (terminal)
|
|
14
|
+
│ FTP (ftplib -> localhost) │
|
|
15
|
+
▼ ▼
|
|
16
|
+
┌────────────────────────┐
|
|
17
|
+
│ pyftpdlib FTP server │ storage = files:
|
|
18
|
+
│ rooms/general/*.txt │ rooms/general/<ms>-<nick>.txt
|
|
19
|
+
│ users/<name>/*.txt │
|
|
20
|
+
└────────────────────────┘
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The host runs **one process** (`ftpchat-web`) that starts the FTP server and
|
|
24
|
+
the browser gateway. The gateway itself speaks FTP to the local FTP server, so
|
|
25
|
+
even the browser traffic becomes FTP file reads/writes.
|
|
26
|
+
|
|
27
|
+
## Run (host PC)
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install -e ".[server]"
|
|
31
|
+
ftpchat-web
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
It prints the addresses to use, e.g.:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
ftp (store): 127.0.0.1:2121
|
|
38
|
+
browser: http://192.168.0.5:8080
|
|
39
|
+
terminal: ftpchat --host <local-ip> --port 2121 --user name
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
* **Browser**: open `http://<host-ip>:8080` on any device in the network —
|
|
43
|
+
type a nickname and chat. No apps, no installs.
|
|
44
|
+
* **Terminal client**: `ftpchat --host <host-ip> --user alice` (auto-registers
|
|
45
|
+
on first login). Commands: `/r <room>` `/to <user>` `/inbox` `/outbox`
|
|
46
|
+
`/users` `/rooms` `/refresh` `/quit`.
|
|
47
|
+
|
|
48
|
+
Windows: double-click `ftpchat-web.bat` (from the launcher) to run the host.
|
|
49
|
+
|
|
50
|
+
## Storage
|
|
51
|
+
|
|
52
|
+
Messages are plain files named `<milliseconds>-<nick>.txt`:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
from: phone
|
|
56
|
+
at: 1789234637227
|
|
57
|
+
room: general
|
|
58
|
+
|
|
59
|
+
привет с браузера
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Inspect the host folder (default `.ftpchat/rooms/general/`) to see every
|
|
63
|
+
message as a file; edit/delete files there if you like.
|
|
64
|
+
|
|
65
|
+
## Notes / security
|
|
66
|
+
|
|
67
|
+
* Toy for a trusted LAN. New FTP users auto-register with any password, and the
|
|
68
|
+
authorizer hands everyone full access to the shared tree.
|
|
69
|
+
* No TLS on FTP or HTTP. Do not expose to the internet.
|
|
70
|
+
* Message text goes through FTP storage; the web page renders it with
|
|
71
|
+
`textContent` (no HTML injection).
|
|
72
|
+
* Polling: browsers poll the gateway every 2 s, terminal polls the FTP store
|
|
73
|
+
every 2 s.
|
|
74
|
+
|
|
75
|
+
## Tests
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
pip install -e ".[server]" pytest
|
|
79
|
+
pytest # 20 tests: protocol, FTP core, web gateway
|
|
80
|
+
```
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "py-ftpchat"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "A messenger where messages are literally files on an FTP server. Terminal client + browser gateway on one LAN host."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "ftpchat contributors" }]
|
|
14
|
+
keywords = ["ftp", "messenger", "chat", "networking", "browser", "lan"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Communications :: Chat",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
ftpchat-server = "ftpchat.server.cli:main"
|
|
23
|
+
ftpchat = "ftpchat.client.terminal:main"
|
|
24
|
+
ftpchat-web = "ftpchat.web.gateway:main"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
server = ["pyftpdlib>=1.5"]
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.packages.find]
|
|
30
|
+
where = ["src"]
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
testpaths = ["tests"]
|
|
34
|
+
pythonpath = ["src"]
|
|
@@ -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."""
|
|
@@ -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()
|
|
@@ -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."""
|