-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
391 lines (263 loc) · 8.94 KB
/
server.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
const express = require('express')
const moment = require('moment')
const path = require('path')
const fs = require('fs')
const extract = require('extract-zip')
const app = express()
const appArgs = process.argv.slice(2)
const DAYLIO_BACKUP = appArgs[0]
let DAYLIO_DATA
/*
======= E N T R Y D A T A ( ID Ordered Entries ) ======
*
* => Used by pug to render the entry elements ( static )
* => Responsible for their ids, groups and non-human-readable data
*/
function getEntryData(rawData) {
/* Render data format:
[ <----- The array that holds all the entries ( newest first )
index: { <---- Entry object
id:..,
mood: ...,
date: ...,
...
}
...
]
*/
var entry_data = []
const daysOfWeek = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]
for (const daily_entry in rawData.dayEntries) {
const current_entry = rawData.dayEntries[daily_entry]
const time_obj = moment.unix((current_entry.datetime + current_entry.timeZoneOffset ) / 1000).utc()
const date_formatted = time_obj.format('Do MMM YYYY')
const time_formatted = time_obj.format('hh:mm A')
const day = daysOfWeek[time_obj.day()]
// Rich text editor exports notes with markdown template by default, but the mini editor doesn't
const note_formatted = (current_entry.note).replaceAll(`\n`,'<br>')
entry_data[daily_entry] = {
id: current_entry.id,
time: time_formatted,
date: `${current_entry.day}-${current_entry.month}-${current_entry.year}`,
date_formatted: date_formatted,
day: day,
journal: [current_entry.note_title, note_formatted],
mood: current_entry.mood,
activities: current_entry.tags
}
}
return entry_data
}
/*
======= R E A D A B L E D A T A ======
*
* => Used by pug to get the human readable data
* => Responsible for showing activity names, groups, and mood names
*
*/
function getReadableData(rawData) {
/* Readable data format:
{
activities: { <---- Object that holds all the activities
activity_id: { <--- Activity Object
name: ...
id: ...
group: ...
}
}
moods: { ... }
...
}
*/
// Iteration is necessary since the exported entries come in 'array/s' rather than 'object/s'.
// Conversion of UNORDERED ARRAY into an ID OBJECT
var activities = {}
var activity_groups = {}
for (const i in rawData.tags) {
activities[rawData.tags[i].id] = {}
activities[rawData.tags[i].id].name = rawData.tags[i].name
activities[rawData.tags[i].id].group = rawData.tags[i].id_tag_group
activities[rawData.tags[i].id].icon = rawData.tags[i].icon
}
for (const i in rawData.tag_groups) {
activity_groups[rawData.tag_groups[i].id] = rawData.tag_groups[i].name
}
var moods = {}
var mood_groups = {}
var ordered_mood_list = []
for (const i in rawData.customMoods) {
moods[rawData.customMoods[i].id] = rawData.customMoods[i].custom_name
mood_groups[rawData.customMoods[i].id] = rawData.customMoods[i].mood_group_id
ordered_mood_list[i] = rawData.customMoods[i].custom_name
}
let vital_data = {
available_activities: activities,
available_activity_groups: activity_groups,
available_moods: moods,
available_mood_groups: mood_groups,
ordered_mood_list: ordered_mood_list,
months: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
}
return vital_data
}
/*
======= S T R U C T U R E D D A T A ======
*
* => Only used by the frontend js
* => Responsible for showing ordered date info ( entry )
*
*/
function getStructuredEntries() {
/* Structured data format:
year: {
month: {
day: mood
...
}
month: {
...
}
...
}
year: {...}
*/
var structuredData = {}
let ENTRY_DATA = getEntryData(DAYLIO_DATA)
let VITAL_DATA = getReadableData(DAYLIO_DATA)
// Iterating through unstructured data ( Array-like )
for (entry in ENTRY_DATA) {
// Parsing date ( there are better ways, but this hack would work )
entryYear = (ENTRY_DATA[entry].date).split('-')[2]
entryMonth = (ENTRY_DATA[entry].date).split('-')[1]
entryDay = (ENTRY_DATA[entry].date).split('-')[0]
entryMood = VITAL_DATA.available_mood_groups[ ENTRY_DATA[entry].mood ]
/*
* NOTE: Daylio uses a 5 point based mood group ( regardless of its child moods )
*
* => Moods in the same group have the same mood score ( 1 - 5 )
* => Awful being 5 and Happy being 1
*
* NOTE: To make more sense, the highest mood ( Awful ) should be the bottom and the lowest ( Happy ) should be the top
*
* => So, swapping the scores with a reversed array ( 1 -> 5, 5 -> 1 ... )
*/
reverseMoodData = [ 5, 4, 3, 2, 1 ]
entryMood = reverseMoodData[ entryMood - 1 ]
/*
* NOTE:
*
* => 1 If year doesn't exist in the data, create a new object
* => 2 If month doesn't exist in the year, create a new object
*
* => 3 If day doesn't exist in the month, set the value. If it does, average their value ( works for multiple entries )
*/
// 1
if (!structuredData[entryYear])
structuredData[ entryYear ] = {}
// 2
if (!structuredData[entryYear][entryMonth])
structuredData[ entryYear][ entryMonth] = {}
// 3
if (structuredData[entryYear][entryMonth][entryDay]) {
structuredData[ entryYear ][ entryMonth ][ entryDay ] += entryMood
structuredData[ entryYear ][ entryMonth ][ entryDay ] /= 2
} else {
structuredData[ entryYear ][ entryMonth ][ entryDay ] = entryMood
}
}
return structuredData
}
// ======= M E T A D A T A ======
function getMetadata(rawData) {
metadata = {
longestDaysInRow: rawData.daysInRowLongestChain,
numberOfEntries: rawData.metadata.number_of_entries
}
return metadata
}
async function extractDaylioBackup() {
try {
await extract(__dirname + '/' + DAYLIO_BACKUP, { dir: __dirname + '/data/' })
} catch (err) {
console.log(err)
}
}
// Only copies the icons that have been used in the tags
function prepareIcons() {
// If needed, change these values
const PUBLIC_ICONS = '/public/assets/activity_icons'
const LOCAL_ICONS = '/activity_icons'
availableActivities = getReadableData(DAYLIO_DATA).available_activities
console.log(`info: loading ${Object.keys(availableActivities).length} icons`)
if (fs.existsSync(__dirname + PUBLIC_ICONS)) {
fs.rmSync(__dirname + PUBLIC_ICONS, { recursive: true, force: true })
}
fs.mkdirSync(__dirname + PUBLIC_ICONS)
for (const i in availableActivities) {
let iconId = availableActivities[i].icon
if (fs.existsSync(__dirname + `${LOCAL_ICONS}/ic_${iconId}.png`)) {
fs.copyFileSync(__dirname + `${LOCAL_ICONS}/ic_${iconId}.png`, __dirname + `${PUBLIC_ICONS}/ic_${iconId}.png` )
} else {
console.log(`error: no icon found - ${iconId}`)
}
}
}
function prepareServer() {
console.log('info: decoding data')
// Decodes and loads the base64-encoded data
// NOTE: Having this file decoded PREVENTS 'accidental' data disclosure
let rawData = fs.readFileSync(__dirname + '/data/backup.daylio').toString()
let bufferData = new Buffer.from(rawData, 'base64')
DAYLIO_DATA = JSON.parse(bufferData.toString('utf-8'))
prepareIcons()
}
function loadServer() {
let ENTRY_DATA = getEntryData(DAYLIO_DATA)
let VITAL_DATA = getReadableData(DAYLIO_DATA)
let META_DATA = getMetadata(DAYLIO_DATA)
app.get('/', (req, res) => {
res.render('index', {
title: 'Daylio',
entry_data: ENTRY_DATA,
vital_data: VITAL_DATA,
metadata: META_DATA
})
})
/*
* FOR CLIENT SIDE
*/
app.get('/vital', (req, res) => {
res.json( VITAL_DATA )
})
app.get('/entries', (req, res) => {
res.json( ENTRY_DATA )
})
app.get('/structured_data', (req, res) => {
res.json( getStructuredEntries() )
})
app.set('view engine', 'pug')
app.use(express.static(__dirname + '/public'))
const server = app.listen(process.env.PORT || 5000, () => {
console.log(`info: running → http://localhost:${server.address().port}/`)
})
}
async function main() {
console.log('info: starting server')
if (!fs.existsSync(__dirname + '/data/')) {
fs.mkdirSync(__dirname + '/data/')
}
if (DAYLIO_BACKUP) {
console.log(`info: loading backup - ${DAYLIO_BACKUP}`)
await extractDaylioBackup()
} else {
if (!fs.existsSync(__dirname + '/data/backup.daylio')) {
console.log(`error: no previous backups found - pass the '.daylio' file as an argument`)
return
} else {
console.log('info: found backup')
}
}
prepareServer()
loadServer()
}
main()