|
11 | 11 |
|
12 | 12 | import os
|
13 | 13 | import re
|
| 14 | +import os |
| 15 | +from hashlib import sha256 |
| 16 | +import json |
| 17 | +from datetime import datetime |
14 | 18 | from collections import namedtuple
|
15 |
| -from otterwiki.server import app, mail, storage, Preferences |
| 19 | +from otterwiki.server import app, mail, storage, Preferences, db, app_renderer |
16 | 20 | from otterwiki.gitstorage import StorageError
|
17 | 21 | from flask import flash, url_for, session
|
18 | 22 | from threading import Thread
|
19 | 23 | from flask_mail import Message
|
20 | 24 | from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
|
21 | 25 | from otterwiki.util import split_path, join_path, clean_slashes, titleSs
|
22 | 26 | from otterwiki.renderer import OtterwikiRenderer
|
| 27 | +from otterwiki.models import Cache |
23 | 28 |
|
24 | 29 |
|
25 | 30 | class SerializeError(ValueError):
|
@@ -283,3 +288,53 @@ def patchset2urlmap(patchset, rev_b, rev_a=None):
|
283 | 288 | }
|
284 | 289 | url_map[file.path] = namedtuple('UrlData', d.keys())(*d.values())
|
285 | 290 | return url_map
|
| 291 | + |
| 292 | + |
| 293 | +def sha256sum(s: str) -> str: |
| 294 | + hash = sha256() |
| 295 | + hash.update(s.encode()) |
| 296 | + return hash.hexdigest() |
| 297 | + |
| 298 | + |
| 299 | +def update_ftoc_cache(filename, ftoc, mtime=None): |
| 300 | + if mtime is None: |
| 301 | + mtime = storage.mtime(filename) |
| 302 | + hash = sha256sum(f"ftoc://{filename}") |
| 303 | + value = json.dumps({"filename": filename, "ftoc": ftoc}) |
| 304 | + # check if key exists in Cache |
| 305 | + c = Cache.query.filter(Cache.key == hash).first() |
| 306 | + if c is None: |
| 307 | + c = Cache() |
| 308 | + c.key = hash |
| 309 | + c.value = value |
| 310 | + c.datetime = mtime |
| 311 | + # and update in the database |
| 312 | + db.session.add(c) |
| 313 | + db.session.commit() |
| 314 | + |
| 315 | + |
| 316 | +def get_ftoc(filename, mtime=None): |
| 317 | + if mtime is None: |
| 318 | + mtime = storage.mtime(filename) |
| 319 | + hash = sha256sum(f"ftoc://{filename}") |
| 320 | + # check if hash is in the Cache |
| 321 | + result = Cache.query.filter( |
| 322 | + db.and_(Cache.key == hash, Cache.datetime >= mtime) |
| 323 | + ).first() |
| 324 | + if result is not None: |
| 325 | + try: |
| 326 | + value = json.loads(result.value) |
| 327 | + try: |
| 328 | + # check |
| 329 | + if filename == value["filename"]: |
| 330 | + return value["ftoc"] |
| 331 | + except KeyError: |
| 332 | + pass |
| 333 | + except: |
| 334 | + pass |
| 335 | + content = storage.load(filename) |
| 336 | + # parse file contents |
| 337 | + _, ftoc = app_renderer.markdown(content) |
| 338 | + update_ftoc_cache(filename, ftoc, mtime) |
| 339 | + |
| 340 | + return ftoc |
0 commit comments