forked from 2minchul/conectus-user-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
84 lines (62 loc) · 2.16 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import asyncio
import async_timeout
from pubmarine import PubPen
from sanic import Sanic, response
from sanic.request import Request
from sanic.response import json
from sanic.websocket import WebSocketProtocol, ConnectionClosed, WebSocketCommonProtocol
from util import arp
from db import sqlite
from api import admin_api
import ujson
from websocket import make_reply
app = Sanic()
app.event: PubPen
@app.listener('before_server_start')
async def setup_db(_app, loop):
await sqlite.make_table()
_app.event = PubPen(loop)
@app.route("/")
async def test(request):
return response.redirect('/chat.html')
@app.websocket('/websocket/')
async def start_websocket(request, ws: WebSocketCommonProtocol):
ws.mac = None
await set_user(request, ws)
def recv_msg(_data: dict):
app.loop.create_task(ws.send(ujson.dumps(_data)))
app.event.subscribe('chat', recv_msg)
async def communicate():
while True:
async with async_timeout.timeout(10.0):
data = await ws.recv()
if data == 'ping':
await asyncio.sleep(0)
continue
print('Received: ' + data)
reply = await make_reply(data, request, ws, app.event)
print('Sending: {}'.format(reply))
async with async_timeout.timeout(10.0):
await ws.send(reply)
try:
await communicate()
except (ConnectionClosed, asyncio.TimeoutError, asyncio.base_futures.InvalidStateError):
print('ConnectionClosed')
await websocket_closed(request, ws)
async def set_user(request: Request, ws):
ws.mac = await arp.get_mac_address_in_thread(request.ip)
print(ws.mac)
async def websocket_closed(request, ws):
print('closed')
if ws.mac:
await asyncio.gather(admin_api.delete_user(ws.mac), sqlite.disable_user(ws.mac))
@app.route("/users/<user_id>")
def chat_from_admin(request: Request, user_id):
data = request.json
print(data)
return ''
app.static('/', './static')
if __name__ == "__main__":
_loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(_loop)
app.run(host="0.0.0.0", port=8080, protocol=WebSocketProtocol)