-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathug_fess.py
279 lines (213 loc) · 8.17 KB
/
ug_fess.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import sys
sys.dont_write_bytecode = True
import os
import re
import django
from django.apps import apps
from django.conf import settings
from django.utils import timezone
import filetype
import streamlit as st
from streamlit.delta_generator import DeltaGenerator
from streamlit.runtime.uploaded_file_manager import UploadedFile
from auth import authenticate
from content_moderation import (
has_disallowed_entities,
has_inappropriate_content,
has_inappropriate_image,
)
from x import create_tweet, is_valid_tweet_url, upload_images
if not settings.configured or not apps.ready:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_settings")
django.setup()
from db.models import Menfess, User
MAX_MENFESS_PER_USER_PER_DAY = 3
MENFESS_SIGNATURE = "yuji!"
X_MAX_IMAGE_ATTACHMENTS = 4
MAX_IMAGE_SIZE_BYTES = 5 * 1024 * 1024
ALLOWED_IMAGE_EXTS = ["jpeg", "jpg", "png", "webp"]
ALLOWED_IMAGE_MIME_TYPES = {"image/jpeg", "image/png", "image/webp"}
MAX_QRT_URL_LENGTH = 54
@st.dialog("Status")
def show_menfess_creation_status(status_type: str, message: str) -> None:
if status_type == "success":
st.success(message)
elif status_type == "error":
st.error(message)
def can_create_menfess_today(user_id: int) -> bool:
today = timezone.localdate()
today_menfess_count = Menfess.objects.filter(
user_id=user_id, created_at__date=today
).count()
return today_menfess_count < MAX_MENFESS_PER_USER_PER_DAY
def has_invalid_image(images: list[UploadedFile]) -> bool:
for image in images:
if image.size > MAX_IMAGE_SIZE_BYTES:
return True
_, image_ext = os.path.splitext(image.name)
image_ext = image_ext[1:]
if image_ext not in ALLOWED_IMAGE_EXTS:
return True
image.seek(0)
kind = filetype.guess(image)
if (
kind is None
or kind.extension not in ALLOWED_IMAGE_EXTS
or kind.mime != image.type
or image.type not in ALLOWED_IMAGE_MIME_TYPES
):
return True
return False
def sign_in(username: str, password: str, error_placeholder: DeltaGenerator) -> None:
try:
if authenticate(username, password):
user = User.objects.get_or_create(username=username)[0]
if user.is_banned:
error_placeholder.error(
"Sorry, lo di-ban dari UG FESS karena ngelanggar rules!"
)
return
st.session_state.user_id = user.user_id
st.session_state.is_authenticated = True
st.rerun()
else:
error_placeholder.error(
"Username atau password yang lo masukin salah nih. Coba cek lagi ya!"
)
except Exception as e:
print(e)
error_placeholder.error(
"Sign in lagi bermasalah nih :disappointed:. Coba lagi nanti ya!"
)
def tweet_menfess(text: str, images: list[UploadedFile], qrt: str) -> None:
try:
if not can_create_menfess_today(st.session_state.user_id):
show_menfess_creation_status(
"error",
f"Yah, udah nyentuh limit kirim menfess hari ini. Max {MAX_MENFESS_PER_USER_PER_DAY} menfess aja ya "
"per hari. Coba lagi besok :smiley:",
)
return
if qrt:
if len(qrt) > MAX_QRT_URL_LENGTH:
show_menfess_creation_status(
"error",
f"QRT-nya ga valid nih, maks {MAX_QRT_URL_LENGTH} karakter aja ya!",
)
return
qrt_match = re.search(r"https://x\.com/ug_fess/status/(\d+)", qrt)
if qrt_match is None or not is_valid_tweet_url(qrt):
show_menfess_creation_status(
"error",
"QRT-nya ga valid nih. Pastiin lo QRT tweet dari @ug_fess ya!",
)
return
qrt_id = qrt_match.group(1)
else:
qrt_id = None
if text:
if MENFESS_SIGNATURE in text.lower():
show_menfess_creation_status(
"error",
f"Menfess-nya jangan ada reserved keyword ***{MENFESS_SIGNATURE}*** ya! Biar sistem aja yang "
f"nambahin ***{MENFESS_SIGNATURE}***-nya.",
)
return
if has_disallowed_entities(text):
show_menfess_creation_status(
"error", "Menfess-nya ga boleh ada #, @, atau URL ya!"
)
return
if has_inappropriate_content(text):
show_menfess_creation_status(
"error",
"Menfess-nya ga boleh ada konten yang inappropriate ya! Baca lagi rules-nya.",
)
return
text = f"{MENFESS_SIGNATURE} {text}"
if images:
if len(images) > X_MAX_IMAGE_ATTACHMENTS:
show_menfess_creation_status(
"error", f"Max {X_MAX_IMAGE_ATTACHMENTS} images aja ya!"
)
return
if has_invalid_image(images):
show_menfess_creation_status(
"error", "Image-nya ada yang ga valid. Coba cek lagi!"
)
return
if has_inappropriate_image(images):
show_menfess_creation_status(
"error", "Ga boleh ada adult, racy, atau gory images ya!"
)
return
media_ids = upload_images(images)
else:
media_ids = None
tweet_or_tweets = create_tweet(text, media_ids, qrt_id)
if isinstance(tweet_or_tweets, list):
tweet = tweet_or_tweets[0]
else:
tweet = tweet_or_tweets
Menfess.objects.create(tweet_id=tweet.id, user_id=st.session_state.user_id)
show_menfess_creation_status(
"success", "Yay! Menfess lo udah di-tweet :smiley:"
)
except Exception as e:
print(e)
show_menfess_creation_status(
"error",
"Lagi ga bisa kirim menfess nih :disappointed:. Coba lagi nanti ya!",
)
def sign_out():
del st.session_state["user_id"]
st.session_state.is_authenticated = False
st.rerun()
def sign_in_form():
st.header("Eitss, sign in dulu!", anchor=False)
st.write(
"Sign in pake kredensial Student Site ya! Buat verifikasi kalo lo emang anak Gundar."
)
st.caption(
"Tenang aja, password lo ga bakal disimpen kok. Sistem cuma nyimpen username lo aja. Kalo lo masih ragu, "
"lo bisa cek codebase UG FESS di [github.com/nxgeo/ug-fess](https://github.com/nxgeo/ug-fess)."
)
error_placeholder = st.empty()
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Sign in"):
if username and password:
sign_in(username, password, error_placeholder)
def main_page():
st.header("Mau kirim menfess apa?", anchor=False)
menfess_submission_form = st.form(
"menfess_submission_form", clear_on_submit=True, enter_to_submit=False
)
text = menfess_submission_form.text_area("Ketikin menfess lo di sini:")
images = menfess_submission_form.file_uploader(
f"Lo juga bisa upload images (max {X_MAX_IMAGE_ATTACHMENTS}):",
type=ALLOWED_IMAGE_EXTS,
accept_multiple_files=True,
)
qrt = menfess_submission_form.text_input(
"QRT (opsional):",
max_chars=MAX_QRT_URL_LENGTH,
help="Contoh: https[]()://x.com/ug_fess/status/1845753430381662319",
)
if menfess_submission_form.form_submit_button():
if text or images:
tweet_menfess(text, images, qrt)
st.divider()
st.subheader("Mau sign out?", anchor=False)
st.write(
"Kalo lo mau sign out, tinggal refresh (CTRL + R) aja atau klik button :point_down:"
)
if st.button("Sign out"):
sign_out()
if "is_authenticated" not in st.session_state:
st.session_state.is_authenticated = False
st.set_page_config(page_title="UG FESS", page_icon=":flying_saucer:")
if st.session_state.is_authenticated:
main_page()
else:
sign_in_form()