Inital Code
This commit is contained in:
75
main.py
Normal file
75
main.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Main entry point for the Terminal Chat application."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import argparse
|
||||
|
||||
from chatapp.models import UserConnection
|
||||
from chatapp.chat_server import ChatServer
|
||||
from chatapp.ui import TerminalChatApp
|
||||
from chatapp.ssh_server import start_ssh_server
|
||||
|
||||
|
||||
# Global chat server instance
|
||||
chat_server = ChatServer()
|
||||
|
||||
|
||||
async def start_terminal_chat(username: str):
|
||||
"""Start a TerminalChatApp for a single local user.
|
||||
|
||||
This creates a UserConnection attached to an asyncio.Queue, registers
|
||||
the user on the chat_server, runs the textual app asynchronously, and
|
||||
ensures the user is removed when the app exits.
|
||||
"""
|
||||
message_queue = asyncio.Queue()
|
||||
user_conn = UserConnection(username, message_queue)
|
||||
chat_server.add_user(username, user_conn)
|
||||
|
||||
try:
|
||||
app = TerminalChatApp(username, message_queue, chat_server)
|
||||
await app.run_async()
|
||||
finally:
|
||||
chat_server.remove_user(username)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point with argument parsing."""
|
||||
parser = argparse.ArgumentParser(description="Run Terminal Chat locally or via SSH")
|
||||
parser.add_argument("--ssh", action="store_true", help="Start SSH server mode")
|
||||
parser.add_argument("--host", default="0.0.0.0", help="Host to bind SSH server to (default: 0.0.0.0)")
|
||||
parser.add_argument("--port", type=int, default=8022, help="Port for SSH server (default: 8022)")
|
||||
parser.add_argument("--username", help="Username to use for the local terminal chat")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.ssh:
|
||||
# SSH server mode
|
||||
try:
|
||||
asyncio.run(start_ssh_server(args.host, args.port, chat_server))
|
||||
except KeyboardInterrupt:
|
||||
print("\nSSH server stopped")
|
||||
raise SystemExit(0)
|
||||
except Exception as exc:
|
||||
print(f"Error starting SSH server: {exc}")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
# Local terminal mode
|
||||
username = args.username or os.getenv("USER") or os.getenv("USERNAME")
|
||||
if not username:
|
||||
try:
|
||||
username = input("Enter username: ").strip()
|
||||
except KeyboardInterrupt:
|
||||
raise SystemExit(1)
|
||||
|
||||
if not username:
|
||||
print("A username is required to start the chat.")
|
||||
raise SystemExit(1)
|
||||
|
||||
try:
|
||||
asyncio.run(start_terminal_chat(username))
|
||||
except Exception as exc:
|
||||
print(f"Error while running Terminal Chat: {exc}")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user