/
TranslationWebServer.py
593 lines (451 loc) · 20.5 KB
/
TranslationWebServer.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
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Translation Web Server
# Copyright © 2012 Luca Wehrstedt <luca.wehrstedt@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import time
import os.path
import simplejson as json
import base64
from datetime import datetime
from tornado.web import HTTPError, Application, RequestHandler, StaticFileHandler, authenticated, asynchronous
from tornado.ioloop import IOLoop
from Teams import teams as team_names
from Langs import langs as lang_names
from Teams2Langs import teams_to_langs
from Langs2Teams import langs_to_teams
from Logger import logger
teams = dict()
tasks = dict()
def init():
# Load teams and tasks from disk
teams_path = os.path.join(os.path.dirname(__file__), "teams")
for f_name in os.listdir(teams_path):
if f_name.endswith(".json"):
name = f_name[:-5]
path = os.path.join(teams_path, f_name)
try:
teams[name] = json.load(open(path))
except IOError:
logger.error("Couldn't read data for team %s" % name)
except ValueError:
logger.error("Couldn't load data for team %s" % name)
tasks_path = os.path.join(os.path.dirname(__file__), "tasks")
for f_name in os.listdir(tasks_path):
if f_name.endswith(".json"):
name = f_name[:-5]
path = os.path.join(tasks_path, f_name)
try:
tasks[name] = json.load(open(path))
except IOError:
logger.error("Couldn't read data for task %s" % name)
except ValueError:
logger.error("Couldn't load data for task %s" % name)
# TODO Notify if some teams are missing or shouldn't be there
# Add needed structures to teams and tasks
for team in teams.itervalues():
team.setdefault("tasks", {})
team.setdefault("langs", {})
team.setdefault("selected", [])
for task in tasks.itervalues():
task.setdefault("teams", {})
task.setdefault("langs", {})
init()
class BaseHandler(RequestHandler):
"""Base RequestHandler for this application.
"""
def get_current_user(self):
"""Gets the current user logged in from the cookies
"""
return self.get_secure_cookie("login")
class MainHandler(BaseHandler):
"""Home page handler.
"""
def get(self):
team = self.current_user
self.render("overview.html",
global_team=team,
global_teams=teams, global_tasks=tasks,
lang_names=lang_names, team_names=team_names,
teams_to_langs=teams_to_langs,
login_error=bool(self.get_argument("login_error", "")))
class LoginHandler(BaseHandler):
"""Login handler
"""
def post(self):
username = self.get_argument("username", "")
password = self.get_argument("password", "")
if username not in teams:
logger.warn("Wrong username (%s / %s)." % (username, password))
self.redirect("/?login_error=1")
return
if teams[username]["password"] != password:
logger.warn("Wrong password (%s / %s)." % (username, password))
self.redirect("/?login_error=1")
return
self.set_secure_cookie("login", username, expires_days=None)
self.redirect("/")
class LogoutHandler(BaseHandler):
"""Logout handler
"""
def get(self):
self.clear_cookie("login")
self.redirect("/")
class MessageProxy(object):
def __init__(self):
self.clients = list()
# We keep a buffer of sent messages, to send them to the clients
# that temporarily lose the connection, to avoid them missing
# any data.
self.buffer = list()
# The "age" of the buffers is the minimum time such that we are
# sure to have all events that happened after that time.
self.age = time.time()
def send(self, event, data, target):
timestamp = time.time()
message = 'id: %0.6f\n' \
'event: %s\n' \
'data: %s\n' \
'\n' % (timestamp, event, data)
for client in self.clients:
client(message, target)
self.buffer.append((timestamp, message, target))
def add_callback(self, callback):
self.clients.append(callback)
def remove_callback(self, callback):
self.clients.remove(callback)
proxy = MessageProxy()
class EventHandler(BaseHandler):
@authenticated
@asynchronous
def get(self):
self.set_status(200)
self.set_header('Content-Type', 'text/event-stream')
self.set_header('Cache-Control', 'no-cache')
self.flush()
# This is only needed to make Firefox fire the 'open' event on
# the EventSource object.
self.write(':\n')
self.flush()
# The EventSource polyfill will only deliver events once the
# connection has been closed, so we have to finish the request
# right after the first message has been sent. This custom
# header allows us to identify the requests from the polyfill.
self.one_shot = False
if 'X-Requested-With' in self.request.headers and \
self.request.headers['X-Requested-With'] == 'XMLHttpRequest':
self.one_shot = True
# We get the ID of the last event the client received. We
# assume that if the header is missing the client didn't
# receive any event. In that case we send the entire history
# (well, not really, but we try to achieve the same effect).
if "Last-Event-ID" in self.request.headers:
last_id = float(self.request.headers.get_list("Last-Event-ID")[-1])
else:
last_id = None
self.outdated = False
if last_id is not None and last_id < proxy.age:
self.outdated = True
# The reload event will tell the client that we can't update
# its data using buffered event and that it'll need to init
# it again from scratch (in pratice: reload the page).
self.write("event: reload\n")
self.write("data: _\n\n")
# We're keeping the connection open because we want the
# client to close it. If we'd close it the client (i.e. the
# browser) may automatically attempt to reconnect before
# having processed the event we sent it.
if self.one_shot:
self.finish()
# Not calling .clean() because there's nothing to be
# cleaned yet and because it would have no effect,
# since self.outdated == True.
else:
self.flush()
return
if last_id is None:
timestamp = time.time()
for task in tasks:
for lang in tasks[task]["langs"]:
for team in tasks[task]["langs"][lang]:
self.send_event("id: %0.6f\n" \
"event: create\n" \
"data: %s %s %s\n" \
"\n" % (timestamp, team, lang, task), '*')
for s in teams[self.current_user]["selected"]:
self.send_event("id: %0.6f\n" \
"event: select\n" \
"data: %s %s %s\n" \
"\n" % (timestamp, s[0], s[1], s[2]), self.current_user)
else:
sent = False
for t, message, target in proxy.buffer:
if t > last_id:
self.send_event(message, target)
sent = True
if sent and self.one_shot:
self.finish()
# Not calling .clean() because there's nothing to be
# cleaned yet
return
proxy.add_callback(self.send_event)
def callback():
self.finish()
self.clean()
# FIXME put the timeout (i.e. 600) in a better location
self.timeout = IOLoop.instance().add_timeout(
time.time() + 600, callback)
# If the connection is closed by the client then the "on_connection_
# _close" callback is called. If we decide to finish the request (by
# calling the finish() method) then the "on_finish" callback gets
# called (and "on_connection_close" *won't* be called!).
def clean(self):
if not self.outdated:
proxy.remove_callback(self.send_event)
IOLoop.instance().remove_timeout(self.timeout)
def on_connection_close(self):
self.clean()
# TODO As soon as we start supporting only Tornado 2.2+ use the
# .on_finish() callback to call .clean() instead of doing it after
# every call to .finish().
def send_event(self, message, target):
if target == '*' or target == self.current_user:
self.write(message)
if self.one_shot:
self.finish()
self.clean()
else:
self.flush()
class TranslationHandler(StaticFileHandler):
def get_current_user(self):
return self.get_secure_cookie("login")
def initialize(self):
StaticFileHandler.initialize(self, os.path.join(os.path.dirname(__file__), "data"))
def head(self, team, lang, task):
path = os.path.join(task, "by_team", "%s (%s).pdf" % (team, lang))
self.set_header("Content-Disposition", "attachment; filename=\"%s (%s, %s).pdf\"" % (task, lang, team))
StaticFileHandler.get(self, path, include_body=False)
def get(self, team, lang, task):
path = os.path.join(task, "by_team", "%s (%s).pdf" % (team, lang))
self.set_header("Content-Disposition", "attachment; filename=\"%s (%s, %s).pdf\"" % (task, lang, team))
StaticFileHandler.get(self, path)
@authenticated
def post(self, team, lang, task):
if team != self.current_user:
logger.warn("Team %s said to be %s while creating translation of %s in %s." % (self.current_user, team, task, lang))
raise HTTPError(403)
if lang not in lang_names:
logger.warn("Team %s tried to create a translation in %s" % (team, lang))
raise HTTPError(404)
if task not in tasks:
logger.warn("Team %s tried to create a translation of %s" % (team, task))
raise HTTPError(404)
if lang in teams[team]["tasks"].get(task, []):
logger.warn("Team %s tried to create a translation that already exists (%s into %s)" % (team, task, lang))
raise HTTPError(405)
self._save(team, lang, task)
proxy.send("create", "%s %s %s" % (team, lang, task), '*')
@authenticated
def put(self, team, lang, task):
if team != self.current_user:
logger.warn("Team %s said to be %s while updating translation of %s in %s." % (self.current_user, team, task, lang))
raise HTTPError(403)
if lang not in teams[team]["tasks"].get(task, []):
logger.warn("Team %s tried to update a translation that doesn't exists (%s in %s)" % (team, task, lang))
raise HTTPError(404)
self._save(team, lang, task)
proxy.send("update", "%s %s %s" % (team, lang, task), '*')
def _save(self, team, lang, task):
timestamp = datetime.now()
logger.info("Team %s uploaded translation of task %s into %s" % (team, task, lang))
# Try immediately to save the file in the history
path = os.path.join(os.path.dirname(__file__), "history",
"%s %s %s %s.pdf" % (timestamp, team, task, lang))
try:
open(path, "wb").write(self.request.body)
except IOError:
logger.error("Couldn't save translation of task %s into %s, made by %s, in the history." % (task, lang, team))
raise HTTPError(500)
# Update the task and team data
task_path = os.path.join(os.path.dirname(__file__),
"tasks", "%s.json" % task)
tasks[task]["teams"][team] = sorted(set(tasks[task]["teams"].get(team, []) + [lang]))
tasks[task]["langs"][lang] = sorted(set(tasks[task]["langs"].get(lang, []) + [team]))
try:
json.dump(tasks[task], open(task_path, "w"), indent=4)
except IOError:
logger.error("Couldn't write data for task %s" % task)
raise HTTPError(500)
except ValueError:
logger.error("Couldn't dump data for task %s" % task)
raise HTTPError(500)
team_path = os.path.join(os.path.dirname(__file__),
"teams", "%s.json" % team)
teams[team]["tasks"][task] = sorted(set(teams[team]["tasks"].get(task, []) + [lang]))
teams[team]["langs"][lang] = sorted(set(teams[team]["langs"].get(lang, []) + [task]))
try:
json.dump(teams[team], open(team_path, "w"), indent=4)
except IOError:
logger.error("Couldn't write data for team %s" % team)
raise HTTPError(500)
except ValueError:
logger.error("Couldn't dump data for team %s" % team)
raise HTTPError(500)
# Make some symlinks to easily access this version of the file
links = [os.path.join(os.path.dirname(__file__),
"data", task, "by_lang", "%s (%s).pdf" % (lang, team)),
os.path.join(os.path.dirname(__file__),
"data", task, "by_team", "%s (%s).pdf" % (team, lang))]
for link in links:
try:
os.makedirs(os.path.dirname(link))
except OSError:
pass # dir already exists
try:
os.remove(link)
except OSError:
pass # file doesn't exist yet
os.symlink(os.path.relpath(path, os.path.dirname(link)), link)
@authenticated
def delete(self, team, lang, task):
if team != self.current_user:
logger.warn("Team %s said to be %s while deleting translation of %s in %s." % (self.current_user, team, task, lang))
raise HTTPError(403)
if lang not in teams[team]["tasks"].get(task, []):
logger.warn("Team %s tried to delete a translation that doesn't exists (%s in %s)" % (team, task, lang))
raise HTTPError(404)
logger.info("Team %s deleted translation of task %s into %s" % (team, task, lang))
# Update the task and team data
task_path = os.path.join(os.path.dirname(__file__),
"tasks", "%s.json" % task)
tasks[task]["teams"][team].remove(lang)
tasks[task]["langs"][lang].remove(team)
try:
json.dump(tasks[task], open(task_path, "w"), indent=4)
except IOError:
logger.error("Couldn't write data for task %s" % task)
raise HTTPError(500)
except ValueError:
logger.error("Couldn't dump data for task %s" % task)
raise HTTPError(500)
team_path = os.path.join(os.path.dirname(__file__),
"teams", "%s.json" % team)
teams[team]["tasks"][task].remove(lang)
teams[team]["langs"][lang].remove(task)
try:
json.dump(teams[team], open(team_path, "w"), indent=4)
except IOError:
logger.error("Couldn't write data for team %s" % team)
raise HTTPError(500)
except ValueError:
logger.error("Couldn't dump data for team %s" % team)
raise HTTPError(500)
# Remove the symlinks
links = [os.path.join(os.path.dirname(__file__),
"data", task, "by_lang", "%s (%s).pdf" % (lang, team)),
os.path.join(os.path.dirname(__file__),
"data", task, "by_team", "%s (%s).pdf" % (team, lang))]
for link in links:
os.remove(link)
proxy.send("delete", "%s %s %s" % (team, lang, task), '*')
class SelectionHandler(BaseHandler):
@authenticated
def put(self, team, lang, task):
logger.info("Team %s selected %s %s %s" % (self.current_user, lang, task, team))
path = os.path.join(os.path.dirname(__file__),
"teams", "%s.json" % self.current_user)
if [team, lang, task] not in teams[self.current_user]["selected"]:
teams[self.current_user]["selected"].append([team, lang, task])
try:
json.dump(teams[self.current_user], open(path, "w"), indent=4)
except IOError:
logger.error("Couldn't write data for team %s" % team)
raise HTTPError(500)
except ValueError:
logger.error("Couldn't dump data for team %s" % team)
raise HTTPError(500)
proxy.send("select", "%s %s %s" % (team, lang, task), self.current_user)
@authenticated
def delete(self, team, lang, task):
logger.info("Team %s unselected %s %s %s" % (self.current_user, lang, task, team))
path = os.path.join(os.path.dirname(__file__),
"teams", "%s.json" % self.current_user)
if [team, lang, task] in teams[self.current_user]["selected"]:
teams[self.current_user]["selected"].remove([team, lang, task])
try:
json.dump(teams[self.current_user], open(path, "w"), indent=4)
except IOError:
logger.error("Couldn't write data for team %s" % team)
raise HTTPError(500)
except ValueError:
logger.error("Couldn't dump data for team %s" % team)
raise HTTPError(500)
proxy.send("unselect", "%s %s %s" % (team, lang, task), self.current_user)
class ImageHandler(RequestHandler):
formats = {
'png': 'image/png',
'jpg': 'image/jpeg',
'gif': 'image/gif',
'bmp': 'image/bmp'
}
def initialize(self, location, fallback):
self.location = location
self.fallback = fallback
def get(self, *args):
self.location %= tuple(args)
for ext, filetype in self.formats.iteritems():
if os.path.isfile(self.location + '.' + ext):
self.serve(self.location + '.' + ext, filetype)
return
self.serve(self.fallback, 'image/png') # FIXME hardcoded type
def serve(self, path, filetype):
self.set_header("Content-Type", filetype)
modified = datetime.utcfromtimestamp(int(os.path.getmtime(path)))
self.set_header('Last-Modified', modified)
# TODO check for If-Modified-Since and If-None-Match
with open(path, 'rb') as data:
self.write(data.read())
class ButtonHandler(RequestHandler):
def get(self, team, lang, task):
self.render("button.html",
team=team, lang=lang, task=task)
def main():
application = Application([
(r"/", MainHandler),
(r"/login", LoginHandler),
(r"/logout", LogoutHandler),
(r"/events", EventHandler),
(r"/translations/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)", TranslationHandler),
(r"/translations/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/button", ButtonHandler),
(r"/selections/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)", SelectionHandler),
(r"/flags/([A-Za-z0-9_]+)", ImageHandler, {
'location': os.path.join(os.path.dirname(__file__), 'flags', '%s'),
'fallback': os.path.join(os.path.dirname(__file__), 'static', 'flag.png')
}),
], **{
"login_url": "/",
"template_path": os.path.join(os.path.dirname(__file__), "templates"),
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"cookie_secret": base64.b64encode("000000000000000000000"),
})
application.listen(8891)
try:
IOLoop.instance().start()
except KeyboardInterrupt:
# Exit cleanly.
return
if __name__ == "__main__":
main()