summaryrefslogtreecommitdiff
path: root/ui/lib/session.svelte.js
blob: 74508ea0a4c87946e426d114cc6d7fe643691ff6 (plain)
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
import { redirect } from '@sveltejs/kit';

import { goto } from '$app/navigation';

import * as api from './apiServer.js';
import * as r from './state/remote/state.svelte.js';
import * as l from './state/local/conversations.svelte.js';
import * as p from './state/local/push.svelte.js';
import { Watchdog } from './watchdog.js';
import { DateTime } from 'luxon';

class Conversation {
  static fromRemote({ at, id, name }, messages, meta) {
    const sentAt = messages
      .filter((message) => message.conversation === id)
      .map((message) => message.at);
    const lastEventAt = DateTime.max(at, ...sentAt);
    const lastReadAt = meta.get(id)?.lastReadAt;

    const hasUnreads = lastReadAt === undefined || lastEventAt > lastReadAt;
    return new Conversation({ at, id, name, hasUnreads });
  }

  constructor({ at, id, name, hasUnreads }) {
    this.at = at;
    this.id = id;
    this.name = name;
    this.hasUnreads = hasUnreads;
  }
}

class Message {
  static fromRemote({ id, at, conversation, sender, body }, users) {
    return new Message({
      id,
      at,
      conversation,
      sender: users.get(sender),
      body,
    });
  }

  constructor({ id, at, conversation, sender, body }) {
    this.id = id;
    this.at = at;
    this.conversation = conversation;
    this.sender = sender;
    this.body = body;
  }
}

class Session {
  remote = $state();
  local = $state();
  push = $state();
  currentUser = $derived(this.remote.currentUser);
  users = $derived(this.remote.users.all);
  messages = $derived(
    this.remote.messages.all.map((message) => Message.fromRemote(message, this.users)),
  );
  conversations = $derived(
    this.remote.conversations.all.map((conversation) =>
      Conversation.fromRemote(conversation, this.messages, this.local.all),
    ),
  );

  static async boot({ login, resume_point, heartbeat, events }) {
    const remote = r.State.boot({
      currentUser: login,
      resumePoint: resume_point,
      heartbeat,
      events,
    });
    const local = l.Conversations.fromLocalStorage();
    const push = await p.Push.boot(events);
    return new Session(remote, local, push);
  }

  async reboot({ login, resume_point, heartbeat, events }) {
    this.remote = r.State.boot({
      currentUser: login,
      resumePoint: resume_point,
      heartbeat,
      events,
    });
    this.push = await p.Push.boot(events);
  }

  constructor(remote, local, push) {
    this.watchdog = new Watchdog(this.watchdogExpired.bind(this));
    this.remote = remote;
    this.local = local;
    this.push = push;
  }

  begin() {
    this.events = api.subscribeToEvents(this.remote.resumePoint);
    this.events.onmessage = this.onMessage.bind(this);
    this.watchdog.reset(this.heartbeatMillis());
  }

  end() {
    this.watchdog.stop();
    this.events.close();
    this.events = null;
  }

  active() {
    return this.events !== null;
  }

  onMessage(message) {
    const event = JSON.parse(message.data);
    this.remote.onEvent(event);
    this.push.onEvent(event);
    this.local.retainConversations(this.remote.conversations.all);
    this.watchdog.reset(this.heartbeatMillis());
  }

  heartbeatMillis() {
    return this.remote.heartbeat /* in seconds */ * 1000 /* millis */;
  }

  async watchdogExpired() {
    // We leave `this.events` set here as a marker that the interruption is temporary. That's then
    // used below, after a potential delay, to decide whether to start the stream back up again or
    // not.
    this.events.close();
    this.watchdog.stop();

    const response = await bootOrNavigate(goto);
    // Session abandoned; give up here. We need to do this after each await, because that's time in
    // which the session may have been abandoned.
    if (!this.active()) return;

    await this.reboot(response);
    this.begin();
  }
}

async function bootOrNavigate(navigateTo) {
  try {
    const response = await api.retry(async () => await api.boot());
    return response.data;
  } catch (err) {
    switch (true) {
      case err instanceof api.LoggedOut:
        // Can't use `Push` state manager here as it requires boot, which we just failed to do.
        const sw = await navigator.serviceWorker.ready;
        const subscription = await sw.pushManager.getSubscription();
        if (subscription !== null) {
          await subscription.unsubscribe();
        }
        await navigateTo('/login');
        break;
      case err instanceof api.SetupRequired:
        await navigateTo('/setup');
        break;
      default:
        throw err;
    }
  }
}

export async function boot() {
  const response = await bootOrNavigate(async (url) => redirect(307, url));
  return await Session.boot(response);
}