forked from yasnaraj/react-calendar-events-example
/
event.js
581 lines (536 loc) · 15.1 KB
/
event.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
import { uuid, guaranteeHexColor, sharedUrl, objectToArray } from './eventFN'
import { lookupProfile } from '@stacks/connect'
import { Storage } from '@stacks/storage'
import { getPublicKeyFromPrivate, makeECPrivateKey } from '@stacks/encryption'
import { iCalParseEvents, icsFromEvents } from './ical'
import { parseQueryString, encodeQueryString } from '../utils'
import { defaultCalendars } from './eventDefaults'
// ################
// Contacts
// ################
export function loadGuestProfiles(guests, contacts) {
const profiles = {}
var profilePromises = Promise.resolve({ profiles, contacts })
for (var i in guests) {
const guest = guests[i]
if (guest && guest.length > 0) {
profilePromises = profilePromises.then(({ profiles, contacts }) => {
return lookupProfile(guest).then(
guestProfile => {
profiles[guest] = guestProfile
return { profiles, contacts }
},
error => {
console.log('invalid guest ' + guest, error)
return Promise.resolve({ profiles, contacts })
}
)
})
}
}
return profilePromises
}
function asInviteEvent(d, username) {
const privKey = makeECPrivateKey()
const pubKey = getPublicKeyFromPrivate(privKey)
d.privKey = privKey
d.pubKey = pubKey
d.uid = d.uid || uuid()
d.owner = username
return d
}
export function sendInvitesToGuests(
contacts,
user,
eventInfoRaw,
guestProfiles,
chatSession,
userOwnedStorage
) {
const userSession = chatSession.userSession
const username = user.username
if (!eventInfoRaw) {
console.log('[ERROR] no eventInfoRaw')
return
}
const eventInfo = asInviteEvent(eventInfoRaw, username)
return putOnBlockstack(userSession, sharedUrl(eventInfo.uid), eventInfo, {
encrypt: eventInfo.pubKey,
}).then(readUrl => {
eventInfo.readUrl = readUrl
const addGuestResultHandler = (guestUsername, guestProfile) => {
return ({ contacts, eventInfo }) => {
console.log('found guest ', guestProfile.name)
return addGuest(
guestUsername,
guestProfile,
eventInfo,
contacts,
chatSession,
user
)
}
}
var addGuestPromises = Promise.resolve({ contacts, eventInfo })
for (var guestUsername in guestProfiles) {
const guestProfile = guestProfiles[guestUsername]
if (guestProfile) {
addGuestPromises = addGuestPromises.then(
addGuestResultHandler(guestUsername, guestProfile)
)
} else {
console.log('invalid guest ', guestProfile)
return Promise.resolve({ contacts, eventInfo })
}
}
return addGuestPromises.then(
({ contacts, eventInfo }) => {
userOwnedStorage.publishContacts(contacts)
return { contacts, eventInfo }
},
error => {
return Promise.reject(error)
}
)
})
}
function addGuest(
guestUsername,
guestProfile,
eventInfo,
contacts,
chatSession,
user
) {
var roomPromise
if (contacts[guestUsername] && contacts[guestUsername].roomId) {
console.log('reusing room', { roomId: contacts[guestUsername].roomId })
roomPromise = Promise.resolve({
room_id: contacts[guestUsername].roomId,
})
} else {
console.log('creating new room')
if (!contacts[guestUsername]) {
contacts[guestUsername] = {}
}
roomPromise = chatSession.createNewRoom(
'Events with ' + user.username,
'Invitations, Updates,..'
)
}
return roomPromise.then(
roomResult => {
var roomId = roomResult.room_id
Object.assign(contacts[guestUsername], {
username: guestUsername,
roomId,
})
return sendInviteMessage(
guestUsername,
chatSession,
roomId,
eventInfo,
user.username,
getUserAppAccount(user.profile)
)
.then(() => {
return { contacts, eventInfo }
})
.catch(error => {
console.log('Invitation not sent', error)
return { contacts, eventInfo }
})
},
error => {
console.log('room failure', error)
return Promise.reject(error)
}
)
}
function getUserAppAccount(userProfile) {
const gaiaUrl = userProfile.apps[window.location.origin]
if (gaiaUrl) {
const urlParts = gaiaUrl.split('/')
var appUserAddress = urlParts[urlParts.length - 2]
return addressToAccount(appUserAddress)
}
}
function addressToAccount(address) {
// TODO lookup home server for user
return '@' + address.toLowerCase() + ':openintents.modular.im'
}
function sendInviteMessage(
guestUsername,
userSessionChat,
roomId,
eventInfo,
username,
userAppAccount
) {
const { title, uid, privKey } = eventInfo
const queryString = encodeQueryString({
u: username,
e: uid,
p: privKey,
r: roomId,
s: userAppAccount,
})
const ahref = `<a href='${window.location.origin}${queryString}"'>${title}</a>`
return userSessionChat.sendMessage(guestUsername, roomId, {
msgtype: 'm.text',
body: `You are invited to ${title}`,
format: 'org.matrix.custom.html',
formatted_body: `You are invited to ${ahref}`,
})
}
export function respondToInvite(
userSessionChat,
eventInfo,
rsvp,
senderAppAccount,
roomId
) {
var text
if (rsvp) {
text = 'I will come to ' + eventInfo.title
} else {
text = "I won't come to " + eventInfo.title
}
return userSessionChat.sendMessage(senderAppAccount, roomId, {
msgtype: 'm.text',
body: text,
})
}
// ###########################################################################
// Blockstack helpers
// ###########################################################################
function fetchFromBlockstack(userStorage, src, config, privateKey, errorData) {
return userStorage
.getFile(src, config)
.then(
str => {
if (str && privateKey) {
str = userStorage.decryptContent(str, { privateKey })
}
return str
},
error => {
console.error('failed to fetch ', src, config, !!privateKey, {
error,
errorData,
})
if (error.code !== 'does_not_exist') {
return Promise.reject(
new Error(`Couldn't fetch from fetchFromBlockstack`)
)
}
}
)
.then(d => {
if (d && typeof d === 'string') {
d = JSON.parse(d)
}
return d
})
}
function putOnBlockstack(userStorage, src, text, config) {
if (text && typeof text !== 'string') {
text = JSON.stringify(text)
}
return userStorage.putFile(src, text, config)
}
function applyCalendarDefaults(calendar, user) {
const { hexColor, mode, name: calendarName } = calendar
const eventDefaults = {
mode: mode,
calendarName,
}
const eventOverrides = {
hexColor: guaranteeHexColor(hexColor),
}
if (
calendar.type === 'blockstack-user' &&
calendar.data &&
user &&
calendar.data.user === user.username
) {
eventOverrides.mode = undefined
}
return d => {
return { ...eventDefaults, uid: uuid(), ...d, ...eventOverrides }
}
}
function fetchAndParseIcal(src) {
return fetch(src)
.then(result => result.text())
.then(iCalParseEvents)
}
function fetchFromIcsRaw(src, config) {
return Promise.resolve(iCalParseEvents(config.events))
}
export function handleIntentsInQueryString(
query,
convertEvent,
whenPrivateEvent,
whenNewEvent,
whenICSUrl,
whenViewPublicCalendar,
whenViewEvent,
userSession
) {
if (query) {
const {
u,
e,
p,
intent,
title,
start,
end,
via,
url,
name,
uid,
} = parseQueryString(query)
if (userSession && u && e && p) {
// userSession shouldn't be needed here
return loadCalendarEventFromUser(new Storage(userSession), u, e, p).then(
whenPrivateEvent
)
} else if (intent) {
const intentAction = intent.toLowerCase()
if (intentAction === 'addevent') {
whenNewEvent(convertEvent(title, start, end, via))
} else if (intentAction === 'addics') {
whenICSUrl(url)
} else if (intentAction === 'view') {
if (name) {
whenViewPublicCalendar(name)
} else {
whenViewEvent(uid)
}
} else {
console.log('unsupported intent ' + intentAction)
}
}
}
}
function loadCalendarEventFromUser(
userStorage,
username,
eventUid,
privateKey
) {
return fetchFromBlockstack(
userStorage,
sharedUrl(eventUid),
{ decrypt: false, username },
privateKey,
{ username, eventUid }
)
}
// END of import options
export function addPublicEvent(eventInfo, publicEvents) {
eventInfo.uid = eventInfo.uid || uuid()
publicEvents[eventInfo.uid] = eventInfo
return { republish: true, publicEvents }
}
export function updatePublicEvent(eventInfo, publicEvents) {
publicEvents[eventInfo.uid] = eventInfo
return { republish: true, publicEvents }
}
export function removePublicEvent(eventUid, publicEvents) {
if (!publicEvents[eventUid]) {
// nothing to do
return { republish: false, publicEvents }
} else {
delete publicEvents[eventUid]
return { republish: true, publicEvents }
}
}
export class UserOwnedStorage {
constructor(userSession) {
if (!userSession) {
throw new Error('UserSession required')
}
this.userSession = userSession
this.userStorage = new Storage({ userSession })
}
fetchContactData() {
return fetchFromBlockstack(this.userStorage, 'Contacts').then(contacts => {
return contacts || {}
})
}
publishContacts(contacts) {
return putOnBlockstack(this.userStorage, 'Contacts', contacts)
}
// ###########################################################################
// List of calendars
// ###########################################################################
fetchCalendars() {
return fetchFromBlockstack(this.userStorage, 'Calendars').then(
calendars => {
if (!Array.isArray(calendars)) {
calendars = objectToArray(calendars)
}
return calendars
}
)
}
publishCalendars(calendars) {
if (!Array.isArray(calendars)) {
calendars = Object.values(calendars || {})
}
const privateCalendarIndex = calendars.findIndex(
c => c.type === 'private' && c.name === 'default'
)
if (privateCalendarIndex < 0) {
console.log('adding calendar', defaultCalendars[0])
calendars.splice(0, 0, defaultCalendars[0])
}
putOnBlockstack(this.userStorage, 'Calendars', calendars)
}
// ###########################################################################
// List of all available import functions as promises
// :NOTE: As there is no more reliance on any knowledge of how these evens are managed
// by the app, all import functions could be moved to a separate file
// ###########################################################################
importCalendarEvents(calendar, user, defaultEvents) {
const { type, data, name } = calendar || {}
let fn = () => {}
let config
if (type === 'ics') {
fn = fetchAndParseIcal
} else if (type === 'ics-raw') {
fn = fetchFromIcsRaw
config = { events: data.events }
} else if (type === 'blockstack-user') {
config = { decrypt: false, username: data.user }
fn = (src, config) => fetchFromBlockstack(this.userStorage, src, config)
} else if (type === 'private') {
fn = (src, config) => fetchFromBlockstack(this.userStorage, src, config)
}
return fn(data.src, config)
.then(objectToArray)
.then(events => {
if (!events && type === 'private' && name === 'default') {
putOnBlockstack(this.userStorage, data.src, defaultEvents)
events = Object.values(defaultEvents)
}
return (events || [])
.map(applyCalendarDefaults(calendar, user))
.reduce((acc, d) => {
acc[d.uid] = d
return acc
}, {})
})
}
loadPublicCalendar(calendarName, username) {
const path = calendarName + '/AllEvents'
return fetchFromBlockstack(this.userStorage, path, {
username,
decrypt: false,
}).then(allEvents => {
const calendar = {
type: 'blockstack-user',
mode: 'read-only',
data: { user: username, src: path },
name: calendarName + '@' + username,
}
allEvents = Object.values(allEvents)
return { allEvents, calendar }
})
}
publishCalendar(eventsString, filepath, contentType) {
putOnBlockstack(this.userStorage, filepath, eventsString, {
encrypt: false,
contentType,
}).then(
f => {
console.log('public calendar at ', f)
},
error => {
console.log('error publish calendar', error)
}
)
}
publishEvents(param, updatePublicEvents) {
const publicEventPath = 'public/AllEvents'
fetchFromBlockstack(this.userStorage, publicEventPath, {
decrypt: false,
}).then(publicEvents => {
if (!publicEvents) {
publicEvents = {}
}
const { republish, publicEvents: newPublicEvents } = updatePublicEvents(
param,
publicEvents
)
if (republish) {
this.publishCalendar(
JSON.stringify(newPublicEvents),
publicEventPath,
'text/json'
)
var ics = icsFromEvents(newPublicEvents)
this.publishCalendar(ics, publicEventPath + '.ics', 'text/calendar')
} else {
console.log('nothing to publish')
}
})
}
saveEvents(calendarName, allEvents) {
console.log('save', { calendarName, allEvents })
const calendarEvents = Object.keys(allEvents)
.filter(key => allEvents[key].calendarName === calendarName)
.reduce((res, key) => {
res[key] = allEvents[key]
return res
}, {})
return putOnBlockstack(
this.userStorage,
calendarName + '/AllEvents',
calendarEvents
)
}
fetchPreferences() {
return fetchFromBlockstack(this.userStorage, 'Preferences').then(
prefs => {
if (prefs) {
return prefs
} else {
return {}
}
},
() => {
// TODO check for 404 and only then return empty object, otherwise preferences are overwritten
return {}
}
)
}
savePreferences(prefAttributes) {
return this.fetchPreferences().then(preferences => {
preferences = Object.assign(preferences, prefAttributes)
return putOnBlockstack(this.userStorage, 'Preferences', preferences)
})
}
}
export function fetchIcsUrl(calendarName) {
console.log('calendarName', calendarName)
const parts = calendarName.split('@')
const path = parts[0] + '/AllEvents.ics'
const username = parts[1]
return getUserAppFileUrl(path, username, window.location.origin)
}
async function getUserAppFileUrl(path, username, appOrigin, zoneFileLookupURL) {
const profile = await lookupProfile({ username, zoneFileLookupURL })
let bucketUrl
if (profile.hasOwnProperty('apps')) {
if (profile.apps.hasOwnProperty(appOrigin)) {
const url = profile.apps[appOrigin]
const bucket = url.replace(/\/?(\?|#|$)/, '/$1')
bucketUrl = `${bucket}${path}`
}
}
return bucketUrl
}