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

import * as api from './apiServer.js';
import * as r from './state/remote/state.svelte.js';
import * as l from './state/local/channels.svelte.js';

class Session {
  remote = $state();
  local = $state();
  currentUser = $derived(this.remote.currentUser);
  logins = $derived(this.remote.logins.all);
  channels = $derived(this.remote.channels.all);
  messages = $derived(
    this.remote.messages.all.map((message) =>
      message.resolve({ sender: (id) => this.logins.get(id) })
    )
  );

  static boot({ login, logins, channels, messages, resume_point }) {
    const remote = r.State.boot({
      currentUser: login,
      logins,
      channels,
      messages,
      resumePoint: resume_point
    });
    const local = l.Channels.fromLocalStorage();
    return new Session(remote, local);
  }

  constructor(remote, local) {
    this.remote = remote;
    this.local = local;
  }

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

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

  onMessage(message) {
    const event = JSON.parse(message.data);
    this.remote.onEvent(event);
    this.local.retainChannels(this.remote.channels.all.keys());
  }
}

export async function boot() {
  const response = await api.boot();
  switch (response.status) {
    case 401:
      redirect(307, '/login');
      break;
    case 503:
      redirect(307, '/setup');
      break;
    case 200:
      return Session.boot(response.data);
  }
}