summaryrefslogtreecommitdiff
path: root/server/szurubooru/api/info_api.py
blob: 757b09cfe1de2a616e7e8ad59bfb2e4ea359688c (plain)
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
import os
from datetime import datetime, timedelta
from typing import Dict, Optional

from szurubooru import config, rest
from szurubooru.func import auth, posts, users, util

_cache_time = None  # type: Optional[datetime]
_cache_result = None  # type: Optional[int]


def _get_disk_usage() -> int:
    global _cache_time, _cache_result
    threshold = timedelta(hours=48)
    now = datetime.utcnow()
    if _cache_time and _cache_time > now - threshold:
        assert _cache_result is not None
        return _cache_result
    total_size = 0
    for dir_path, _, file_names in os.walk(config.config["data_dir"]):
        for file_name in file_names:
            file_path = os.path.join(dir_path, file_name)
            try:
                total_size += os.path.getsize(file_path)
            except FileNotFoundError:
                pass
    _cache_time = now
    _cache_result = total_size
    return total_size


@rest.routes.get("/info/?")
def get_info(ctx: rest.Context, _params: Dict[str, str] = {}) -> rest.Response:
    post_feature = posts.try_get_current_post_feature()
    ret = {
        "postCount": posts.get_post_count(),
        "diskUsage": _get_disk_usage(),
        "serverTime": datetime.utcnow(),
        "config": {
            "name": config.config["name"],
            "userNameRegex": config.config["user_name_regex"],
            "passwordRegex": config.config["password_regex"],
            "tagNameRegex": config.config["tag_name_regex"],
            "tagCategoryNameRegex": config.config["tag_category_name_regex"],
            "defaultUserRank": config.config["default_rank"],
            "enableSafety": config.config["enable_safety"],
            "contactEmail": config.config["contact_email"],
            "canSendMails": bool(config.config["smtp"]["host"]),
            "privileges": util.snake_case_to_lower_camel_case_keys(
                config.config["privileges"]
            ),
        },
    }
    if auth.has_privilege(ctx.user, "posts:view:featured"):
        ret["featuredPost"] = (
            posts.serialize_post(post_feature.post, ctx.user)
            if post_feature
            else None
        )
        ret["featuringUser"] = (
            users.serialize_user(post_feature.user, ctx.user)
            if post_feature
            else None
        )
        ret["featuringTime"] = post_feature.time if post_feature else None
    return ret