forked from tsileo/microblog.pub
-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.py
218 lines (176 loc) · 5.88 KB
/
config.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
from datetime import datetime
from enum import Enum
import mimetypes
import os
import subprocess
from itsdangerous import JSONWebSignatureSerializer
from little_boxes import strtobool
from little_boxes.activitypub import DEFAULT_CTX
from pymongo import MongoClient
import pymongo
import requests
import sass
import yaml
from utils.key import KEY_DIR
from utils.key import get_key
from utils.key import get_secret_key
from utils.media import MediaCache
class ThemeStyle(Enum):
LIGHT = "light"
DARK = "dark"
DEFAULT_THEME_STYLE = ThemeStyle.LIGHT.value
DEFAULT_THEME_PRIMARY_COLOR = {
ThemeStyle.LIGHT: "#1d781d", # Green
ThemeStyle.DARK: "#33ff00", # Purple
}
def noop():
pass
CUSTOM_CACHE_HOOKS = False
try:
from cache_hooks import purge as custom_cache_purge_hook
except ModuleNotFoundError:
custom_cache_purge_hook = noop
try:
if os.path.isdir('.git'):
VERSION = (
subprocess.check_output(
["git", "describe", "--always"]
).split()[0].decode("utf-8")
)
elif os.path.isdir('.hg'):
VERSION = (
subprocess.check_output(
["hg", "id", "-i"]
).split()[0].decode("utf-8")
)
except:
VERSION = "-"
DEBUG_MODE = strtobool(os.getenv("MICROBLOGPUB_DEBUG", "false"))
HEADERS = [
"application/activity+json",
"application/ld+json;profile=https://www.w3.org/ns/activitystreams",
'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
"application/ld+json",
]
with open(os.path.join(KEY_DIR, "me.yml")) as f:
conf = yaml.load(f)
USERNAME = conf["username"]
NAME = conf["name"]
DOMAIN = conf["domain"]
SCHEME = "https" if conf.get("https", True) else "http"
BASE_URL = SCHEME + "://" + DOMAIN
ID = BASE_URL
SUMMARY = conf["summary"]
ICON_URL = conf["icon_url"]
PASS = conf["pass"]
EXTRA_INBOXES = conf.get("extra_inboxes", [])
HIDE_FOLLOWING = conf.get("hide_following", True)
# Theme-related config
theme_conf = conf.get("theme", {})
THEME_STYLE = ThemeStyle(theme_conf.get("style", DEFAULT_THEME_STYLE))
THEME_COLOR = theme_conf.get("color", DEFAULT_THEME_PRIMARY_COLOR[THEME_STYLE])
TIMEZONE = int(conf.get("timezone_hours", 0))
CDN_URL = conf.get("cdn_url", "")
YANDEX_TRANSLATE_API = conf.get("yandex_translate_api_key", "")
NO_TRANSLATE = conf.get("no_translate", [])
TARGET_LANG = conf.get("target_lang", "en")
SIMILARITY_THRESHOLD = conf.get("similarity_threshold", 94)
IMAGE_MAX_SIZE = (
conf.get("image_max_size", {}).get("width", 1920),
conf.get("image_max_size", {}).get("height", 1920)
)
SASS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sass")
theme_css = f"$primary-color: {THEME_COLOR};\n"
with open(os.path.join(SASS_DIR, f"{THEME_STYLE.value}.scss")) as f:
theme_css += f.read()
theme_css += "\n"
with open(os.path.join(SASS_DIR, "base_theme.scss")) as f:
raw_css = theme_css + f.read()
CSS = sass.compile(string=raw_css, output_style="compressed")
USER_AGENT = (
f"{requests.utils.default_user_agent()} (microblog.pub/{VERSION}; +{BASE_URL})"
)
def create_mongo_client():
return MongoClient(
host=[os.getenv("MICROBLOGPUB_MONGODB_HOST", "localhost:27017")],
connect=False,
)
def create_db_client(db_name):
return create_mongo_client()[db_name]
DB_NAME = "{}_{}".format(USERNAME, DOMAIN.replace(".", "_"))
DB = create_db_client(DB_NAME)
GRIDFS = create_db_client(f"{DB_NAME}_gridfs")
MEDIA_CACHE = MediaCache(GRIDFS, USER_AGENT)
def create_indexes():
DB.activities.create_index([("remote_id", pymongo.ASCENDING)])
DB.activities.create_index([("activity.object.id", pymongo.ASCENDING)])
DB.activities.create_index([
("activity.object.id", pymongo.ASCENDING),
("meta.deleted", pymongo.ASCENDING),
])
DB.cache2.create_index([("path", pymongo.ASCENDING), ("type", pymongo.ASCENDING), ("arg", pymongo.ASCENDING)])
DB.cache2.create_index("date", expireAfterSeconds=3600 * 12)
DB.translate.create_index([("hash", pymongo.ASCENDING), ("target_lang", pymongo.ASCENDING)])
# Index for the block query
DB.activities.create_index(
[
("box", pymongo.ASCENDING),
("type", pymongo.ASCENDING),
("meta.undo", pymongo.ASCENDING),
]
)
# Index for count queries
DB.activities.create_index(
[
("box", pymongo.ASCENDING),
("type", pymongo.ASCENDING),
("meta.undo", pymongo.ASCENDING),
("meta.deleted", pymongo.ASCENDING),
]
)
DB.activities.create_index(
[
("type", pymongo.ASCENDING),
("activity.object.type", pymongo.ASCENDING),
("activity.object.inReplyTo", pymongo.ASCENDING),
("meta.deleted", pymongo.ASCENDING),
]
)
def _drop_db():
if not DEBUG_MODE:
return
create_mongo_client().drop_database(DB_NAME)
KEY = get_key(ID, USERNAME, DOMAIN)
JWT_SECRET = get_secret_key("jwt")
JWT = JSONWebSignatureSerializer(JWT_SECRET)
def _admin_jwt_token() -> str:
return JWT.dumps(# type: ignore
{"me": "ADMIN", "ts": datetime.now().timestamp()}
).decode(# type: ignore
"utf-8"
)
ADMIN_API_KEY = get_secret_key("admin_api_key", _admin_jwt_token)
ME = {
"@context": DEFAULT_CTX,
"type": "Person",
"id": ID,
"following": ID + "/following",
"followers": ID + "/followers",
"featured": ID + "/featured",
"liked": ID + "/liked",
"inbox": ID + "/inbox",
"outbox": ID + "/outbox",
"preferredUsername": USERNAME,
"name": NAME,
"summary": SUMMARY,
"endpoints": {},
"url": ID,
"manuallyApprovesFollowers": False,
"attachment": [],
"icon": {
"mediaType": mimetypes.guess_type(ICON_URL)[0],
"type": "Image",
"url": ICON_URL,
},
"publicKey": KEY.to_dict(),
}