-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
126 lines (107 loc) · 3.98 KB
/
app.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
from werkzeug.exceptions import RequestEntityTooLarge
from firebase import firebase
import json
import re
from flask_cors import CORS
from ThunderWeapon import Uploader, DiceBot
from datetime import datetime, tzinfo, timedelta
from os.path import join, dirname
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import os
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
firebase = firebase.FirebaseApplication(os.getenv("FIREBASE_URL"), None)
app = Flask("ChatServer")
def rate_limit_from_config():
return app.config.get("API_LIMIT", "50/hour")
app.config['API_LIMIT'] = '50/hour'
limitter = Limiter(
app,
key_func=get_remote_address,
)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024 - 1
cors = CORS(app)
class JST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=9)
def dst(self, dt):
return timedelta(0)
def tzname(self, dt):
return 'JST'
@app.route("/", methods=["POST"])
def chat():
def validator(data):
for i in ["user", "text", "color"]:
a = data.get(i, None)
if a is None:
raise ValueError(i)
elif a == "":
raise ValueError(i)
if not re.match(r"^#[0-9a-fA-F]{6}$", data.get("color")):
raise ValueError("invalid color code")
try:
data = json.loads(request.data.decode('utf-8'))
if data.get('time', None) is None:
data['time'] = datetime.now(tz=JST()).strftime("%H:%M")
validator(data)
firebase.post('/boards/chat', data)
dicebot = DiceBot()
roll_result = dicebot.roll(data["text"])
if roll_result is not None:
res = {}
res["text"] = dicebot.template(roll_result, data["user"])
res["color"] = "#0F7001"
res["user"] = "DiceBot"
res["time"] = datetime.now(tz=JST()).strftime("%H:%M")
firebase.post('/boards/chat', res)
res = jsonify({"status": "ok"})
res.headers.add('Access-Control-Allow-Origin', '*')
res.headers.add('Access-Control-Allow-Methods',
'OPTIONS, GET,PUT,POST,DELETE')
res.status_code = 201
return res
except Exception as e:
print(e)
res = jsonify({"status": "fail"})
res.headers.add('Access-Control-Allow-Origin', '*')
res.headers.add('Access-Control-Allow-Methods',
'OPTIONS, GET,PUT,POST,DELETE')
res.status_code = 400
return res
@app.route("/upload", methods=["POST"])
@limitter.limit(rate_limit_from_config, error_message='api limit')
def upload():
try:
f = request.files['file']
uploader = Uploader()
result = uploader.upload(f)
firebase.post('/boards/assets', result)
result.update({"status": "ok"})
response = jsonify(result)
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Methods',
'OPTIONS, GET,PUT,POST,DELETE')
response.status_code = 201
return response
except RequestEntityTooLarge as e:
app.logger.debug(e)
response = jsonify({"status": "fail", "message": e.args})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Methods',
'OPTIONS, GET,PUT,POST,DELETE')
response.status_code = 413
return response
except Exception as e:
app.logger.debug(e)
response = jsonify({"status": "fail", "message": e.args})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Methods',
'OPTIONS, GET,PUT,POST,DELETE')
response.status_code = 400
return response
if __name__ == '__main__':
app.run(host="0.0.0.0")