-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.py
322 lines (277 loc) · 7.93 KB
/
server.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#
# twitterbot2
#
# edoardottt
# edoardoottavianelli.it
# https://github.com/edoardottt/twitterbot2
#
# This repository is under GPL-3 License.
#
#
# This file contains the backend code and
# API logic for the web service.
#
from flask import Flask
from flask import request
from flask.templating import render_template
import datetime
import db
from dateutil.parser import parse
import threading
app = Flask(__name__, template_folder="templates")
app.config["SECRET_KEY"] = "ILVYilvbthLQETHeteggrgwi2r389"
# Needed for uptime
starting_time = datetime.datetime.now()
@app.route("/")
def hello():
conn = db.conn_db()
users = db.all_users(conn)
return render_template("index.html", len=len(users), users=users)
def user_ok(user):
"""
This function checks if a username is correct.
"""
if user is None:
return False
if len(user) == 0:
return False
conn = db.conn_db()
users = db.all_users(conn)
for param in users:
if user == param[0]:
return True
return False
@app.route("/dashboard")
def user_dashboard():
user = request.args.get("user")
if not user_ok(user):
return render_template("error.html", errormsg="Invalid username.")
# if user ok ->
conn = db.conn_db()
values = db.today_stats(conn, user)
today_show = 1
if values is None:
today_show = 0
else:
(
username,
today,
tweet_count,
likes_count,
retweet_count,
followers_count,
) = values
values = db.user_stats(conn, user)
if values is None:
return render_template("error.html", errormsg="No data for this user.")
# render last 50 logs
logs_line = 50
logs = []
render_logs = 1
try:
with open("twitterbot2.log", "r") as f:
text = f.read().split("\n")
if len(text) > logs_line:
start = len(text) - logs_line - 1
else:
start = 0
for line in text[start:]:
if line.strip() != "":
logs.append(line)
except Exception:
render_logs = 0
if not today_show:
(
tweet_count,
likes_count,
retweet_count,
followers_count,
) = ("", "", "", "")
uptime = "🟢Uptime: " + str(datetime.datetime.now() - starting_time)
for thread in threading.enumerate():
if thread.name == "bot":
if not thread.is_alive():
uptime = "🔴Uptime: Dead"
break
return render_template(
"dashboard.html",
user=user,
update=datetime.datetime.now().strftime("%d %b %Y %H:%M:%S"),
tweets=tweet_count,
likes=likes_count,
retweets=retweet_count,
followers=followers_count,
values=values,
today_show=today_show,
len=len(logs),
logs=logs,
render_logs=render_logs,
uptime=str(uptime).split(".")[0],
)
@app.route('/api/docs')
def get_docs():
return render_template('swaggerui.html')
# ---------------------------------------------------------
# ------------------------ API ----------------------------
# ---------------------------------------------------------
@app.route("/api/health")
def api_health():
"""
Server health endpoint.
"""
for thread in threading.enumerate():
if thread.getName() == "bot" and not thread.is_alive():
return "error", 500
return "ok"
@app.route("/api/tweets/<user>")
def api_user_tweets(user):
"""
Total tweets for user <user>.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
# if user ok ->
conn = db.conn_db()
values = db.user_stats(conn, user)
if values is None:
return "ERROR: No data for this user.", 404
else:
result = 0
for i in range(0, len(values)):
result += values[i][2]
return str(result)
@app.route("/api/likes/<user>")
def api_user_likes(user):
"""
Total likes for user <user>.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
# if user ok ->
conn = db.conn_db()
values = db.user_stats(conn, user)
if values is None:
return "ERROR: No data for this user.", 404
else:
result = 0
for i in range(0, len(values)):
result += values[i][3]
return str(result)
@app.route("/api/retweets/<user>")
def api_user_retweets(user):
"""
Total retweets for user <user>.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
# if user ok ->
conn = db.conn_db()
values = db.user_stats(conn, user)
if values is None:
return "ERROR: No data for this user.", 404
else:
result = 0
for i in range(0, len(values)):
result += values[i][4]
return str(result)
@app.route("/api/followers/<user>")
def api_user_followers(user):
"""
Latest follower count for user <user>.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
# if user ok ->
conn = db.conn_db()
values = db.user_stats(conn, user)
if values is None:
return "ERROR: No data for this user.", 404
else:
result = values[len(values) - 1][5]
return str(result)
def string_to_date(date):
"""
@Input: string
@Output: string
This function tries to convert a string into a date,
if it's not possible return an empty string.
"""
try:
converted = parse(date)
return converted
except Exception:
return ""
@app.route("/api/tweets/<user>/<date>")
def api_user_date_tweets(user, date):
"""
Tweets for user <user> in date <date>.
Date format: YYYY-MM-DD.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
if string_to_date(date) == "":
return "ERROR: Invalid date.", 400
# if checks ok ->
conn = db.conn_db()
values = db.user_date_stats(conn, user, date)
if values is None or len(values) == 0:
return "ERROR: No data for this user on this day.", 404
else:
result = values[0][2]
return str(result)
@app.route("/api/likes/<user>/<date>")
def api_user_date_likes(user, date):
"""
Likes for user <user> in date <date>.
Date format: YYYY-MM-DD.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
if string_to_date(date) == "":
return "ERROR: Invalid date.", 400
# if checks ok ->
conn = db.conn_db()
values = db.user_date_stats(conn, user, date)
if values is None or len(values) == 0:
return "ERROR: No data for this user on this day.", 404
else:
result = values[0][3]
return str(result)
@app.route("/api/retweets/<user>/<date>")
def api_user_date_retweets(user, date):
"""
Retweets for user <user> in date <date>.
Date format: YYYY-MM-DD.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
if string_to_date(date) == "":
return "ERROR: Invalid date.", 400
# if checks ok ->
conn = db.conn_db()
values = db.user_date_stats(conn, user, date)
if values is None or len(values) == 0:
return "ERROR: No data for this user on this day.", 404
else:
result = values[0][4]
return str(result)
@app.route("/api/followers/<user>/<date>")
def api_user_date_followers(user, date):
"""
Followers for user <user> in date <date>.
Date format: YYYY-MM-DD.
"""
if not user_ok(user):
return "ERROR: Invalid username.", 404
if string_to_date(date) == "":
return "ERROR: Invalid date.", 400
# if checks ok ->
conn = db.conn_db()
values = db.user_date_stats(conn, user, date)
if values is None or len(values) == 0:
return "ERROR: No data for this user on this day.", 404
else:
result = values[0][5]
return str(result)
if __name__ == "__main__":
app.run()