-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.py
417 lines (336 loc) · 13.5 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
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
import bibtexparser
from bibtexparser.bparser import BibTexParser
from flask import Flask, jsonify, request
import Levenshtein
import git
import json
import sys
import importlib
VERSION = 15
app = Flask(__name__)
tokens = True
no_commit = False
token_db = {
"test": {"search": True, "read": True, "write": True, "delete": True}
}
def check_token(token, operation):
if not tokens:
return (True, None)
if len(token_db) == 0:
return (False, {"success": False, "reason": "server_problem", "message": "The token database on the server seems to be corrupted, please inform your BibTool administrator."})
if not token in token_db:
return (False, {"success": False, "reason": "access_denied", "message": "Invalid token. Check your 'token' file."})
if not operation in token_db[token]:
return (False, {"success": False, "reason": "access_denied", "message": "Your token does not grant %s access." % operation})
ok = token_db[token][operation]
if not ok:
return (False, {"success": False, "reason": "access_denied", "message": "Your token does not grant %s access." % operation})
else:
return (True, None)
def entry_to_bibtex(entry):
newdb = bibtexparser.bibdatabase.BibDatabase()
newdb.entries = [ entry ]
return bibtexparser.dumps(newdb)
def get_duplicates(entry):
dups = []
for e in bib_database.entries:
dist = 0
fields = set(e.keys())
fields.update(entry.keys())
length = 0
exact = e["ID"] == entry["ID"]
for field in fields:
if field in e and field in entry:
dist += Levenshtein.distance(e[field], entry[field])
length += max(len(e[field]), len(entry[field]))
if (exact and sorted(e.keys()) != sorted(entry.keys())) or ((dist < max(5, length * 0.1) or exact) and dist > 0):
dups.append((dist, entry["ID"], e))
return dups
def entry_by_key(key):
for entry in bib_database.entries:
if entry["ID"] == key:
return entry
return None
def save_bib(commit_message = None, token = None):
with open(repo_path + "/" + repo_name, "w") as bibtex_file:
bibtexparser.dump(bib_database, bibtex_file)
if repo and not no_commit:
msg = commit_message if commit_message else "update"
if tokens:
msg += " (Token %s)" % (token if token else "none")
msg = "[BibTool] %s" % msg
repo.index.add(repo_path + "/" + repo_name)
repo.index.commit(msg)
try:
repo.remotes.origin.push()
except:
print("Warning: could not push to repository")
def entry_is_same(e1, e2):
if set(e1.keys()) != set(e2.keys()):
return False
for f in e1.keys():
if e1[f] != e2[f]:
return False
return True
@app.route("/")
def index():
return "BibTool v1<br/>\n<a href=\"v1/client.py\">Download client</a><br/>\n<a href=\"v1/requirements.txt\">Download requirements.txt</a>"
@app.route("/v1/client.py")
def get_client():
return open("client.py").read()
@app.route("/v1/requirements.txt")
def get_reqtxt():
return open("requirements.txt").read()
@app.route("/v1/entry/<string:key>", defaults={"token": None}, methods=["GET"])
@app.route("/v1/entry/<string:key>/<string:token>", methods=["GET"])
def get_entry(key, token):
ok, reason = check_token(token, "read")
if not ok:
return jsonify(reason)
return jsonify({"success": True, "entry": entry_by_key(key)})
@app.route("/v1/bibentry/<string:key>", defaults={"token": None}, methods=["GET"])
@app.route("/v1/bibentry/<string:key>/<string:token>", methods=["GET"])
def get_bibentry(key, token):
ok, reason = check_token(token, "read")
if not ok:
return reason["message"]
return entry_to_bibtex(entry_by_key(key))
@app.route("/v1/get", methods=["POST"])
def get_bibfile():
if not request.json or not "entries" in request.json or not "token" in request.json:
return "Invalid request"
ok, reason = check_token(request.json["token"], "read")
if not ok:
return reason["message"]
bib = ""
for entry in request.json["entries"]:
bib += entry_to_bibtex(entry_by_key(entry)) + "\n"
return bib
@app.route("/v1/get_json", methods=["POST"])
def get_bibfile_as_json():
if not request.json or not "entries" in request.json or not "token" in request.json:
return jsonify({"success": False, "reason": "invalid_request", "message": "Invalid request"})
ok, reason = check_token(request.json["token"], "read")
if not ok:
return jsonify(reason)
bib = []
for entry in request.json["entries"]:
bib.append(entry_by_key(entry))
return jsonify(bib)
@app.route("/v1/suggest/<string:key>", defaults={"token": None}, methods=["GET"])
@app.route("/v1/suggest/<string:key>/<string:token>", methods=["GET"])
def suggest_entry(key, token):
ok, reason = check_token(token, "search")
if not ok:
return jsonify(reason)
entry = entry_by_key(key)
if not entry:
entries = []
for entry in bib_database.entries:
dist = Levenshtein.distance(entry["ID"].lower(), key.lower())
if key.lower() in entry["ID"].lower() or dist == 0:
entries.append((1, entry))
continue
if dist < 5:
entries.append((1-dist/100.0, entry))
continue
common_prefix = 0
for i in range(min(len(entry["ID"]), len(key))):
if entry["ID"].lower()[i] != key.lower()[i]:
break
common_prefix += 1
if common_prefix >= 6:
entries.append((common_prefix/float(max(len(entry["ID"]), len(key))), entry))
else:
entries = [ (1, entry) ]
top = sorted(entries, key=lambda x: x[0], reverse=True)
return jsonify({"success": True, "entries": top[:5]})
@app.route("/v1/search/<string:query>", defaults={"token": None}, methods=["GET"])
@app.route("/v1/search/<string:query>/<string:token>", methods=["GET"])
def search_entry(query, token):
ok, reason = check_token(token, "search")
if not ok:
return reason["message"]
query_parts = query.split(" ")
for q in query_parts:
if len(q) < 3:
return "Each query must be at least 3 characters!"
entries = []
for entry in bib_database.entries:
found_part = [False for q in query_parts]
for field in entry:
for (idx, q) in enumerate(query_parts):
if field.lower() != "entrytype" and q.lower() in entry[field].lower():
found_part[idx] = True
was_found = True
for q in found_part:
was_found &= q
if was_found:
entries.append((entry_to_bibtex(entry)))
return "\n".join(list(set(entries)))
@app.route("/v1/entry/<string:key>", methods=["POST"])
def add_entry(key):
if not request.json or not "entry" in request.json or not "token" in request.json:
return jsonify({"success": False, "reason": "missing_entry"})
ok, reason = check_token(request.json["token"], "write")
if not ok:
return jsonify(reason)
# check if the client is forcing the server policy
if "force" in request.json:
ok, reason = check_token(request.json["token"], "force")
if not ok:
return jsonify(reason)
if "ID" not in request.json["entry"]:
request.json["entry"]["ID"] = key
existing = entry_by_key(request.json["entry"]["ID"])
if existing:
return jsonify({"success": False, "reason": "exists", "entry": existing})
if policy and "force" not in request.json:
accept, reason = policy.check(request.json["entry"], bib_database.entries)
if not accept:
entry = request.json["entry"]
entry["reason"] = reason
return jsonify({"success": False, "reason": "policy", "entries": [entry]})
bib_database.entries.append(request.json["entry"])
save_bib("Added %s" % request.json["entry"]["ID"], request.json["token"])
return jsonify({"success": True})
@app.route("/v1/entry/<string:key>", methods=["PUT"])
def replace_entry(key):
if not request.json or not "entry" in request.json or not "token" in request.json:
return jsonify({"success": False, "reason": "missing_entry"})
ok, reason = check_token(request.json["token"], "write")
if not ok:
return jsonify(reason)
if policy and "force" not in request.json:
accept, reason = policy.check(request.json["entry"], bib_database.entries)
if not accept:
entry = request.json["entry"]
entry["reason"] = reason
return jsonify({"success": False, "reason": "policy", "entries": [entry]})
for (idx, entry) in enumerate(bib_database.entries):
if entry["ID"] == key:
bib_database.entries[idx] = request.json["entry"]
save_bib("Changed %s" % key, request.json["token"])
return jsonify({"success": True})
return jsonify({"success": False, "reason": "not_found"})
@app.route("/v1/entry/<string:key>", defaults={"token": None}, methods=["DELETE"])
@app.route("/v1/entry/<string:key>/<string:token>", methods=["DELETE"])
def remove_entry(key, token):
ok, reason = check_token(token, "delete")
if not ok:
return jsonify(reason)
for (idx, entry) in enumerate(bib_database.entries):
if entry["ID"] == key:
del bib_database.entries[idx]
save_bib("Deleted %s" % key, token)
return jsonify({"success": True})
return jsonify({"success": False, "reason": "not_found"})
@app.route("/v1/update", methods=["POST"])
def add_entries():
if not request.json or not "entries" in request.json or not "token" in request.json:
return jsonify({"success": False, "reason": "missing_entry"})
ok, reason = check_token(request.json["token"], "write")
if not ok:
return jsonify(reason)
# check if the client is forcing the server policy
if "force" in request.json:
ok, reason = check_token(request.json["token"], "force")
if not ok:
return jsonify(reason)
dups = []
changes = False
changelog = []
rejects = []
for entry in request.json["entries"]:
existing = entry_by_key(entry["ID"])
if existing and entry_is_same(existing, entry):
continue
dup = get_duplicates(entry)
if len(dup) == 0:
# new entry, add
if not entry_by_key(entry["ID"]):
if policy and "force" not in request.json:
accept, reason = policy.check(entry, bib_database.entries)
if not accept:
entry["reason"] = reason
rejects.append(entry)
print("Rejecting entry %s" % entry["ID"])
continue
bib_database.entries.append(entry)
changelog.append("Added %s" % entry["ID"])
changes = True
else:
dups += dup
if changes:
save_bib("\n".join(changelog), request.json["token"])
if len(rejects) > 0:
return jsonify({"success": False, "reason": "policy", "entries": rejects})
if len(dups) > 0:
return jsonify({"success": False, "reason": "duplicate", "entries": dups})
return jsonify({"success": True})
@app.route("/v1/sync", methods=["GET"])
def sync():
global repo, bib_database, token_db, tokens
parser = BibTexParser(common_strings=True)
parser.ignore_nonstandard_types = False
parser.homogenize_fields = True
repo = git.Repo(repo_path)
try:
origin = repo.remotes.origin
origin.pull()
except:
print("Warning: could not pull from repository")
with open(repo_path + "/" + repo_name) as bibtex_file:
bib_database = bibtexparser.load(bibtex_file, parser)
# uncomment for debug purposes
#for e in bib_database.entries:
#if policy:
#accept, reason = policy.check(e, bib_database.entries)
#if not accept:
#print("Reject %s: %s" % (e["ID"], reason))
try:
tdb = open(repo_path + "/tokens.json")
token_db = json.load(tdb)
except IOError:
print("No tokens.json, disable token checks")
tokens = False
except:
print("Error: error in the tokens.json, could not load it!")
token_db = {}
return "Synced!"
@app.route("/v1/webhook", methods=["POST"])
def webhook():
if not request.json or not "commits" in request.json:
return jsonify({"success": False, "reason": "missing_entry"})
was_internal = True
for commit in request.json["commits"]:
if "title" in commit and "[BibTool]" not in commit["title"]:
was_internal = False
break
if "message" in commit and "[BibTool]" not in commit["message"]:
was_internal = False
break
if not was_internal:
return sync()
else:
return "OK"
@app.route("/v1/version", methods=["GET"])
def version():
return jsonify({"version": VERSION, "url": "client.py"})
if __name__ == "__main__":
global repo_path, repo_name, policy
if len(sys.argv) < 3:
print("Usage: %s <repo path> <bib filename> [<policy>]" % sys.argv[0])
sys.exit(1)
repo_path = sys.argv[1]
repo_name = sys.argv[2]
if len(sys.argv) > 3:
try:
print("Import policy %s" % sys.argv[3])
policy = importlib.import_module(sys.argv[3])
except:
policy = None
else:
policy = None
sync()
app.run(debug=False, host='0.0.0.0')