summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/app.js
blob: 1b284bb462f1f22541d8ea3d73be43db0603ca73 (plain) (blame)
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
/* MeshBay Web Client — Phase 4
 * Communicates with: Hub API (auth, groups) + Node HTTP API (files, streaming)
 * Requires: hub at same origin, node at configured URL
 */

const HUB = '';   // same origin — hub serves this file

// ── State ─────────────────────────────────────────────────────────────────────

let state = {
  token: localStorage.getItem('mb_token') || null,
  refreshToken: localStorage.getItem('mb_rt') || null,
  username: localStorage.getItem('mb_user') || null,
  nodeUrl: localStorage.getItem('mb_node') || null,
};

// ── Hub API helpers ───────────────────────────────────────────────────────────

async function hubGet(path) {
  const headers = state.token ? { Authorization: `Bearer ${state.token}` } : {};
  const r = await fetch(HUB + path, { headers });
  if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
  return r.json();
}

async function hubPost(path, body) {
  const headers = {
    'Content-Type': 'application/json',
    ...(state.token ? { Authorization: `Bearer ${state.token}` } : {}),
  };
  const r = await fetch(HUB + path, { method: 'POST', headers, body: JSON.stringify(body) });
  if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
  return r.json();
}

// ── Auth ──────────────────────────────────────────────────────────────────────

async function login(username, password) {
  const data = await hubPost('/v1/users/login', { username, password });
  state.token = data.access_token;
  state.refreshToken = data.refresh_token;
  state.username = username;
  localStorage.setItem('mb_token', state.token);
  localStorage.setItem('mb_rt', state.refreshToken);
  localStorage.setItem('mb_user', username);
  return data;
}

async function register(username, email, password, pkEd, pkX) {
  return hubPost('/v1/users/register', {
    username, email, password,
    pk_user_ed25519: pkEd,
    pk_user_x25519: pkX,
  });
}

function logout() {
  state = { token: null, refreshToken: null, username: null, nodeUrl: null };
  localStorage.clear();
  render();
}

// ── Node API helpers ──────────────────────────────────────────────────────────

async function nodeGet(path) {
  if (!state.nodeUrl) throw new Error('No node configured');
  const sep = path.includes('?') ? '&' : '?';
  const url = state.nodeUrl + path + (state.token ? `${sep}token=${state.token}` : '');
  const r = await fetch(url);
  if (!r.ok) throw new Error(`Node ${r.status}`);
  return r.json();
}

// ── Pages ─────────────────────────────────────────────────────────────────────

async function pageHome() {
  const groups = await hubGet('/v1/groups');
  const items = groups.groups.map(g => `
    <div class="card" onclick="pageGroup('${g.id}')">
      <b>${esc(g.name)}</b>
      <span class="badge">${g.join_policy}</span>
    </div>`).join('');

  return `
    <h2>Public Groups</h2>
    ${items || '<p>No public groups yet.</p>'}
    ${state.nodeUrl ? `
      <h2>My Node (<a href="${esc(state.nodeUrl)}" target="_blank">${esc(state.nodeUrl)}</a>)</h2>
      <button onclick="pageNodeBrowser()">Browse My Node</button>
    ` : `
      <h2>Connect to a Node</h2>
      <input id="nodeUrl" placeholder="http://node-ip:19001" style="width:300px">
      <button onclick="connectNode()">Connect</button>
    `}`;
}

async function pageGroup(groupId) {
  // TODO: fetch group info + node from hub
  return `<p>Group ${groupId} — coming soon</p><button onclick="render()">Back</button>`;
}

async function pageNodeBrowser() {
  const data = await nodeGet('/index');
  const rows = data.entries.map(e => `
    <tr>
      <td>${esc(e.name)}</td>
      <td>${e.type}</td>
      <td>${fmtSize(e.size)}</td>
      <td>
        ${e.type === 'video' ? `<button onclick="streamVideo('${e.id}','${esc(e.name)}')">▶ Play</button>` : ''}
        <a href="${state.nodeUrl}/file/${e.id}" target="_blank">⬇ Download</a>
      </td>
    </tr>`).join('');

  return `
    <h2>📁 ${esc(data.group_name)}</h2>
    <p>${data.entries.length} files — index v${data.version}</p>
    <table>
      <thead><tr><th>Name</th><th>Type</th><th>Size</th><th>Actions</th></tr></thead>
      <tbody>${rows}</tbody>
    </table>
    <button onclick="render()">← Back</button>`;
}

function pageStream(fileId, name) {
  const src = `${state.nodeUrl}/hls/${fileId}/playlist.m3u8${state.token ? '?token=' + state.token : ''}`;
  return `
    <h2>▶ ${esc(name)}</h2>
    <video controls autoplay style="max-width:100%;width:800px">
      <source src="${esc(src)}" type="application/vnd.apple.mpegurl">
      Your browser does not support HLS. <a href="${state.nodeUrl}/file/${fileId}">Download instead</a>.
    </video>
    <br><button onclick="pageNodeBrowser().then(setMain)">← Back to files</button>`;
}

// ── Actions ───────────────────────────────────────────────────────────────────

async function connectNode() {
  const url = document.getElementById('nodeUrl')?.value?.trim();
  if (!url) return;
  state.nodeUrl = url;
  localStorage.setItem('mb_node', url);
  await pageNodeBrowser().then(setMain);
}

async function streamVideo(fileId, name) {
  setMain(pageStream(fileId, name));
}

async function doLogin() {
  const u = document.getElementById('lu').value;
  const p = document.getElementById('lp').value;
  try {
    await login(u, p);
    render();
  } catch(e) { alert('Login failed: ' + e.message); }
}

// ── Router / render ───────────────────────────────────────────────────────────

function setMain(html) {
  document.getElementById('main').innerHTML = html;
}

async function render() {
  const nav = document.getElementById('nav');
  if (state.username) {
    nav.innerHTML = `<b>MeshBay</b> | Logged in as <b>${esc(state.username)}</b>
      <button onclick="logout()" style="float:right">Logout</button>`;
    setMain('<p>Loading…</p>');
    setMain(await pageHome());
  } else {
    nav.innerHTML = '<b>MeshBay</b>';
    setMain(`
      <h2>Login</h2>
      <input id="lu" placeholder="Username" autocomplete="username">
      <input id="lp" type="password" placeholder="Password" autocomplete="current-password">
      <button onclick="doLogin()">Login</button>
      <p><small>No account? Register via the API for now.</small></p>`);
  }
}

// ── Utils ─────────────────────────────────────────────────────────────────────

function esc(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
                  .replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

function fmtSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024**2) return (bytes/1024).toFixed(1) + ' KB';
  if (bytes < 1024**3) return (bytes/1024**2).toFixed(1) + ' MB';
  return (bytes/1024**3).toFixed(2) + ' GB';
}

// ── Boot ──────────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', render);