-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.py
More file actions
379 lines (302 loc) · 13.9 KB
/
app.py
File metadata and controls
379 lines (302 loc) · 13.9 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
from datetime import date, datetime
from typing import Dict, List, Optional, Tuple, Union, Any
import logging
import os
from mwoauth import ConsumerToken, Handshaker, RequestToken
from flask import Flask, Response, jsonify, redirect, request, send_from_directory, send_file
from flask import session as flask_session
from flask_cors import CORS
from extensions import db, migrate
from config import config
from models import Book, Contest, ContestAdmin, IndexPage, User
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Determine static folder path - look for dist folder from frontend build
static_folder = os.path.join(os.path.dirname(__file__), 'dist')
if not os.path.exists(static_folder):
# If not found, look in parent directory structure
static_folder = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'wscontest', 'dist')
if not os.path.exists(static_folder):
static_folder = None
logger.warning("Frontend dist folder not found. Build the frontend first with 'npm run build'")
app: Flask = Flask(__name__, static_folder=static_folder, static_url_path='')
app.secret_key = config["APP_SECRET_KEY"]
app.config['SQLALCHEMY_DATABASE_URI'] = config["SQL_URI"]
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
migrate.init_app(app, db)
consumer_token: ConsumerToken = ConsumerToken(
config["CONSUMER_KEY"], config["CONSUMER_SECRET"]
)
WIKI_OAUTH_URL = "https://meta.wikimedia.org/w/index.php"
CORS(app, origins=[config["FRONTEND_URL"]], supports_credentials=True)
"""Static file serving for frontend"""
@app.route('/')
def serve_frontend():
"""Serve the main frontend application"""
if app.static_folder and os.path.exists(os.path.join(app.static_folder, 'index.html')):
return send_from_directory(app.static_folder, 'index.html')
else:
return jsonify({"message": "Frontend not built. Run 'npm run build' in the wscontest directory and copy dist folder to backend."}), 404
"""Legacy OAuth routes for backward compatibility"""
# Backward compatibility route for login
@app.route("/login")
def login_legacy() -> Response:
"""Legacy route for login - redirects to new API route"""
return login()
# Backward compatibility route for logout
@app.route("/logout")
def logout_legacy() -> Response:
"""Legacy route for logout - redirects to new API route"""
return logout()
# Backward compatibility route for OAuth callback
@app.route("/complete-login")
def complete_login_legacy() -> Response:
"""Legacy route for OAuth callback - redirects to new API route"""
return complete_login()
@app.route('/<path:path>')
def serve_static_files(path):
"""Serve static files (JS, CSS, images, etc.) and handle Vue Router"""
# Skip API routes - legacy routes are handled above
if path.startswith('api/'):
return jsonify({"error": "API endpoint not found"}), 404
if app.static_folder:
file_path = os.path.join(app.static_folder, path)
if os.path.exists(file_path):
return send_from_directory(app.static_folder, path)
else:
# For Vue Router - serve index.html for unknown routes (SPA routing)
if os.path.exists(os.path.join(app.static_folder, 'index.html')):
return send_from_directory(app.static_folder, 'index.html')
return jsonify({"error": "File not found"}), 404
"""oAuth logic"""
@app.route("/api/login")
def login() -> Response:
handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)
redirect_url, request_token = handshaker.initiate()
flask_session['request_token_key'] = request_token.key
flask_session['request_token_secret'] = request_token.secret
flask_session['return_to_url'] = request.args.get('next', config["FRONTEND_URL"])
return redirect(redirect_url)
@app.route("/api/logout")
def logout() -> Response:
flask_session.clear()
return redirect(request.args.get('next', '/'))
@app.route("/api/complete-login")
def complete_login() -> Response:
handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)
rt_key = flask_session.get('request_token_key')
rt_secret = flask_session.get('request_token_secret')
if not rt_key or not rt_secret:
return redirect('/api/login')
request_token = RequestToken(rt_key, rt_secret)
try:
access_token = handshaker.complete(request_token, request.query_string)
identity = handshaker.identify(access_token)
userid = identity['sub']
username = identity['username']
# Store user info in session
flask_session['userid'] = userid
flask_session['username'] = username
logger.info(f"Logged in user: {username} (ID: {userid})")
# Always redirect to frontend after successful login
return_url = flask_session.pop('return_to_url', config["FRONTEND_URL"])
return redirect(return_url)
except Exception as e:
logger.error(f"OAuth error: {e}")
return redirect('/api/login')
""" Logical routes for the app """
def get_current_user(cached: bool = True) -> Optional[str]:
return flask_session.get('username')
@app.route("/api/user", methods=["GET"])
def get_user_info() -> Tuple[Response, int]:
username = get_current_user()
if username:
return jsonify({
"logged_in": True,
"username": username,
"userid": flask_session.get('userid')
}), 200
else:
return jsonify({
"logged_in": False,
"username": None,
"userid": None
}), 200
@app.route("/api/graph-data", methods=["GET"])
def graph_data() -> Response:
return jsonify("graph data here")
@app.route("/api/contest/create", methods=["POST"])
def create_contest() -> Tuple[Response, int]:
if get_current_user(False) is None:
return (
jsonify("Please login!"),
403,
)
if request.method == "POST":
try:
data: Dict[str, Any] = request.json
contest: Contest = Contest(
name=data["name"],
created_by=get_current_user(),
start_date=date.fromisoformat(data["start_date"]),
end_date=date.fromisoformat(data["end_date"]),
status=True,
point_per_proofread=int(data["proofread_points"]),
point_per_validate=int(data["validate_points"]),
lang=data["language"],
)
db.session.add(contest)
book_names: List[str] = data.get("book_names").split("\n")
for book in book_names:
book_name = book.split(":")[1]
existing_book: Optional[Book] = Book.query.filter_by(name=book_name).first()
if existing_book:
# Book already exists, add this contest to it if not already added
if contest not in existing_book.contests:
existing_book.contests.append(contest)
else:
# Create new book and add the contest to it
new_book = Book(name=book_name)
new_book.contests.append(contest)
db.session.add(new_book)
admins: List[str] = data.get("admins").split("\n")
for admin_name in admins:
admin: Optional[ContestAdmin] = ContestAdmin.query.filter_by(user_name=admin_name).first()
if admin:
admin.contests.append(contest)
else:
db.session.add(ContestAdmin(user_name=admin_name, contests=[contest]))
db.session.commit()
return jsonify({"success": True}), 200
except Exception as e:
logger.error(f"Error creating contest: {e}")
return jsonify({"success": False, "message": str(e)}), 404
@app.route("/api/contests", methods=["GET"])
def contest_list() -> Tuple[Response, int]:
contests: List[Contest] = Contest.query.all()
result = []
for contest in contests:
current_date = datetime.now().date()
contest_end_date = contest.end_date.date() if hasattr(contest.end_date, 'date') else contest.end_date
is_running = current_date <= contest_end_date and contest.status is not False
result.append({
"id": contest.cid,
"name": contest.name,
"start_date": contest.start_date.strftime("%d-%m-%Y"),
"end_date": contest.end_date.strftime("%d-%m-%Y"),
"status": is_running,
})
return jsonify(result), 200
@app.route("/api/contest/<int:id>")
def contest_by_id(id: int) -> Tuple[Response, int]:
contest: Optional[Contest] = Contest.query.get(id)
if not contest:
return jsonify("Contest with this id does not exist!"), 404
else:
data: Dict[str, Any] = {}
data["contest_details"] = {
"cid": contest.cid,
"name": contest.name,
"created_by": contest.created_by,
"createdon": contest.createdon.isoformat() if contest.createdon else None,
"start_date": contest.start_date.isoformat() if contest.start_date else None,
"end_date": contest.end_date.isoformat() if contest.end_date else None,
"status": contest.status,
"point_per_proofread": contest.point_per_proofread,
"point_per_validate": contest.point_per_validate,
"lang": contest.lang
}
data["adminstrators"] = [admin.user_name for admin in contest.admins]
data["books"] = [book.name for book in contest.books]
data["users"] = []
for user in contest.users:
proofread_count: int = len(user.proofread_pages)
validated_count: int = len(user.validated_pages)
points: int = (proofread_count * contest.point_per_proofread) + (
validated_count * contest.point_per_validate
)
user_pages = []
contest_book_names = [book.name for book in contest.books]
for page in IndexPage.query.filter(
(IndexPage.validator_username == user.user_name) |
(IndexPage.proofreader_username == user.user_name)
).all():
if page.book_name in contest_book_names:
user_pages.append({
"id": page.id,
"page_name": page.page_name,
"book_name": page.book_name,
"validate_time": page.validate_time.isoformat() if page.validate_time else None,
"proofread_time": page.proofread_time.isoformat() if page.proofread_time else None,
"v_revision_id": page.v_revision_id,
"p_revision_id": page.p_revision_id
})
data["users"].append({
user.user_name: {
"proofread_count": proofread_count,
"validated_count": validated_count,
"points": points,
"pages": user_pages,
}
})
return jsonify(data), 200
@app.route("/api/contest/<int:id>/status", methods=["PATCH"])
def update_contest_status(id: int) -> Tuple[Response, int]:
current_user = get_current_user(False)
if current_user is None:
return jsonify({"success": False, "message": "Please login!"}), 403
contest: Optional[Contest] = Contest.query.get(id)
if not contest:
return jsonify({"success": False, "message": "Contest not found!"}), 404
# Check if user is an admin of this contest
is_admin = any(admin.user_name == current_user for admin in contest.admins)
if not is_admin:
return jsonify({"success": False, "message": "Unauthorized! Only contest admins can update status."}), 403
try:
data = request.json
new_status = data.get('status')
if new_status is None:
return jsonify({"success": False, "message": "Status field is required"}), 400
contest.status = new_status
db.session.commit()
return jsonify({"success": True, "message": f"Contest {'opened' if new_status else 'closed'} successfully"}), 200
except Exception as e:
db.session.rollback()
return jsonify({"success": False, "message": str(e)}), 500
@app.route("/api/contest/<int:id>", methods=["PUT"])
def update_contest(id: int) -> Tuple[Response, int]:
current_user = get_current_user(False)
if current_user is None:
return jsonify({"success": False, "message": "Please login!"}), 403
contest: Optional[Contest] = Contest.query.get(id)
if not contest:
return jsonify({"success": False, "message": "Contest not found!"}), 404
# Check if user is an admin of this contest
is_admin = any(admin.user_name == current_user for admin in contest.admins)
if not is_admin:
return jsonify({"success": False, "message": "Unauthorized! Only contest admins can edit contest."}), 403
try:
data = request.json
# Update contest fields
if 'name' in data:
contest.name = data['name']
if 'start_date' in data:
contest.start_date = date.fromisoformat(data['start_date'])
if 'end_date' in data:
contest.end_date = date.fromisoformat(data['end_date'])
if 'point_per_proofread' in data:
contest.point_per_proofread = int(data['point_per_proofread'])
if 'point_per_validate' in data:
contest.point_per_validate = int(data['point_per_validate'])
db.session.commit()
return jsonify({"success": True, "message": "Contest updated successfully"}), 200
except Exception as e:
db.session.rollback()
return jsonify({"success": False, "message": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True)