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| 1 |
+
from fastapi import FastAPI, Request, Form, UploadFile, File
|
| 2 |
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
import sqlite3
|
| 5 |
+
import os
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# create folders
|
| 11 |
+
os.makedirs("uploads", exist_ok=True)
|
| 12 |
+
|
| 13 |
+
# database
|
| 14 |
+
conn = sqlite3.connect("chat.db", check_same_thread=False)
|
| 15 |
+
c = conn.cursor()
|
| 16 |
+
|
| 17 |
+
c.execute("""CREATE TABLE IF NOT EXISTS users(
|
| 18 |
+
username TEXT PRIMARY KEY,
|
| 19 |
+
password TEXT
|
| 20 |
+
)""")
|
| 21 |
+
|
| 22 |
+
c.execute("""CREATE TABLE IF NOT EXISTS messages(
|
| 23 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 24 |
+
username TEXT,
|
| 25 |
+
message TEXT,
|
| 26 |
+
image TEXT,
|
| 27 |
+
time TEXT
|
| 28 |
+
)""")
|
| 29 |
+
|
| 30 |
+
conn.commit()
|
| 31 |
+
|
| 32 |
+
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
| 33 |
+
|
| 34 |
+
# homepage
|
| 35 |
+
@app.get("/", response_class=HTMLResponse)
|
| 36 |
+
def home():
|
| 37 |
+
return """
|
| 38 |
+
<h1>Emalawi19 Chat</h1>
|
| 39 |
+
<a href="/login">Login</a><br>
|
| 40 |
+
<a href="/register">Register</a>
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
# register
|
| 44 |
+
@app.get("/register", response_class=HTMLResponse)
|
| 45 |
+
def register_form():
|
| 46 |
+
return """
|
| 47 |
+
<h2>Register</h2>
|
| 48 |
+
<form action="/register" method="post">
|
| 49 |
+
Username:<br>
|
| 50 |
+
<input name="username"><br>
|
| 51 |
+
Password:<br>
|
| 52 |
+
<input type="password" name="password"><br><br>
|
| 53 |
+
<button type="submit">Register</button>
|
| 54 |
+
</form>
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
@app.post("/register")
|
| 58 |
+
def register(username: str = Form(...), password: str = Form(...)):
|
| 59 |
+
try:
|
| 60 |
+
c.execute("INSERT INTO users VALUES(?,?)", (username,password))
|
| 61 |
+
conn.commit()
|
| 62 |
+
except:
|
| 63 |
+
pass
|
| 64 |
+
return RedirectResponse("/login", status_code=302)
|
| 65 |
+
|
| 66 |
+
# login
|
| 67 |
+
@app.get("/login", response_class=HTMLResponse)
|
| 68 |
+
def login_form():
|
| 69 |
+
return """
|
| 70 |
+
<h2>Login</h2>
|
| 71 |
+
<form action="/login" method="post">
|
| 72 |
+
Username:<br>
|
| 73 |
+
<input name="username"><br>
|
| 74 |
+
Password:<br>
|
| 75 |
+
<input type="password" name="password"><br><br>
|
| 76 |
+
<button type="submit">Login</button>
|
| 77 |
+
</form>
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
@app.post("/login")
|
| 81 |
+
def login(username: str = Form(...), password: str = Form(...)):
|
| 82 |
+
user = c.execute(
|
| 83 |
+
"SELECT * FROM users WHERE username=? AND password=?",
|
| 84 |
+
(username,password)
|
| 85 |
+
).fetchone()
|
| 86 |
+
|
| 87 |
+
if user:
|
| 88 |
+
return RedirectResponse(f"/chat/{username}", status_code=302)
|
| 89 |
+
|
| 90 |
+
return HTMLResponse("Login failed")
|
| 91 |
+
|
| 92 |
+
# chat page
|
| 93 |
+
@app.get("/chat/{username}", response_class=HTMLResponse)
|
| 94 |
+
def chat(username: str):
|
| 95 |
+
|
| 96 |
+
messages = c.execute(
|
| 97 |
+
"SELECT username,message,image,time FROM messages"
|
| 98 |
+
).fetchall()
|
| 99 |
+
|
| 100 |
+
chat_html = ""
|
| 101 |
+
|
| 102 |
+
for u,m,i,t in messages:
|
| 103 |
+
|
| 104 |
+
if m:
|
| 105 |
+
chat_html += f"<p><b>{u}</b>: {m} ({t})</p>"
|
| 106 |
+
|
| 107 |
+
if i:
|
| 108 |
+
chat_html += f"<p><b>{u}</b>:<br><img src='/uploads/{i}' width='200'></p>"
|
| 109 |
+
|
| 110 |
+
return f"""
|
| 111 |
+
<html>
|
| 112 |
+
<head>
|
| 113 |
+
<meta http-equiv="refresh" content="3">
|
| 114 |
+
</head>
|
| 115 |
+
|
| 116 |
+
<body>
|
| 117 |
+
|
| 118 |
+
<h2>Emalawi19 Chat - {username}</h2>
|
| 119 |
+
|
| 120 |
+
<div style="height:300px;overflow:auto;border:1px solid gray;">
|
| 121 |
+
{chat_html}
|
| 122 |
+
</div>
|
| 123 |
+
|
| 124 |
+
<br>
|
| 125 |
+
|
| 126 |
+
<form action="/send/{username}" method="post" enctype="multipart/form-data">
|
| 127 |
+
|
| 128 |
+
<input name="message" placeholder="Type message">
|
| 129 |
+
<input type="file" name="image">
|
| 130 |
+
|
| 131 |
+
<button type="submit">Send</button>
|
| 132 |
+
|
| 133 |
+
</form>
|
| 134 |
+
|
| 135 |
+
</body>
|
| 136 |
+
</html>
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
# send message
|
| 140 |
+
@app.post("/send/{username}")
|
| 141 |
+
async def send(username: str,
|
| 142 |
+
message: str = Form(""),
|
| 143 |
+
image: UploadFile = File(None)):
|
| 144 |
+
|
| 145 |
+
filename = None
|
| 146 |
+
|
| 147 |
+
if image:
|
| 148 |
+
filename = image.filename
|
| 149 |
+
path = f"uploads/{filename}"
|
| 150 |
+
|
| 151 |
+
with open(path,"wb") as f:
|
| 152 |
+
f.write(await image.read())
|
| 153 |
+
|
| 154 |
+
time = datetime.now().strftime("%H:%M")
|
| 155 |
+
|
| 156 |
+
c.execute(
|
| 157 |
+
"INSERT INTO messages(username,message,image,time) VALUES(?,?,?,?)",
|
| 158 |
+
(username,message,filename,time)
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
conn.commit()
|
| 162 |
+
|
| 163 |
+
return RedirectResponse(f"/chat/{username}", status_code=302)
|