-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
283 lines (255 loc) · 8.12 KB
/
index.js
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
import { readFile, writeFile } from "fs/promises";
import { Wallet } from "ethers";
import { Bee, Utils } from "@ethersphere/bee-js";
import schedule from "node-schedule";
import {
DEFUAULT_BEE_API_URL,
DUMMY_STAMP,
FEEDTYPE_SEQUENCE,
FEED_OWNER_ADDRESS,
FEED_TOPIC,
DAYS_KEY_ARRAY,
DEVCON_7_DAYS_MAP,
VERSION_API_URL,
SESSIONS_API_URL,
ASSETS_PATH,
} from "./constants.js";
const bee = new Bee(process.env.BEE_API_URL || DEFUAULT_BEE_API_URL);
const feedOwnerAddress = process.env.FEED_OWNER_ADDRESS || FEED_OWNER_ADDRESS;
const feedTopic = process.env.FEED_TOPIC || FEED_TOPIC;
const mainnet_stamp = process.env.STAMP || DUMMY_STAMP;
const mainnet_pk = process.env.MAINNET_PK || null;
async function initFeed(rawTopic, stamp) {
try {
const topic = bee.makeFeedTopic(rawTopic);
const feedManif = await bee.createFeedManifest(
stamp,
FEEDTYPE_SEQUENCE,
topic,
feedOwnerAddress
);
console.log("created feed manifest", feedManif.reference);
if (!mainnet_pk) {
console.log("mainnet_pk is missing");
return null;
}
const wallet = new Wallet(mainnet_pk);
const signer = {
address: Utils.hexToBytes(wallet.address.slice(2)),
sign: async (data) => {
return await wallet.signMessage(data);
},
};
return bee.makeFeedWriter(FEEDTYPE_SEQUENCE, topic, signer);
} catch (error) {
console.log("error creating feed manifest", error);
return null;
}
}
async function uploadSessionsJSON(stamp, data) {
try {
console.log("uploading sessions json");
const sessionsReference = await bee.uploadData(stamp, data);
console.log("success, file reference: ", sessionsReference.reference);
return sessionsReference.reference;
} catch (error) {
console.log("error file upload", error);
return null;
}
}
async function updateFeed(feedWriter, stamp, ref) {
console.log("updating feed with the file reference: ", ref);
try {
const feedUpdateRes = await feedWriter.upload(stamp, ref);
console.log("feed upload result: ", feedUpdateRes.reference);
return feedUpdateRes.reference;
} catch (error) {
console.log("error feed update: ", error);
return null;
}
}
async function transformDataMaptoJSON(path, filename) {
let sessionsFile;
try {
console.log("reading " + filename);
sessionsFile = await readFile(path + filename);
} catch (e) {
console.log("error reading " + path + filename + " file", e);
return null;
}
const sortedSessionsMap = new Map();
for (let i = 0; i < DAYS_KEY_ARRAY.length; i++) {
sortedSessionsMap.set(DAYS_KEY_ARRAY[i], new Array());
}
const items = JSON.parse(sessionsFile).data.items;
const itemsWithoutAvatars = removeSpeakers(items);
for (let i = 0; i < itemsWithoutAvatars.length; i++) {
const slotStart = itemsWithoutAvatars[i].slot_start;
if (slotStart) {
const day = new Date(slotStart).toDateString();
let dayIndex = -1;
switch (day) {
case DEVCON_7_DAYS_MAP.get("Day 1"):
dayIndex = 0;
break;
case DEVCON_7_DAYS_MAP.get("Day 2"):
dayIndex = 1;
break;
case DEVCON_7_DAYS_MAP.get("Day 3"):
dayIndex = 2;
break;
case DEVCON_7_DAYS_MAP.get("Day 4"):
dayIndex = 3;
break;
default:
console.log("unkown day: ", day);
break;
}
if (dayIndex !== -1) {
sortedSessionsMap
.get(DAYS_KEY_ARRAY[dayIndex])
.push(itemsWithoutAvatars[i]);
}
}
}
sortedSessionsMap.forEach((value, key) => {
console.log(key, " length: ", value.length);
if (value.length == 0) {
console.log("empty day: ", key);
return null;
}
});
return sortedSessionsMap;
}
async function uploadFeedAndData(path, filename) {
let sessionsFile;
try {
console.log("reading " + filename);
sessionsFile = await readFile(path + filename);
} catch (e) {
console.log("error reading " + filename + " file", e);
return null;
}
const feedWriter = await initFeed(feedTopic, mainnet_stamp);
if (feedWriter === null) {
console.log("feedwriter is null");
return null;
}
const sessionsReference = await uploadSessionsJSON(
mainnet_stamp,
sessionsFile
);
if (!sessionsReference || sessionsReference.length === 0) {
console.log("canot update feed because of invalid reference");
return null;
}
return await updateFeed(feedWriter, mainnet_stamp, sessionsReference);
}
function removeSpeakers(sessionItems) {
const newSessionItems = sessionItems;
for (let i = 0; i < newSessionItems.length; i++) {
const item = newSessionItems[i];
if (item.speakers) {
item.speakers = [];
}
}
return newSessionItems;
}
async function fetchDevconAPI(path, filename) {
let currentVersion = "";
try {
console.log("reading " + filename);
const versionFile = await readFile(path + filename);
currentVersion = JSON.parse(versionFile).data;
} catch (e) {
console.log("error reading version file " + filename, e);
return;
}
try {
console.log("fetching API for version: ", VERSION_API_URL);
const r = await fetch(VERSION_API_URL);
const versionJSON = await r.json();
// check if the version changed
const newVersion = versionJSON.data;
if (versionJSON.status === 200 && newVersion !== currentVersion) {
console.log(`version changed from ${currentVersion} to ${newVersion}`);
console.log("fetching API for sessions: ", SESSIONS_API_URL);
const resp = await fetch(SESSIONS_API_URL);
const sessionsJSON = await resp.json();
const newSessionsFile =
"all_devcon_7_sessions_asc_" + newVersion + ".json";
// udpate the sessions file
try {
await writeFile(
ASSETS_PATH + newSessionsFile,
JSON.stringify(sessionsJSON, null, 2)
);
console.log("new sessions written to file: ", newSessionsFile);
} catch (e) {
console.log("error writing sessions file", e);
return;
}
// udpate the version file only if the fetch was successful
try {
await writeFile(path + filename, JSON.stringify(versionJSON, null, 2));
console.log("new version written to file: ", path + filename);
} catch (e) {
console.log("error writing version file", e);
return;
}
const sortedSessionsMap = await transformDataMaptoJSON(
ASSETS_PATH,
newSessionsFile
);
if (sortedSessionsMap === null) {
console.log("error transforming the data map to json");
return;
}
const outputFile =
"all_devcon_7_sessions_sorted_by_day_asc_" + newVersion + ".json";
try {
await writeFile(
path + outputFile,
JSON.stringify(Object.fromEntries(sortedSessionsMap), null, 2)
);
console.log("sortedSessionsMap written to file: ", outputFile);
} catch (e) {
console.log("error writing sortedSessionsMap file", e);
return null;
}
const res = uploadFeedAndData(ASSETS_PATH, outputFile);
if (res === null) {
console.log("session data update fail, still using the old data");
}
} else {
console.log("version did not change, current version: ", currentVersion);
}
} catch (e) {
console.log("unexpected error during data fetch and update: ", e);
}
return;
}
async function scheduleSessionUpdateJob() {
const jobName = "fetchDevconAPI";
const updadtePeriod = 15;
const cronSchedule = "* */" + updadtePeriod + " * * * *";
schedule.scheduleJob(jobName, cronSchedule, async () => {
console.log(
"Scheduler job started at: " +
new Date().toLocaleString() +
" with period: " +
updadtePeriod +
" minutes (" +
cronSchedule +
")"
);
await fetchDevconAPI(ASSETS_PATH, "version.json");
console.log("Scheduler job ended at:", new Date().toLocaleString());
});
}
async function main() {
console.log("Fetch and update started at:", new Date().toLocaleString());
scheduleSessionUpdateJob();
}
// main();
uploadFeedAndData(ASSETS_PATH, "all_devcon_7_sessions_sorted_by_day_asc_1731761435222.json")