cryptpad/www/common/outer/calendar.js

950 lines
35 KiB
JavaScript
Raw Normal View History

2021-04-02 11:44:28 +00:00
define([
'/common/common-util.js',
'/common/common-hash.js',
'/common/common-constants.js',
'/common/common-realtime.js',
2021-04-06 12:03:51 +00:00
'/common/outer/cache-store.js',
2021-04-02 11:44:28 +00:00
'/customize/messages.js',
2021-04-06 10:12:12 +00:00
'/bower_components/nthen/index.js',
2021-04-02 11:44:28 +00:00
'/bower_components/chainpad-listmap/chainpad-listmap.js',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/chainpad/chainpad.dist.js',
2021-04-06 12:03:51 +00:00
], function (Util, Hash, Constants, Realtime, Cache, Messages, nThen, Listmap, Crypto, ChainPad) {
2021-04-02 11:44:28 +00:00
var Calendar = {};
2021-04-06 10:12:12 +00:00
var getStore = function (ctx, id) {
if (!id || id === 1) {
return ctx.store;
}
var m = ctx.store.modules && ctx.store.modules.team;
if (!m) { return; }
return m.getTeam(id);
};
2021-04-02 11:44:28 +00:00
var makeCalendar = function () {
var hash = Hash.createRandomHash('calendar');
var secret = Hash.getSecrets('calendar', hash);
var roHash = Hash.getViewHashFromKeys(secret);
var href = Hash.hashToHref(hash, 'calendar');
var roHref = Hash.hashToHref(roHash, 'calendar');
return {
href: href,
roHref: roHref,
channel: secret.channel,
};
};
var initializeCalendars = function (ctx, cb) {
var proxy = ctx.store.proxy;
proxy.calendars = proxy.calendars || {};
2021-04-02 11:44:28 +00:00
setTimeout(cb);
};
var sendUpdate = function (ctx, c) {
ctx.emit('UPDATE', {
teams: c.stores,
roTeams: c.roStores,
2021-04-02 11:44:28 +00:00
id: c.channel,
2021-04-06 13:01:43 +00:00
loading: !c.ready && !c.cacheready,
readOnly: c.readOnly || (!c.ready && c.cacheready) || c.offline,
offline: c.offline,
2021-04-06 08:37:31 +00:00
deleted: !c.stores.length,
2021-04-06 12:03:51 +00:00
restricted: c.restricted,
2021-04-06 13:01:43 +00:00
owned: ctx.Store.isOwned(c.owners),
2021-04-06 15:25:18 +00:00
content: Util.clone(c.proxy),
hashes: c.hashes
2021-04-02 11:44:28 +00:00
}, ctx.clients);
};
2021-04-09 16:10:13 +00:00
var clearReminders = function (ctx, id) {
var calendar = ctx.calendars[id];
if (!calendar || !calendar.reminders) { return; }
// Clear existing reminders
Object.keys(calendar.reminders).forEach(function (uid) {
if (!Array.isArray(calendar.reminders[uid])) { return; }
calendar.reminders[uid].forEach(function (to) { clearTimeout(to); });
});
};
var closeCalendar = function (ctx, id) {
var ctxCal = ctx.calendars[id];
if (!ctxCal) { return; }
// If the calendar doesn't exist in any other team, stop it and delete it from ctx
if (!ctxCal.stores.length) {
ctxCal.lm.stop();
2021-04-09 16:10:13 +00:00
clearReminders(ctx, id);
delete ctx.calendars[id];
}
};
2021-04-02 16:21:59 +00:00
var updateLocalCalendars = function (ctx, c, data) {
// Also update local data
c.stores.forEach(function (id) {
var s = getStore(ctx, id);
if (!s || !s.proxy) { return; }
if (!s.rpc) { return; } // team viewer
if (!s.proxy.calendars) { return; }
var cal = s.proxy.calendars[c.channel];
if (!cal) { return; }
if (cal.color !== data.color) { cal.color = data.color; }
if (cal.title !== data.title) { cal.title = data.title; }
});
};
2021-04-09 16:10:13 +00:00
2021-04-13 15:44:35 +00:00
var updateEventReminders = function (ctx, reminders, _ev, useLastVisit) {
2021-04-09 16:10:13 +00:00
var now = +new Date();
2021-04-13 15:44:35 +00:00
var ev = Util.clone(_ev);
2021-04-09 16:10:13 +00:00
var uid = ev.id;
2021-04-12 15:55:56 +00:00
//ctx.store.data.lastVisit = 1617922639683; // XXX Friday Apr 09, used to test
2021-04-09 16:10:13 +00:00
// Clear reminders for this event
if (Array.isArray(reminders[uid])) {
reminders[uid].forEach(function (to) { clearTimeout(to); });
}
reminders[uid] = [];
var last = ctx.store.data.lastVisit;
2021-04-13 15:44:35 +00:00
if (ev.isAllDay) {
if (ev.startDay) { ev.start = +new Date(ev.startDay); }
if (ev.endDay) {
2021-04-14 09:42:41 +00:00
var endDate = new Date(ev.endDay);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
2021-04-14 09:42:41 +00:00
ev.end = +endDate;
}
2021-04-13 15:44:35 +00:00
}
// XXX add a limit to make sure we don't go too far in the past?
var missed = useLastVisit && ev.start > last && ev.end <= now;
if (ev.end <= now && !missed) {
// No reminder for past events
2021-04-09 16:10:13 +00:00
delete reminders[uid];
return;
}
// XXX
// TODO
// use custom notifications per event
// if you missed a notification, show it instantly (eg: load cryptpad 45min before an event, show the 1h notification)
2021-04-09 16:10:13 +00:00
var send = function () {
2021-04-12 09:19:12 +00:00
var hide = Util.find(ctx, ['store', 'proxy', 'settings', 'general', 'calendar', 'hideNotif']);
2021-04-12 12:16:42 +00:00
if (hide) { return; }
var ctime = ev.start <= now ? ev.start : +new Date(); // Correct order for past events
2021-04-09 16:10:13 +00:00
ctx.store.mailbox.showMessage('reminders', {
msg: {
ctime: ctime,
2021-04-09 16:10:13 +00:00
type: "REMINDER",
missed: Boolean(missed),
2021-04-09 16:10:13 +00:00
content: ev
},
hash: 'REMINDER|'+uid
}, null, function () {
});
};
var sendNotif = function () { ctx.Store.onReadyEvt.reg(send); };
2021-04-13 13:21:24 +00:00
var notifs = ev.reminders || [];
2021-04-15 09:11:46 +00:00
notifs.sort(function (a, b) {
return a - b;
});
2021-04-09 16:10:13 +00:00
2021-04-13 13:21:24 +00:00
notifs.some(function (delayMinutes) {
var delay = delayMinutes * 60000;
2021-04-12 15:55:56 +00:00
var time = now + delay;
2021-04-12 14:38:39 +00:00
2021-04-12 15:55:56 +00:00
// setTimeout only work with 32bit timeout values. If the event is too far away,
// ignore this event for now
// FIXME: call this function again in xxx days to reload these missing timeout?
if (ev.start - time >= 2147483647) { return true; }
2021-04-12 14:38:39 +00:00
2021-04-12 15:55:56 +00:00
// If we're too late to send a notification, send it instantly and ignore
// all notifications that were supposed to be sent even earlier
if (ev.start <= time) {
sendNotif();
return true;
}
2021-04-09 16:10:13 +00:00
2021-04-12 15:55:56 +00:00
// It starts in more than "delay": prepare the notification
reminders[uid].push(setTimeout(function () {
sendNotif();
}, (ev.start - time)));
});
2021-04-09 16:10:13 +00:00
};
var addReminders = function (ctx, id, ev) {
var calendar = ctx.calendars[id];
if (!calendar || !calendar.reminders) { return; }
if (calendar.stores.length === 1 && calendar.stores[0] === 0) { return; }
updateEventReminders(ctx, calendar.reminders, ev);
};
var addInitialReminders = function (ctx, id, useLastVisit) {
2021-04-09 16:10:13 +00:00
var calendar = ctx.calendars[id];
if (!calendar || !calendar.reminders) { return; }
if (Object.keys(calendar.reminders).length) { return; } // Already initialized
// No reminders for calendars not stored
if (calendar.stores.length === 1 && calendar.stores[0] === 0) { return; }
// Re-add all reminders
var content = Util.find(calendar, ['proxy', 'content']);
if (!content) { return; }
Object.keys(content).forEach(function (uid) {
updateEventReminders(ctx, calendar.reminders, content[uid], useLastVisit);
2021-04-09 16:10:13 +00:00
});
};
2021-04-02 13:18:59 +00:00
var openChannel = function (ctx, cfg, _cb) {
var cb = Util.once(Util.mkAsync(_cb || function () {}));
2021-04-02 11:44:28 +00:00
var teamId = cfg.storeId;
var data = cfg.data;
var channel = data.channel;
if (!channel) { return; }
var c = ctx.calendars[channel];
2021-04-06 15:25:18 +00:00
var update = function () {
sendUpdate(ctx, c);
};
2021-04-02 11:44:28 +00:00
if (c) {
if (c.readOnly && data.href) {
// Upgrade readOnly calendar to editable
var upgradeParsed = Hash.parsePadUrl(data.href);
var upgradeSecret = Hash.getSecrets('calendar', upgradeParsed.hash, data.password);
var upgradeCrypto = Crypto.createEncryptor(upgradeSecret.keys);
c.hashes.editHash = Hash.getEditHashFromKeys(upgradeSecret);
c.lm.setReadOnly(false, upgradeCrypto);
c.readOnly = false;
} else if (teamId === 0) {
// Existing calendars can't be "temp calendars" (unless they are an upgrade)
return void cb();
2021-04-02 11:44:28 +00:00
}
// Remove from roStores when upgrading this store
if (c.roStores.indexOf(teamId) !== -1 && data.href) {
c.roStores.splice(c.roStores.indexOf(teamId), 1);
// If we've upgraded a stored calendar, remove the temp calendar
if (c.stores.indexOf(0) !== -1) {
c.stores.splice(c.stores.indexOf(0), 1);
}
update();
}
// Don't store duplicates
2021-04-06 15:25:18 +00:00
if (c.stores && c.stores.indexOf(teamId) !== -1) { return void cb(); }
// If we store a temp calendar to our account or team, remove this "temp calendar"
if (c.stores.indexOf(0) !== -1) { c.stores.splice(c.stores.indexOf(0), 1); }
2021-04-02 11:44:28 +00:00
c.stores.push(teamId);
if (!data.href) {
c.roStores.push(teamId);
}
2021-04-06 15:25:18 +00:00
update();
return void cb();
2021-04-02 11:44:28 +00:00
}
// Multiple teams can have the same calendar. Make sure we remember the list of stores
// that know it so that we don't close the calendar when leaving/deleting a team.
c = ctx.calendars[channel] = {
ready: false,
channel: channel,
readOnly: !data.href,
2021-04-06 15:25:18 +00:00
stores: [teamId],
roStores: data.href ? [] : [teamId],
2021-04-09 16:10:13 +00:00
reminders: {},
2021-04-06 15:25:18 +00:00
hashes: {}
2021-04-02 11:44:28 +00:00
};
var parsed = Hash.parsePadUrl(data.href || data.roHref);
2021-04-06 16:21:48 +00:00
var secret = Hash.getSecrets('calendar', parsed.hash, data.password);
2021-04-02 11:44:28 +00:00
var crypto = Crypto.createEncryptor(secret.keys);
2021-04-06 15:25:18 +00:00
c.hashes.viewHash = Hash.getViewHashFromKeys(secret);
if (data.href) {
c.hashes.editHash = Hash.getEditHashFromKeys(secret);
}
2021-04-06 13:01:43 +00:00
c.proxy = {
metadata: {
color: data.color,
title: data.title
}
};
update();
var onDeleted = function () {
// Remove this calendar from all our teams
// XXX Maybe not? don't remove automatically so that we can tell the user to do so.
2021-04-06 13:01:43 +00:00
c.stores.forEach(function (storeId) {
var store = getStore(ctx, storeId);
if (!store || !store.rpc || !store.proxy.calendars) { return; }
delete store.proxy.calendars[channel];
// And unpin
var unpin = store.unpin || ctx.unpinPads;
unpin([channel], function (res) {
if (res && res.error) { console.error(res.error); }
});
});
// Close listmap, update the UI and clear the memory
if (c.lm) { c.lm.stop(); }
c.stores = [];
sendUpdate(ctx, c);
2021-04-09 16:10:13 +00:00
clearReminders(ctx, channel);
2021-04-06 13:01:43 +00:00
delete ctx.calendars[channel];
};
2021-04-06 10:12:12 +00:00
2021-04-06 13:01:43 +00:00
nThen(function (waitFor) {
if (!ctx.store.network || cfg.isNew) { return; }
// This is supposed to be an existing channel. Make sure it exists on the server
// before trying to load it.
// NOTE: if we can't check (error), we can skip this step. On "ready", we have
// another check to make sure we won't make a new calendar
ctx.Store.isNewChannel(null, channel, waitFor(function (obj) {
if (obj && obj.error) {
// If we can't check, skip this part
return;
}
if (obj && typeof(obj.isNew) === "boolean") {
if (obj.isNew) {
onDeleted();
2021-04-06 16:21:48 +00:00
cb({error: 'EDELETED'});
2021-04-06 13:01:43 +00:00
waitFor.abort();
return;
}
}
}));
2021-04-06 10:12:12 +00:00
}).nThen(function () {
// Set the owners as the first store opening it. We don't know yet if it's a new or
// existing calendar. "owners' will be ignored if the calendar already exists.
var edPublic;
2021-04-06 16:21:48 +00:00
if (teamId === 1 || !teamId) {
2021-04-06 10:12:12 +00:00
edPublic = ctx.store.proxy.edPublic;
} else {
var teams = ctx.store.modules.team && ctx.store.modules.team.getTeamsData();
var team = teams && teams[teamId];
edPublic = team ? team.edPublic : undefined;
2021-04-02 13:18:59 +00:00
}
2021-04-06 10:12:12 +00:00
var config = {
data: {},
2021-04-06 13:01:43 +00:00
network: ctx.store.network || ctx.store.networkPromise,
2021-04-06 10:12:12 +00:00
channel: secret.channel,
crypto: crypto,
owners: [edPublic],
ChainPad: ChainPad,
validateKey: secret.keys.validateKey || undefined,
userName: 'calendar',
2021-04-06 12:03:51 +00:00
Cache: Cache,
classic: true,
onRejected: ctx.Store && ctx.Store.onRejected
2021-04-06 10:12:12 +00:00
};
var lm = Listmap.create(config);
c.lm = lm;
var proxy = c.proxy = lm.proxy;
2021-04-06 12:03:51 +00:00
lm.proxy.on('cacheready', function () {
if (!proxy.metadata) { return; }
c.cacheready = true;
setTimeout(update);
if (cb) { cb(null, lm.proxy); }
addInitialReminders(ctx, channel, cfg.lastVisitNotif);
2021-04-06 13:01:43 +00:00
}).on('ready', function (info) {
var md = info.metadata;
c.owners = md.owners || [];
2021-04-06 10:12:12 +00:00
c.ready = true;
if (!proxy.metadata) {
if (!cfg.isNew) {
2021-04-06 13:01:43 +00:00
// no metadata on an existing calendar: deleted calendar
2021-04-06 10:12:12 +00:00
return void onDeleted();
}
proxy.metadata = {
color: data.color,
title: data.title
};
}
setTimeout(update);
if (cb) { cb(null, lm.proxy); }
addInitialReminders(ctx, channel, cfg.lastVisitNotif);
2021-04-06 10:12:12 +00:00
}).on('change', [], function () {
if (!c.ready) { return; }
setTimeout(update);
2021-04-09 16:10:13 +00:00
}).on('change', ['content'], function (o, n, p) {
if (p.length === 2 && n && !o) { // New event
addReminders(ctx, channel, n);
}
if (p.length === 2 && !n && o) { // Deleted event
addReminders(ctx, channel, {
id: p[1],
start: 0
});
}
if (p.length === 3 && n && o && p[2] === 'start') { // Update event start
setTimeout(function () {
addReminders(ctx, channel, proxy.content[p[1]]);
});
}
2021-04-06 10:12:12 +00:00
}).on('change', ['metadata'], function () {
// if title or color have changed, update our local values
var md = proxy.metadata;
if (!md || !md.title || !md.color) { return; }
updateLocalCalendars(ctx, c, md);
}).on('disconnect', function () {
c.offline = true;
setTimeout(update);
}).on('reconnect', function () {
c.offline = false;
setTimeout(update);
2021-04-06 10:12:12 +00:00
}).on('error', function (info) {
if (!info || !info.error) { return; }
if (info.error === "EDELETED" ) {
return void onDeleted();
}
2021-04-06 12:03:51 +00:00
if (info.error === "ERESTRICTED" ) {
c.restricted = true;
}
2021-04-06 10:12:12 +00:00
cb(info);
});
2021-04-02 11:44:28 +00:00
});
};
2021-04-08 10:02:36 +00:00
var decryptTeamCalendarHref = function (store, calData) {
if (!calData.href) { return; }
// Already decrypted? nothing to do
if (calData.href.indexOf('#') !== -1) { return; }
// href exists and is encrypted: decrypt if we can or ignore the href
if (store.secondaryKey) {
try {
calData.href = store.userObject.cryptor.decrypt(calData.href);
} catch (e) {
console.error(e);
delete calData.href;
}
} else {
delete calData.href;
}
};
var initializeStore = function (ctx, store) {
var c = store.proxy.calendars;
var storeId = store.id || 1;
// Add listeners
store.proxy.on('change', ['calendars'], function (o, n, p) {
if (p.length < 2) { return; }
// Handle deletions
if (o && !n) {
(function () {
var id = p[1];
var ctxCal = ctx.calendars[id];
if (!ctxCal) { return; }
var idx = ctxCal.stores.indexOf(storeId);
// Check if the team has loaded this calendar in memory
if (idx === -1) { return; }
// Remove the team from memory
ctxCal.stores.splice(idx, 1);
var roIdx = ctxCal.roStores.indexOf(storeId);
if (roIdx !== -1) { ctxCal.roStores.splice(roIdx, 1); }
// Check if we need to close listmap and update the UI
closeCalendar(ctx, id);
sendUpdate(ctx, ctxCal);
})();
}
// Handle additions
2021-04-08 12:02:39 +00:00
// NOTE: this also upgrade from readOnly to edit (add an "href" to the calendar)
if (!o && n) {
(function () {
var id = p[1];
2021-04-08 10:02:36 +00:00
var _cal = store.proxy.calendars[id];
if (!_cal) { return; }
var cal = Util.clone(_cal);
decryptTeamCalendarHref(store, cal);
openChannel(ctx, {
storeId: storeId,
2021-04-08 10:02:36 +00:00
data: cal
});
})();
}
});
2021-04-02 11:44:28 +00:00
// If this store contains existing calendars, open them
Object.keys(c || {}).forEach(function (channel) {
2021-04-08 10:02:36 +00:00
var cal = Util.clone(c[channel]);
decryptTeamCalendarHref(store, cal);
openChannel(ctx, {
storeId: storeId,
lastVisitNotif: true,
2021-04-08 10:02:36 +00:00
data: cal
});
});
};
var openChannels = function (ctx) {
2021-04-02 11:44:28 +00:00
// Personal drive
initializeStore(ctx, ctx.store);
2021-04-06 15:25:18 +00:00
var teams = ctx.store.modules.team && ctx.store.modules.team.getTeamsData();
if (!teams) { return; }
Object.keys(teams).forEach(function (id) {
var store = getStore(ctx, id);
initializeStore(ctx, store);
2021-04-06 15:25:18 +00:00
});
2021-04-02 11:44:28 +00:00
};
var subscribe = function (ctx, data, cId, cb) {
// Subscribe to new notifications
var idx = ctx.clients.indexOf(cId);
if (idx === -1) {
ctx.clients.push(cId);
}
2021-04-02 13:18:59 +00:00
cb({
empty: !Object.keys(ctx.calendars).length
});
2021-04-02 11:44:28 +00:00
Object.keys(ctx.calendars).forEach(function (channel) {
var c = ctx.calendars[channel] || {};
sendUpdate(ctx, c);
});
};
2021-04-15 15:45:38 +00:00
var importICSCalendar = function (ctx, data, cId, cb) {
var id = data.id;
var c = ctx.calendars[id];
if (!c || !c.proxy) { return void cb({error: "ENOENT"}); }
var json = data.json;
c.proxy.content = c.proxy.content || {};
Object.keys(json).forEach(function (uid) {
c.proxy.content[uid] = json[uid];
});
Realtime.whenRealtimeSyncs(c.lm.realtime, function () {
sendUpdate(ctx, c);
cb();
});
};
2021-04-06 16:21:48 +00:00
var openCalendar = function (ctx, data, cId, cb) {
var secret = Hash.getSecrets('calendar', data.hash, data.password);
2021-04-07 13:49:20 +00:00
var hash = Hash.getEditHashFromKeys(secret);
var roHash = Hash.getViewHashFromKeys(secret);
2021-04-06 16:21:48 +00:00
var cal = {
2021-04-07 13:49:20 +00:00
href: hash && Hash.hashToHref(hash, 'calendar'),
roHref: roHash && Hash.hashToHref(roHash, 'calendar'),
2021-04-06 16:21:48 +00:00
channel: secret.channel,
color: Util.getRandomColor(),
title: '...'
};
openChannel(ctx, {
storeId: 0,
2021-04-08 10:02:36 +00:00
data: cal
2021-04-06 16:21:48 +00:00
}, cb);
};
var importCalendar = function (ctx, data, cId, cb) {
var id = data.id;
var c = ctx.calendars[id];
if (!c) { return void cb({error: "ENOENT"}); }
if (!Array.isArray(c.stores) || c.stores.indexOf(data.teamId) === -1) {
return void cb({error: 'EINVAL'});
}
// Add to my calendars
var store = ctx.store;
var calendars = store.proxy.calendars = store.proxy.calendars || {};
var hash = c.hashes.editHash;
var roHash = c.hashes.viewHash;
calendars[id] = {
href: hash && Hash.hashToHref(hash, 'calendar'),
roHref: roHash && Hash.hashToHref(roHash, 'calendar'),
channel: id,
color: Util.find(c,['proxy', 'metadata', 'color']) || Util.getRandomColor(),
title: Util.find(c,['proxy', 'metadata', 'title']) || '...'
};
ctx.Store.onSync(null, cb);
// Make the change in memory
openChannel(ctx, {
storeId: 1,
data: {
href: calendars[id].href,
toHref: calendars[id].roHref,
channel: id
}
});
};
2021-04-06 15:25:18 +00:00
var addCalendar = function (ctx, data, cId, cb) {
var store = getStore(ctx, data.teamId);
if (!store) { return void cb({error: "NO_STORE"}); }
// Check team edit rights: viewers in teams don't have rpc
if (!store.rpc) { return void cb({error: "EFORBIDDEN"}); }
var c = store.proxy.calendars = store.proxy.calendars || {};
var parsed = Hash.parsePadUrl(data.href);
var secret = Hash.getSecrets(parsed.type, parsed.hash, data.password);
if (secret.channel !== data.channel) { return void cb({error: 'EINVAL'}); }
var hash = Hash.getEditHashFromKeys(secret);
var roHash = Hash.getViewHashFromKeys(secret);
2021-04-08 10:02:36 +00:00
var href = hash && Hash.hashToHref(hash, 'calendar');
2021-04-06 15:25:18 +00:00
var cal = {
2021-04-08 10:02:36 +00:00
href: href,
roHref: roHash && Hash.hashToHref(roHash, 'calendar'),
2021-04-06 15:25:18 +00:00
color: data.color,
title: data.title,
channel: data.channel
};
// If it already existed and it's not an upgrade, nothing to do
if (c[data.channel] && (c[data.channel].href || !cal.href)) { return void cb(); }
2021-04-06 15:25:18 +00:00
cal.color = data.color;
cal.title = data.title;
openChannel(ctx, {
storeId: store.id || 1,
2021-04-08 10:02:36 +00:00
data: Util.clone(cal)
2021-04-06 15:25:18 +00:00
}, function (err) {
if (err) {
// Can't open this channel, don't store it
console.error(err);
2021-04-08 12:02:39 +00:00
return void cb({error: err.error});
2021-04-06 15:25:18 +00:00
}
2021-04-08 10:02:36 +00:00
if (href && store.id && store.secondaryKey) {
try {
cal.href = store.userObject.cryptor.encrypt(href);
} catch (e) {
console.error(e);
}
}
2021-04-06 15:25:18 +00:00
// Add the calendar and call back
// If it already existed it means this is an upgrade
2021-04-06 15:25:18 +00:00
c[cal.channel] = cal;
var pin = store.pin || ctx.pinPads;
pin([cal.channel], function (res) {
if (res && res.error) { console.error(res.error); }
});
ctx.Store.onSync(store.id, cb);
});
};
2021-04-02 13:18:59 +00:00
var createCalendar = function (ctx, data, cId, cb) {
var store = getStore(ctx, data.teamId);
if (!store) { return void cb({error: "NO_STORE"}); }
// Check team edit rights: viewers in teams don't have rpc
if (!store.rpc) { return void cb({error: "EFORBIDDEN"}); }
var c = store.proxy.calendars = store.proxy.calendars || {};
var cal = makeCalendar();
cal.color = data.color;
cal.title = data.title;
openChannel(ctx, {
storeId: store.id || 1,
2021-04-06 10:12:12 +00:00
data: cal,
isNew: true
2021-04-06 15:25:18 +00:00
}, function (err) {
2021-04-02 13:18:59 +00:00
if (err) {
// Can't open this channel, don't store it
console.error(err);
2021-04-08 12:02:39 +00:00
return void cb({error: err.error});
2021-04-02 13:18:59 +00:00
}
// Add the calendar and call back
2021-04-09 11:23:28 +00:00
// Wait for the metadata to be stored (channel fully ready) before adding it
// to our store
var ctxCal = ctx.calendars[cal.channel];
Realtime.whenRealtimeSyncs(ctxCal.lm.realtime, function () {
c[cal.channel] = cal;
var pin = store.pin || ctx.pinPads;
pin([cal.channel], function (res) {
if (res && res.error) { console.error(res.error); }
});
ctx.Store.onSync(store.id, cb);
2021-04-06 08:26:30 +00:00
});
2021-04-02 13:18:59 +00:00
});
};
2021-04-02 16:21:59 +00:00
var updateCalendar = function (ctx, data, cId, cb) {
var id = data.id;
var c = ctx.calendars[id];
if (!c) { return void cb({error: "ENOENT"}); }
var md = Util.find(c, ['proxy', 'metadata']);
if (!md) { return void cb({error: 'EINVAL'}); }
md.title = data.title;
md.color = data.color;
Realtime.whenRealtimeSyncs(c.lm.realtime, cb);
sendUpdate(ctx, c);
updateLocalCalendars(ctx, c, data);
};
var deleteCalendar = function (ctx, data, cId, cb) {
var store = getStore(ctx, data.teamId);
if (!store) { return void cb({error: "NO_STORE"}); }
if (!store.rpc) { return void cb({error: "EFORBIDDEN"}); }
if (!store.proxy.calendars) { return; }
var id = data.id;
var cal = store.proxy.calendars[id];
if (!cal) { return void cb(); } // Already deleted
2021-04-06 09:31:25 +00:00
// Delete
2021-04-02 16:21:59 +00:00
delete store.proxy.calendars[id];
2021-04-06 09:31:25 +00:00
// Unpin
2021-04-06 08:26:30 +00:00
var unpin = store.unpin || ctx.unpinPads;
unpin([id], function (res) {
2021-04-06 10:12:12 +00:00
if (res && res.error) { console.error(res.error); }
2021-04-06 08:26:30 +00:00
});
2021-04-06 08:37:31 +00:00
2021-04-06 09:31:25 +00:00
// Clear/update ctx data
// Remove this store from the calendar's clients
2021-04-06 08:37:31 +00:00
var ctxCal = ctx.calendars[id];
var idx = ctxCal.stores.indexOf(store.id || 1);
ctxCal.stores.splice(idx, 1);
closeCalendar(ctx, id);
2021-04-06 08:37:31 +00:00
ctx.Store.onSync(store.id, function () {
sendUpdate(ctx, ctxCal);
cb();
});
2021-04-02 16:21:59 +00:00
};
2021-04-02 13:18:59 +00:00
var createEvent = function (ctx, data, cId, cb) {
var id = data.calendarId;
var c = ctx.calendars[id];
if (!c) { return void cb({error: "ENOENT"}); }
var startDate = new Date(data.start);
var endDate = new Date(data.end);
if (data.isAllDay) {
data.startDay = startDate.getFullYear() + '-' + (startDate.getMonth()+1) + '-' + startDate.getDate();
data.endDay = endDate.getFullYear() + '-' + (endDate.getMonth()+1) + '-' + endDate.getDate();
} else {
2021-04-13 15:45:18 +00:00
delete data.startDay;
delete data.endDay;
}
2021-04-02 13:18:59 +00:00
c.proxy.content = c.proxy.content || {};
c.proxy.content[data.id] = data;
2021-04-06 10:12:12 +00:00
Realtime.whenRealtimeSyncs(c.lm.realtime, function () {
2021-04-09 16:10:13 +00:00
addReminders(ctx, id, data);
2021-04-06 10:12:12 +00:00
sendUpdate(ctx, c);
cb();
});
2021-04-02 13:18:59 +00:00
};
var updateEvent = function (ctx, data, cId, cb) {
if (!data || !data.ev) { return void cb({error: 'EINVAL'}); }
var id = data.ev.calendarId;
var c = ctx.calendars[id];
if (!c || !c.proxy || !c.proxy.content) { return void cb({error: "ENOENT"}); }
// Find the event
var ev = c.proxy.content[data.ev.id];
if (!ev) { return void cb({error: "EINVAL"}); }
// update the event
var changes = data.changes || {};
var newC;
if (changes.calendarId) {
newC = ctx.calendars[changes.calendarId];
2021-04-09 11:23:28 +00:00
if (!newC || !newC.proxy) { return void cb({error: "ENOENT"}); }
newC.proxy.content = newC.proxy.content || {};
}
2021-04-02 13:18:59 +00:00
Object.keys(changes).forEach(function (key) {
ev[key] = changes[key];
});
var startDate = new Date(ev.start);
var endDate = new Date(ev.end);
if (ev.isAllDay) {
ev.startDay = startDate.getFullYear() + '-' + (startDate.getMonth()+1) + '-' + startDate.getDate();
ev.endDay = endDate.getFullYear() + '-' + (endDate.getMonth()+1) + '-' + endDate.getDate();
} else {
delete ev.startDay;
delete ev.endDay;
}
2021-04-09 16:10:13 +00:00
// Move to a different calendar?
if (changes.calendarId && newC) {
newC.proxy.content[data.ev.id] = Util.clone(ev);
delete c.proxy.content[data.ev.id];
}
nThen(function (waitFor) {
Realtime.whenRealtimeSyncs(c.lm.realtime, waitFor());
if (newC) { Realtime.whenRealtimeSyncs(newC.lm.realtime, waitFor()); }
2021-04-09 16:10:13 +00:00
}).nThen(function () {
2021-04-13 14:46:04 +00:00
if (newC) {
// Move reminders to the new calendar
addReminders(ctx, id, {
id: ev.id,
start: 0
});
addReminders(ctx, ev.calendarId, ev);
} else if (changes.start || changes.reminders || changes.isAllDay) {
// Update reminders
addReminders(ctx, id, ev);
}
sendUpdate(ctx, c);
if (newC) { sendUpdate(ctx, newC); }
2021-04-09 16:10:13 +00:00
cb();
});
2021-04-02 13:18:59 +00:00
};
var deleteEvent = function (ctx, data, cId, cb) {
var id = data.calendarId;
var c = ctx.calendars[id];
if (!c) { return void cb({error: "ENOENT"}); }
c.proxy.content = c.proxy.content || {};
delete c.proxy.content[data.id];
2021-04-09 16:10:13 +00:00
Realtime.whenRealtimeSyncs(c.lm.realtime, function () {
addReminders(ctx, id, {
id: data.id,
start: 0
});
sendUpdate(ctx, c);
2021-04-13 09:37:48 +00:00
cb();
2021-04-09 16:10:13 +00:00
});
2021-04-02 13:18:59 +00:00
};
2021-04-02 11:44:28 +00:00
var removeClient = function (ctx, cId) {
var idx = ctx.clients.indexOf(cId);
ctx.clients.splice(idx, 1);
};
Calendar.init = function (cfg, waitFor, emit) {
var calendar = {};
var store = cfg.store;
if (!store.loggedIn || !store.proxy.edPublic) { return; } // XXX logged in only?
var ctx = {
store: store,
Store: cfg.Store,
pinPads: cfg.pinPads,
2021-04-06 09:31:25 +00:00
unpinPads: cfg.unpinPads,
2021-04-02 11:44:28 +00:00
updateMetadata: cfg.updateMetadata,
emit: emit,
onReady: Util.mkEvent(true),
calendars: {},
2021-04-09 16:10:13 +00:00
clients: []
2021-04-02 11:44:28 +00:00
};
initializeCalendars(ctx, waitFor(function (err) {
if (err) { return; }
openChannels(ctx);
}));
calendar.closeTeam = function (teamId) {
Object.keys(ctx.calendars).forEach(function (id) {
var ctxCal = ctx.calendars[id];
var idx = ctxCal.stores.indexOf(teamId);
if (idx === -1) { return; }
ctxCal.stores.splice(idx, 1);
var roIdx = ctxCal.roStores.indexOf(teamId);
if (roIdx !== -1) { ctxCal.roStores.splice(roIdx, 1); }
closeCalendar(ctx, id);
sendUpdate(ctx, ctxCal);
});
};
calendar.openTeam = function (teamId) {
var store = getStore(ctx, teamId);
if (!store) { return; }
initializeStore(ctx, store);
};
2021-04-08 10:02:36 +00:00
calendar.upgradeTeam = function (teamId) {
if (!teamId) { return; }
var store = getStore(ctx, teamId);
if (!store) { return; }
Object.keys(ctx.calendars).forEach(function (id) {
var ctxCal = ctx.calendars[id];
var idx = ctxCal.stores.indexOf(teamId);
if (idx === -1) { return; }
var _cal = store.proxy.calendars[id];
var cal = Util.clone(_cal);
decryptTeamCalendarHref(store, cal);
openChannel(ctx, {
storeId: teamId,
data: cal
});
sendUpdate(ctx, ctxCal);
});
};
2021-04-02 11:44:28 +00:00
calendar.removeClient = function (clientId) {
removeClient(ctx, clientId);
};
calendar.execCommand = function (clientId, obj, cb) {
var cmd = obj.cmd;
var data = obj.data;
if (cmd === 'SUBSCRIBE') {
return void subscribe(ctx, data, clientId, cb);
}
2021-04-06 16:21:48 +00:00
if (cmd === 'OPEN') {
ctx.Store.onReadyEvt.reg(function () {
openCalendar(ctx, data, clientId, cb);
});
return;
}
if (cmd === 'IMPORT') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
return void importCalendar(ctx, data, clientId, cb);
}
2021-04-15 15:45:38 +00:00
if (cmd === 'IMPORT_ICS') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
return void importICSCalendar(ctx, data, clientId, cb);
}
2021-04-06 15:25:18 +00:00
if (cmd === 'ADD') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
return void addCalendar(ctx, data, clientId, cb);
}
2021-04-02 13:18:59 +00:00
if (cmd === 'CREATE') {
2021-04-08 10:02:36 +00:00
if (data.initialCalendar) {
return void ctx.Store.onReadyEvt.reg(function () {
createCalendar(ctx, data, clientId, cb);
});
}
2021-04-06 13:01:43 +00:00
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
2021-04-02 13:18:59 +00:00
return void createCalendar(ctx, data, clientId, cb);
}
2021-04-02 16:21:59 +00:00
if (cmd === 'UPDATE') {
2021-04-06 13:01:43 +00:00
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
2021-04-02 16:21:59 +00:00
return void updateCalendar(ctx, data, clientId, cb);
}
2021-04-06 09:31:25 +00:00
if (cmd === 'DELETE') {
2021-04-06 13:01:43 +00:00
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
2021-04-06 09:31:25 +00:00
return void deleteCalendar(ctx, data, clientId, cb);
}
2021-04-02 13:18:59 +00:00
if (cmd === 'CREATE_EVENT') {
2021-04-06 13:01:43 +00:00
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
2021-04-02 13:18:59 +00:00
return void createEvent(ctx, data, clientId, cb);
}
if (cmd === 'UPDATE_EVENT') {
2021-04-06 13:01:43 +00:00
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
2021-04-02 13:18:59 +00:00
return void updateEvent(ctx, data, clientId, cb);
}
if (cmd === 'DELETE_EVENT') {
2021-04-06 13:01:43 +00:00
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
2021-04-02 13:18:59 +00:00
return void deleteEvent(ctx, data, clientId, cb);
}
2021-04-02 11:44:28 +00:00
};
return calendar;
};
return Calendar;
});