This repository has been archived by the owner on Mar 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetup.py
executable file
·297 lines (242 loc) · 8.09 KB
/
setup.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
#!/usr/bin/env python3
import os
import sys
import time
import json
from nxtools import *
from defaults import *
if os.path.exists("template"):
from template import *
try:
import psycopg2
except ImportError:
log_traceback("Import error")
critical_error("Unable to import psycopg2")
#
# Settings
#
# Use settings.json file
config = {}
try:
config.update(json.load(open("settings.json")))
except Exception:
pass
# Then environment variables (which have the highest priority) to override
for key, value in dict(os.environ).items():
if key.lower().startswith("nebula_"):
key = key.lower().replace("nebula_", "", 1)
config[key] = value
# Assert requiered settings are present
for key in ["site_name", "db_host", "db_user", "db_pass", "db_name"]:
if not config.get(key):
critical_error(f"{key} is not specified")
#
# Download classification schemes
#
def cs_download():
if not os.path.exists("cs"):
os.mkdir("cs")
try:
import requests
except ImportError:
logging.warning("python-requests library is not installed")
return
try:
csdata = json.loads(requests.get("https://cs.nbla.xyz/dump").text)
except:
log_traceback("Unable to load classification schemes")
return
for csdato in csdata:
with open("cs/{}.json".format(slugify(csdato["cs"])), "w") as f:
json.dump(csdato, f)
cs_download()
#
# Database connection
#
class DB(object):
def __init__(self, **kwargs):
self.pmap = {
"host": "db_host",
"user": "db_user",
"password": "db_pass",
"database": "db_name",
}
self.settings = {
key: kwargs.get(self.pmap[key], config[self.pmap[key]]) for key in self.pmap
}
self.conn = psycopg2.connect(**self.settings)
self.cur = self.conn.cursor()
def lastid(self):
self.query("SELECT LASTVAL()")
return self.fetchall()[0][0]
def query(self, query, *args):
self.cur.execute(query, *args)
def fetchone(self):
return self.cur.fetchone()
def fetchall(self):
return self.cur.fetchall()
def commit(self):
self.conn.commit()
def rollback(self):
self.conn.rollback()
def close(self):
self.conn.close()
def __len__(self):
return True
#
# Template installers
#
def install_settings():
logging.info("Installing site settings")
db = DB()
db.query("DELETE FROM settings")
for key in data["settings"]:
value = json.dumps(data["settings"][key])
db.query("INSERT INTO settings (key, value) VALUES (%s, %s)", [key, value])
db.commit()
def install_storages():
logging.info("Installing storages")
db = DB()
db.query("DELETE FROM storages")
for key in data["storages"]:
value = json.dumps(data["storages"][key])
db.query("INSERT INTO storages (id, settings) VALUES (%s, %s)", [key, value])
db.commit()
db.query("SELECT setval(pg_get_serial_sequence('storages', 'id'), coalesce(max(id),0) + 1, false) FROM storages;")
db.commit()
def install_channels():
logging.info("Installing channels")
db = DB()
db.query("DELETE FROM channels")
for id in data["channels"]:
channel_type, settings = data["channels"][id]
db.query(
"INSERT INTO channels (id, channel_type, settings) VALUES (%s, %s, %s)",
[id, channel_type, json.dumps(settings)]
)
db.query("SELECT setval(pg_get_serial_sequence('channels', 'id'), coalesce(max(id),0) + 1, false) FROM channels;")
db.commit()
def install_services():
logging.info("Installing services")
db = DB()
db.query("DELETE FROM services")
for id in data["services"]:
stype, host, title, settings, autostart, loop_delay = data["services"][id]
if not settings:
settings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<service/>"
else:
settings = open(settings).read()
db.query(
"INSERT INTO services (id, service_type, host, title, settings, autostart, loop_delay) VALUES (%s, %s, %s, %s, %s, %s, %s)",
[id, stype, host, title, settings, autostart, loop_delay])
db.commit()
db.query("SELECT setval(pg_get_serial_sequence('services', 'id'), coalesce(max(id),0) + 1, false) FROM services;")
db.commit()
def install_actions():
logging.info("Installing actions")
db = DB()
db.query("DELETE FROM actions")
for id in data["actions"]:
title, service_type, settings_path = data["actions"][id]
settings = open(settings_path).read()
db.query(
"INSERT INTO actions (id, service_type, title, settings) VALUES (%s, %s, %s, %s)",
[id, service_type, title, settings]
)
db.query("SELECT setval(pg_get_serial_sequence('actions', 'id'), coalesce(max(id),0) + 1, false) FROM actions;")
db.commit()
def install_folders():
logging.info("Installing asset folders")
db = DB()
db.query("DELETE FROM folders")
for id in data["folders"]:
settings = data["folders"][id]
db.query(
"INSERT INTO folders (id, settings) VALUES (%s, %s)",
[id, json.dumps(settings)]
)
db.query("SELECT setval(pg_get_serial_sequence('folders', 'id'), coalesce(max(id),0) + 1, false) FROM folders;")
db.commit()
def install_meta_types():
logging.info("Installing metadata set")
db = DB()
languages = ["en", "cs"]
aliases = {}
for lang in languages:
aliases[lang] = {}
trans_table_fname = os.path.join("aliases", "meta-aliases-{}.json".format(lang))
l = json.load(open(trans_table_fname))
for key, alias, header, description in l:
if header is None:
header = alias
aliases[lang][key] = [alias, header, description]
db.query("DELETE FROM meta_types")
for key in data["meta_types"]:
ns, e, index, ft, cls, settings = data["meta_types"][key]
meta_type_data = {
"ns": ns,
"class": cls,
"fulltext": ft,
"editable": e,
"aliases": {}
}
if settings:
meta_type_data.update(settings)
for lang in languages:
meta_type_data["aliases"][lang] = aliases[lang][key]
db.query(
"INSERT INTO meta_types (key, settings) VALUES (%s, %s)",
[key, json.dumps(meta_type_data)]
)
if index:
idx_name = "idx_" + key.replace("/", "_")
db.query(
"CREATE INDEX IF NOT EXISTS {} ON assets((meta->>%s))".format(idx_name),
[key]
)
db.commit()
def install_cs():
logging.info("Installing classification schemes")
db = DB()
for csfile in get_files("cs"):
try:
data = json.load(csfile.open())
except:
log_traceback("Unable to load classification schema {}".format(csfile))
continue
name = data["cs"]
db.query("DELETE FROM cs WHERE cs=%s", [name])
db.commit()
for value in data["data"]:
settings = data["data"][value]
db.query("INSERT INTO cs (cs, value, settings) VALUES (%s, %s, %s)", [
name, value, json.dumps(settings)])
db.commit()
def install_views():
logging.info("Installing asset views")
db = DB()
db.query("DELETE FROM views")
for id in data["views"]:
settings = data["views"][id]
db.query(
"INSERT INTO views (id, settings) VALUES (%s, %s)",
[id, json.dumps(settings)]
)
db.query("SELECT setval(pg_get_serial_sequence('views', 'id'), coalesce(max(id),0) + 1, false) FROM views;")
db.commit()
#
# Run
#
if __name__ == "__main__":
start_time = time.time()
install_settings()
install_storages()
install_channels()
install_services()
install_actions()
install_folders()
install_meta_types()
install_cs()
install_views()
logging.goodnews("Nebula settings migration completed in {:03f} seconds".format(
time.time() - start_time))