sharerare 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,15 +14,21 @@ Requires Node.js 22 or newer. Prebuilt for macOS, Linux and Windows (x64 and ARM
14
14
 
15
15
  ```bash
16
16
  sharerare send report.pdf photos.zip # share until Ctrl+C
17
+ sharerare send ~/Pictures/Holiday # a whole folder, with its subfolders
17
18
  sharerare note "https://example.com" # share a note or a link
18
19
  echo "build 4512 is green" | sharerare note
19
20
  sharerare ls # devices nearby and what they share
21
+ sharerare get # pick from a list (arrow keys, space, Enter)
20
22
  sharerare get report.pdf # download by name, or part of a name
21
23
  sharerare get --all --from iPhone -o ~/Downloads
22
24
  sharerare get --all --zip # everything as one .zip
23
25
  sharerare cat notes.md # print a shared text file or note
24
26
  ```
25
27
 
28
+ A bare `get` opens a list of everything shared nearby, grouped by device and folder. Use `↑` `↓` to move, `Space` to tick a file or a whole folder, `a` for everything, `/` to filter, `Enter` to download and `q` to quit. With nothing ticked, `Enter` takes the highlighted row.
29
+
30
+ Shared folders keep their structure: `get` recreates the same folders under the output folder, and `--zip` keeps them inside the archive. Hidden files (names starting with a dot) are left out, and one run shares at most 500 files.
31
+
26
32
  `get` writes each file as `name.part` and renames it when it is complete. An existing file is never overwritten: a second `report.pdf` is saved as `report (1).pdf`.
27
33
 
28
34
  `cat` prints to the terminal and refuses binary files there; redirect it instead (`sharerare cat photo.jpg > photo.jpg`), or use `get`.
package/cli/picker.js ADDED
@@ -0,0 +1,160 @@
1
+ // The interactive list behind a bare `sharerare get`: pick files (or whole
2
+ // folders) with the keyboard. Pure state and rendering, so it can be tested
3
+ // without a terminal; cli/sharerare.js wires it to the keyboard.
4
+
5
+ import { fmtSize } from './lan.js';
6
+
7
+ const keyOf = (entry) => `${entry.peer.id}:${entry.item.id}`;
8
+ const pathOf = (item) => (item.dir ? `${item.dir}/${item.name}` : item.name);
9
+
10
+ // Rows: a header per device (when there are several), a header per folder,
11
+ // then the files. A header selects everything under it.
12
+ export function buildRows(entries, nameOf) {
13
+ const files = entries.filter((e) => e.item.kind !== 'text');
14
+ const devices = [...new Set(files.map((e) => e.peer.id))];
15
+ const rows = [];
16
+ for (const id of devices) {
17
+ const mine = files.filter((e) => e.peer.id === id)
18
+ .sort((a, b) => (a.item.dir || '').localeCompare(b.item.dir || '') || a.item.name.localeCompare(b.item.name));
19
+ if (devices.length > 1) rows.push({ type: 'device', label: nameOf(mine[0].peer), keys: mine.map(keyOf), depth: 0 });
20
+ const base = devices.length > 1 ? 1 : 0;
21
+ const shown = new Set(); // folders that already have a header
22
+ for (const e of mine) {
23
+ const parts = (e.item.dir || '').split('/').filter(Boolean);
24
+ // A header for each folder on the way down, nested under its parent.
25
+ parts.forEach((part, i) => {
26
+ const dir = parts.slice(0, i + 1).join('/');
27
+ if (shown.has(dir)) return;
28
+ shown.add(dir);
29
+ const under = mine.filter((x) => x.item.dir === dir || (x.item.dir || '').startsWith(`${dir}/`));
30
+ rows.push({ type: 'folder', label: `${part}/`, dir, keys: under.map(keyOf), depth: base + i });
31
+ });
32
+ rows.push({ type: 'file', key: keyOf(e), entry: e, label: e.item.name, path: pathOf(e.item), size: e.item.size, depth: base + parts.length });
33
+ }
34
+ }
35
+ return rows;
36
+ }
37
+
38
+ export function initialState(rows) {
39
+ return { rows, cursor: 0, top: 0, selected: new Set(), filter: '', filtering: false };
40
+ }
41
+
42
+ // Keeps the cursor and the selection when the list changes underneath (a
43
+ // device adds or removes files while the picker is open).
44
+ export function withRows(state, rows) {
45
+ const keys = new Set(rows.filter((r) => r.type === 'file').map((r) => r.key));
46
+ const selected = new Set([...state.selected].filter((k) => keys.has(k)));
47
+ const next = { ...state, rows, selected };
48
+ return { ...next, cursor: Math.min(state.cursor, Math.max(0, visible(next).length - 1)) };
49
+ }
50
+
51
+ export function visible(state) {
52
+ const q = state.filter.toLowerCase();
53
+ if (!q) return state.rows;
54
+ const hits = new Set(state.rows.filter((r) => r.type === 'file' && `${r.path}\n${r.entry.peer.hello?.name || ''}`.toLowerCase().includes(q)).map((r) => r.key));
55
+ return state.rows.filter((r) => (r.type === 'file' ? hits.has(r.key) : r.keys.some((k) => hits.has(k))));
56
+ }
57
+
58
+ export function selectedEntries(state) {
59
+ return state.rows.filter((r) => r.type === 'file' && state.selected.has(r.key)).map((r) => r.entry);
60
+ }
61
+
62
+ // key: 'up' | 'down' | 'pageup' | 'pagedown' | 'home' | 'end' | 'space' |
63
+ // 'enter' | 'escape' | 'backspace' | 'quit' | a single printable character.
64
+ // Returns { state, action } where action is null, 'download' or 'quit'.
65
+ export function press(state, key, page = 10) {
66
+ const rows = visible(state);
67
+ const move = (to) => ({ state: { ...state, cursor: Math.max(0, Math.min(rows.length - 1, to)) }, action: null });
68
+
69
+ if (state.filtering) {
70
+ if (key === 'enter' || key === 'down') return { state: { ...state, filtering: false, cursor: 0 }, action: null };
71
+ if (key === 'escape') return { state: { ...state, filtering: false, filter: '', cursor: 0 }, action: null };
72
+ if (key === 'backspace') return { state: { ...state, filter: state.filter.slice(0, -1), cursor: 0 }, action: null };
73
+ if (key === 'quit') return { state, action: 'quit' };
74
+ if (key === 'space') return { state: { ...state, filter: `${state.filter} `, cursor: 0 }, action: null };
75
+ if (key.length === 1) return { state: { ...state, filter: state.filter + key, cursor: 0 }, action: null };
76
+ return { state, action: null };
77
+ }
78
+
79
+ switch (key) {
80
+ case 'up': case 'k': return move(state.cursor - 1);
81
+ case 'down': case 'j': return move(state.cursor + 1);
82
+ case 'pageup': return move(state.cursor - page);
83
+ case 'pagedown': return move(state.cursor + page);
84
+ case 'home': case 'g': return move(0);
85
+ case 'end': case 'G': return move(rows.length - 1);
86
+ case '/': return { state: { ...state, filtering: true }, action: null };
87
+ case 'escape':
88
+ if (state.filter) return { state: { ...state, filter: '', cursor: 0 }, action: null };
89
+ return { state, action: 'quit' };
90
+ case 'q': case 'quit': return { state, action: 'quit' };
91
+ case 'space': {
92
+ const row = rows[state.cursor];
93
+ if (!row) return { state, action: null };
94
+ const keys = row.type === 'file' ? [row.key] : row.keys;
95
+ const selected = new Set(state.selected);
96
+ const on = !keys.every((k) => selected.has(k));
97
+ for (const k of keys) (on ? selected.add(k) : selected.delete(k));
98
+ // Move on after ticking a file, like most list pickers.
99
+ return { state: { ...state, selected, cursor: row.type === 'file' ? Math.min(rows.length - 1, state.cursor + 1) : state.cursor }, action: null };
100
+ }
101
+ case 'a': {
102
+ // Everything shown (respecting the filter), or nothing if it already is.
103
+ const keys = rows.filter((r) => r.type === 'file').map((r) => r.key);
104
+ const selected = new Set(state.selected);
105
+ const on = !keys.every((k) => selected.has(k));
106
+ for (const k of keys) (on ? selected.add(k) : selected.delete(k));
107
+ return { state: { ...state, selected }, action: null };
108
+ }
109
+ case 'enter': {
110
+ // Nothing ticked: Enter takes what is under the cursor.
111
+ if (!state.selected.size) {
112
+ const row = rows[state.cursor];
113
+ if (!row) return { state, action: null };
114
+ const selected = new Set(row.type === 'file' ? [row.key] : row.keys);
115
+ return { state: { ...state, selected }, action: 'download' };
116
+ }
117
+ return { state, action: 'download' };
118
+ }
119
+ default: return { state, action: null };
120
+ }
121
+ }
122
+
123
+ const fit = (text, width) => (text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text.padEnd(width));
124
+
125
+ // The whole screen as text. `height` and `width` are the terminal's size.
126
+ export function render(state, { height = 24, width = 80, title = '' } = {}) {
127
+ const rows = visible(state);
128
+ const bodyHeight = Math.max(3, height - 5);
129
+ let top = state.top;
130
+ if (state.cursor < top) top = state.cursor;
131
+ if (state.cursor >= top + bodyHeight) top = state.cursor - bodyHeight + 1;
132
+ top = Math.max(0, Math.min(top, Math.max(0, rows.length - bodyHeight)));
133
+ state.top = top; // remembered for the next frame
134
+
135
+ const lines = [];
136
+ lines.push(fit(title || 'Choose what to download', width));
137
+ lines.push(fit(state.filtering ? `Filter: ${state.filter}█` : state.filter ? `Filter: ${state.filter} (Esc clears)` : '', width));
138
+ for (let i = top; i < Math.min(rows.length, top + bodyHeight); i++) {
139
+ const row = rows[i];
140
+ const here = i === state.cursor ? '›' : ' ';
141
+ const keys = row.type === 'file' ? [row.key] : row.keys;
142
+ const count = keys.filter((k) => state.selected.has(k)).length;
143
+ const box = count === 0 ? '[ ]' : count === keys.length ? '[x]' : '[-]';
144
+ const indent = ' '.repeat(row.depth);
145
+ if (row.type === 'file') {
146
+ const size = fmtSize(row.size).padStart(9);
147
+ lines.push(fit(`${here} ${box} ${indent}${fit(row.label, Math.max(8, width - 18 - indent.length))}${size}`, width));
148
+ } else {
149
+ const total = row.keys.length;
150
+ lines.push(fit(`${here} ${box} ${indent}${row.type === 'device' ? '● ' : ''}${row.label} (${total} file${total === 1 ? '' : 's'})`, width));
151
+ }
152
+ }
153
+ if (!rows.length) lines.push(fit(state.filter ? ' Nothing matches the filter.' : ' Nothing is shared right now. Waiting…', width));
154
+ while (lines.length < height - 2) lines.push(''.padEnd(width));
155
+ const chosen = selectedEntries(state);
156
+ const bytes = chosen.reduce((n, e) => n + (e.item.size || 0), 0);
157
+ lines.push(fit(chosen.length ? `${chosen.length} selected · ${fmtSize(bytes)}` : 'Nothing selected: Enter takes the highlighted row', width));
158
+ lines.push(fit('↑↓ move · space select · a all · / filter · enter download · q quit', width));
159
+ return lines.join('\n');
160
+ }
package/cli/sharerare.js CHANGED
@@ -4,17 +4,20 @@
4
4
  // public/js/mesh.js), so files travel directly between devices. Nothing is
5
5
  // uploaded.
6
6
 
7
+ import { execFileSync } from 'node:child_process';
7
8
  import fs from 'node:fs';
8
9
  import os from 'node:os';
9
10
  import path from 'node:path';
10
11
  import { Readable } from 'node:stream';
11
12
  import { pipeline } from 'node:stream/promises';
13
+ import readline from 'node:readline';
12
14
  import { parseArgs } from 'node:util';
13
15
  import { RTCPeerConnection } from 'node-datachannel/polyfill';
14
16
  import { filterSdp, fmtSize, freePath, isAllowedCandidate, looksBinary, safeName, typeOf } from './lan.js';
17
+ import { buildRows, initialState, press, render, selectedEntries, withRows } from './picker.js';
15
18
 
16
19
  globalThis.RTCPeerConnection = RTCPeerConnection;
17
- const { Mesh, isCode, randomCode, randomId } = await import('../public/js/mesh.js');
20
+ const { Mesh, cleanDir, isCode, randomCode, randomId } = await import('../public/js/mesh.js');
18
21
  const { buildZip, cleanSegment, crc32, uniquePath } = await import('../public/js/zip.js');
19
22
  const { renderUnicodeCompact } = await import('../public/vendor/uqr.js');
20
23
 
@@ -23,9 +26,10 @@ const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.met
23
26
  const HELP = `Sharerare: send files between devices on the same network.
24
27
 
25
28
  Usage
26
- sharerare send <file...> Share files until you press Ctrl+C
29
+ sharerare send <file|folder...> Share files or whole folders until Ctrl+C
27
30
  sharerare note <text...> Share a note or a link (or pipe text in)
28
31
  sharerare ls List nearby devices and what they share
32
+ sharerare get Pick what to download from a list
29
33
  sharerare get <name...> Download files by name (or part of it)
30
34
  sharerare get --all [--zip] Download everything, optionally as one .zip
31
35
  sharerare cat <name> Print a shared file or note to the terminal
@@ -132,7 +136,22 @@ if (opt.pair && !['send', 'note'].includes(command)) fail('--pair works with sen
132
136
  if (opt.hidden && !code && !opt.pair) fail('--hidden needs --code or --pair, otherwise no device could find this one.', 2);
133
137
  if (zipName !== null && command !== 'get') fail('--zip works with get.', 2);
134
138
  const waitMs = Math.max(2, Number(opt.wait) || 15) * 1000;
135
- const myName = (opt.name || os.hostname().replace(/\.local$/, '') || 'Terminal').slice(0, 40);
139
+ const myName = (opt.name || defaultName()).slice(0, 40);
140
+
141
+ // The name people know this computer by, plus "Terminal" so it can be told
142
+ // apart from a browser tab on the same machine. The host name alone can be an
143
+ // IP address (macOS sets it from the network when none is configured).
144
+ function defaultName() {
145
+ let name = '';
146
+ try {
147
+ if (process.platform === 'darwin') name = execFileSync('scutil', ['--get', 'ComputerName'], { encoding: 'utf8', timeout: 1500, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
148
+ else if (process.platform === 'win32') name = process.env.COMPUTERNAME || '';
149
+ } catch {}
150
+ if (!name) name = os.hostname().replace(/\.(local|lan|home)$/i, '');
151
+ const looksLikeAddress = /^[\d.]+$|^[0-9a-f:]+$/i.test(name) || /^localhost$/i.test(name);
152
+ if (!name || looksLikeAddress) name = { darwin: 'Mac', win32: 'Windows PC', linux: 'Linux' }[process.platform] || 'Computer';
153
+ return `${name.slice(0, 28)} · Terminal`;
154
+ }
136
155
  const myCode = opt.pair ? randomCode() : null;
137
156
 
138
157
  // ---------- the mesh ----------
@@ -216,12 +235,13 @@ function pick(list, queries) {
216
235
  const picked = [];
217
236
  for (const query of queries) {
218
237
  const q = query.toLowerCase();
219
- const exact = list.filter(({ item }) => item.name === query || item.id === query);
220
- const loose = exact.length ? exact : list.filter(({ item }) => item.name.toLowerCase().includes(q) || (item.text || '').toLowerCase().includes(q));
238
+ const full = (item) => (item.dir ? `${item.dir}/${item.name}` : item.name);
239
+ const exact = list.filter(({ item }) => item.name === query || full(item) === query || item.id === query);
240
+ const loose = exact.length ? exact : list.filter(({ item }) => full(item).toLowerCase().includes(q) || (item.text || '').toLowerCase().includes(q));
221
241
  if (!loose.length) { err(`No shared file matches "${query}". Run "sharerare ls" to see what is shared.`); stop(1); return null; }
222
242
  if (loose.length > 1) {
223
243
  err(`"${query}" matches ${loose.length} files. Be more specific, or add --from <device>:`);
224
- for (const { peer, item } of loose) err(` ${safeName(item.name)} (${peerName(peer)})`);
244
+ for (const { peer, item } of loose) err(` ${item.dir ? `${item.dir}/` : ''}${safeName(item.name)} (${peerName(peer)})`);
225
245
  stop(2);
226
246
  return null;
227
247
  }
@@ -255,11 +275,11 @@ async function ls() {
255
275
  }
256
276
  if (list.length) {
257
277
  // Notes are shown as written (links keep their slashes); file names are cleaned.
258
- const label = (item) => (item.kind === 'text' ? item.text.split('\n')[0].replace(/[\u0000-\u001f\u007f]/g, '') : safeName(item.name));
259
- const width = Math.min(48, Math.max(...list.map(({ item }) => label(item).length)));
278
+ const label = (item) => (item.kind === 'text' ? item.text.split('\n')[0].replace(/[\u0000-\u001f\u007f]/g, '') : `${item.dir ? `${item.dir}/` : ''}${safeName(item.name)}`);
279
+ const width = Math.min(60, Math.max(...list.map(({ item }) => label(item).length)));
260
280
  out('\nShared');
261
281
  for (const { peer, item } of list) {
262
- out(` ${label(item).slice(0, 48).padEnd(width)} ${(item.kind === 'text' ? 'note' : fmtSize(item.size)).padStart(8)} ${peerName(peer)}`);
282
+ out(` ${label(item).slice(0, 60).padEnd(width)} ${(item.kind === 'text' ? 'note' : fmtSize(item.size)).padStart(8)} ${peerName(peer)}`);
263
283
  }
264
284
  }
265
285
  stop(peers.some((p) => p.state === 'connected') || !peers.length ? 0 : 1);
@@ -314,14 +334,69 @@ function fileSink(target) {
314
334
  return sink;
315
335
  }
316
336
 
337
+ // A bare `get` in a terminal: a list to pick from. The list stays live: files
338
+ // that devices add or remove while it is open come and go.
339
+ function choose() {
340
+ return new Promise((resolve) => {
341
+ const title = () => `Shared nearby${where()}`;
342
+ const rowsNow = () => buildRows(entries([...mesh.peers.values()]), peerName);
343
+ let state = initialState(rowsNow());
344
+ const draw = () => process.stderr.write(`\x1b[H\x1b[2J${render(state, { height: process.stderr.rows || 24, width: process.stderr.columns || 80, title: title() })}`);
345
+ const onShelf = () => { state = withRows(state, rowsNow()); draw(); };
346
+ const names = { up: 'up', down: 'down', pageup: 'pageup', pagedown: 'pagedown', home: 'home', end: 'end', space: 'space', return: 'enter', enter: 'enter', escape: 'escape', backspace: 'backspace' };
347
+ const onKey = (text, key = {}) => {
348
+ if (key.ctrl && key.name === 'c') return finish(null);
349
+ const name = names[key.name] || (text && text.length === 1 && text >= ' ' ? text : null);
350
+ if (!name) return;
351
+ const result = press(state, name, Math.max(3, (process.stderr.rows || 24) - 6));
352
+ state = result.state;
353
+ if (result.action === 'quit') return finish([]);
354
+ if (result.action === 'download') return finish(selectedEntries(state));
355
+ draw();
356
+ };
357
+ function finish(chosen) {
358
+ process.stdin.off('keypress', onKey);
359
+ process.stderr.off('resize', draw);
360
+ mesh.removeEventListener('shelf', onShelf);
361
+ mesh.removeEventListener('peers', onShelf);
362
+ process.stdin.setRawMode(false);
363
+ process.stdin.pause();
364
+ process.stderr.write('\x1b[?25h\x1b[?1049l'); // cursor back, leave the full-screen view
365
+ if (chosen === null) { stop(130); return resolve(null); }
366
+ resolve(chosen);
367
+ }
368
+ readline.emitKeypressEvents(process.stdin);
369
+ process.stdin.setRawMode(true);
370
+ process.stdin.resume();
371
+ process.stdin.on('keypress', onKey);
372
+ process.stderr.on('resize', draw);
373
+ mesh.addEventListener('shelf', onShelf);
374
+ mesh.addEventListener('peers', onShelf);
375
+ process.stderr.write('\x1b[?1049h\x1b[?25l'); // full-screen view, hide the cursor
376
+ draw();
377
+ });
378
+ }
379
+
380
+ // Where a file from a shared folder goes: the same folders under `dir`.
381
+ function folderFor(dir, item) {
382
+ const parts = cleanDir(item.dir).split('/').filter(Boolean).map(safeName);
383
+ const target = path.join(dir, ...parts);
384
+ if (target !== dir && !target.startsWith(dir + path.sep)) return dir; // never outside
385
+ fs.mkdirSync(target, { recursive: true });
386
+ return target;
387
+ }
388
+
389
+ const interactive = () => process.stdin.isTTY && process.stderr.isTTY;
390
+
317
391
  async function get() {
318
- if (!opt.all && !rest.length) fail('say which file, or use --all. Run "sharerare ls" to see what is shared.', 2);
392
+ if (!opt.all && !rest.length && !interactive()) fail('say which file, or use --all. Run "sharerare ls" to see what is shared.', 2);
319
393
  const dir = path.resolve(opt.out || '.');
320
394
  if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) fail(`${dir} is not a folder`, 2);
321
395
  const list = await nearby();
322
396
  if (!list) return;
323
- const wanted = opt.all ? list : pick(list, rest);
397
+ const wanted = opt.all ? list : rest.length ? pick(list, rest) : await choose();
324
398
  if (!wanted) return;
399
+ if (!wanted.length) { err('Nothing selected.'); return stop(0); }
325
400
  if (zipName !== null) return getZip(wanted, dir);
326
401
 
327
402
  let failed = 0;
@@ -330,7 +405,7 @@ async function get() {
330
405
  out(item.text ?? '');
331
406
  continue;
332
407
  }
333
- const target = freePath(dir, safeName(item.name), fs.existsSync);
408
+ const target = freePath(folderFor(dir, item), safeName(item.name), fs.existsSync);
334
409
  let sink;
335
410
  try { sink = fileSink(target); } catch (e) { failed++; err(`✗ can't write ${target}: ${e.code || e.message}`); continue; }
336
411
  const result = await receive(peer, item, sink);
@@ -362,7 +437,7 @@ async function getZip(wanted, dir) {
362
437
  const result = await receive(peer, item, sink);
363
438
  if (!result.ok) { failed++; err(`✗ ${safeName(item.name)}: ${result.error}`); continue; }
364
439
  entries.push({
365
- path: uniquePath(`${devices.size > 1 ? `${cleanSegment(peerName(peer))}/` : ''}${cleanSegment(item.name)}`, used),
440
+ path: uniquePath(`${devices.size > 1 ? `${cleanSegment(peerName(peer))}/` : ''}${item.dir ? `${cleanDir(item.dir).split('/').map(cleanSegment).join('/')}/` : ''}${cleanSegment(item.name)}`, used),
366
441
  blob: await fs.openAsBlob(file),
367
442
  crc: sink.crc,
368
443
  size: result.size,
@@ -440,19 +515,26 @@ async function share() {
440
515
  // Listen before joining: on a fast local network a link can be up before
441
516
  // start() returns.
442
517
  const known = new Map(); // peer id -> last state we printed
518
+ const names = new Map(); // peer id -> name, kept for the "left" line
443
519
  mesh.addEventListener('peers', () => {
444
520
  for (const peer of mesh.peers.values()) {
445
521
  const state = peer.state === 'connected' && !peer.hello ? 'connecting' : peer.state;
446
522
  const shown = `${state}:${peer.route || ''}`;
447
523
  if (known.get(peer.id) === shown) continue;
448
524
  known.set(peer.id, shown);
449
- if (state === 'connected') logLink(`● ${peerName(peer)} linked${peer.route === 'internet' ? ' over the internet' : ''}`);
450
- else if (state === 'unreachable' && (peer.linked || mesh.paired(peer))) logLink(`○ found a device but can't link directly (different network?)`);
525
+ if (state === 'connected') {
526
+ names.set(peer.id, peerName(peer));
527
+ logLink(`● ${peerName(peer)} linked${peer.route === 'internet' ? ' over the internet' : ''}`);
528
+ } else if (state === 'unreachable' && (peer.linked || mesh.paired(peer))) {
529
+ logLink(`○ can't reach ${peer.hello ? peerName(peer) : 'a paired device'} directly right now (asleep, or on another network?)`);
530
+ }
451
531
  }
452
532
  for (const [id, shown] of known) {
453
533
  if (mesh.peers.has(id)) continue;
454
534
  known.delete(id);
455
- if (shown.startsWith('connected')) logLink('○ a device left');
535
+ // Phones drop the link whenever the browser goes to the background or
536
+ // the page is opened again; it comes back by itself.
537
+ if (shown.startsWith('connected')) logLink(`○ ${names.get(id) || 'a device'} left (closed, reloaded or in the background)`);
456
538
  }
457
539
  });
458
540
 
@@ -460,7 +542,8 @@ async function share() {
460
542
  mesh.addEventListener('upload', (e) => {
461
543
  const u = e.detail;
462
544
  if (!u) return;
463
- const name = shelf.get(u.itemId)?.meta.name ?? 'file';
545
+ const meta = shelf.get(u.itemId)?.meta;
546
+ const name = meta ? (meta.dir ? `${meta.dir}/${meta.name}` : meta.name) : 'file';
464
547
  const who = peerName(mesh.peers.get(u.peerId));
465
548
  if (!seen.has(u)) { seen.set(u, 'started'); logLink(`→ ${who} is ${u.preview ? 'previewing' : 'downloading'} ${name}`); }
466
549
  if (!mesh.uploads.has(u) && seen.get(u) !== 'ended') {
@@ -479,7 +562,10 @@ async function share() {
479
562
  logLink = (text) => report.push(text); // hold until the header is out, so the log reads in order
480
563
  await start();
481
564
  const items = [...shelf.values()].map((x) => x.meta);
482
- const what = items.length === 1 ? (items[0].kind === 'text' ? 'a note' : items[0].name) : `${items.length} files`;
565
+ const bytes = items.reduce((n, x) => n + (x.size || 0), 0);
566
+ const what = sharedFolders.length === 1 && items.every((x) => x.dir)
567
+ ? `the folder ${sharedFolders[0]} (${items.length} file${items.length === 1 ? '' : 's'}, ${fmtSize(bytes)})`
568
+ : items.length === 1 ? (items[0].kind === 'text' ? 'a note' : items[0].name) : `${items.length} files (${fmtSize(bytes)})`;
483
569
  err(`Sharing ${what} as "${myName}"${opt.hidden ? ' (hidden from the network)' : where()}.`);
484
570
  if (myCode) showPairing();
485
571
  else err(opt.hidden ? 'Paired devices can download it. Ctrl+C to stop.' : 'Open Sharerare on another device on this network to download. Ctrl+C to stop.');
@@ -488,21 +574,56 @@ async function share() {
488
574
  for (const line of report) realLog(line);
489
575
  }
490
576
 
577
+ // Browsers show up to 500 items per device, so that is the most one run shares.
578
+ const MAX_ITEMS = 500;
579
+
580
+ // Every file in a folder, with its folder relative to the shared folder's
581
+ // parent ("Holiday/day 2"). Hidden files and links are left out.
582
+ function walk(root) {
583
+ const base = path.dirname(path.resolve(root));
584
+ const found = [];
585
+ const visit = (folder) => {
586
+ for (const entry of fs.readdirSync(folder, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
587
+ if (entry.name.startsWith('.')) continue;
588
+ const full = path.join(folder, entry.name);
589
+ if (entry.isDirectory()) visit(full);
590
+ else if (entry.isFile()) found.push({ file: full, dir: path.relative(base, folder).split(path.sep).join('/') });
591
+ }
592
+ };
593
+ visit(path.resolve(root));
594
+ return found;
595
+ }
596
+
491
597
  async function send() {
492
- if (!rest.length) fail('say which files to share: sharerare send <file...>', 2);
493
- for (const file of rest) {
598
+ if (!rest.length) fail('say what to share: sharerare send <file or folder...>', 2);
599
+ const files = [];
600
+ const folders = [];
601
+ for (const target of rest) {
494
602
  let stat;
495
- try { stat = fs.statSync(file); } catch { fail(`${file}: no such file`, 2); }
496
- if (!stat.isFile()) fail(`${file} is not a file (folders can't be shared yet; zip it first)`, 2);
603
+ try { stat = fs.statSync(target); } catch { fail(`${target}: no such file or folder`, 2); }
604
+ if (stat.isDirectory()) {
605
+ folders.push(path.basename(path.resolve(target)));
606
+ files.push(...walk(target));
607
+ } else if (stat.isFile()) files.push({ file: target, dir: '' });
608
+ else fail(`${target} is not a file or a folder`, 2);
609
+ }
610
+ if (!files.length) fail('there are no files in that folder (hidden files are left out).', 2);
611
+ if (files.length > MAX_ITEMS) err(`That is ${files.length} files; sharing the first ${MAX_ITEMS}. Zip the rest, or share subfolders one at a time.`);
612
+ const addedAt = Date.now();
613
+ for (const [i, { file, dir }] of files.slice(0, MAX_ITEMS).entries()) {
497
614
  const id = randomId(16);
498
615
  const name = path.basename(file);
616
+ const size = fs.statSync(file).size;
499
617
  shelf.set(id, {
500
618
  blob: await fs.openAsBlob(file),
501
- meta: { id, name, size: stat.size, type: typeOf(name), kind: 'file', addedAt: Date.now() },
619
+ // Newest first in browsers: keep the folder's order by counting down.
620
+ meta: { id, name, dir: dir || undefined, size, type: typeOf(name), kind: 'file', addedAt: addedAt - i },
502
621
  });
503
622
  }
623
+ sharedFolders = folders;
504
624
  await share();
505
625
  }
626
+ let sharedFolders = [];
506
627
 
507
628
  async function readStdin() {
508
629
  const chunks = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sharerare",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Send files between devices on the same network, from the terminal. Direct, device to device: the files never touch a server. Works with the Sharerare web app.",
5
5
  "keywords": [
6
6
  "file-sharing",
@@ -20,6 +20,7 @@
20
20
  "files": [
21
21
  "cli/sharerare.js",
22
22
  "cli/lan.js",
23
+ "cli/picker.js",
23
24
  "public/js/mesh.js",
24
25
  "public/js/zip.js",
25
26
  "public/vendor/uqr.js",
package/public/js/mesh.js CHANGED
@@ -67,6 +67,18 @@ function isLocalAddress(address) {
67
67
  const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
68
68
  const num = (v) => (Number.isFinite(v) && v >= 0 ? v : 0);
69
69
 
70
+ // A file's folder inside a shared folder ("Holiday/day 2"). Untrusted: only
71
+ // plain segments survive, so it can never point outside where it is saved.
72
+ export function cleanDir(dir) {
73
+ if (typeof dir !== 'string') return '';
74
+ return dir.split(/[\\/]+/)
75
+ .map((part) => part.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 100))
76
+ .filter((part) => part && part !== '.' && part !== '..')
77
+ .slice(0, 16)
78
+ .join('/')
79
+ .slice(0, 300);
80
+ }
81
+
70
82
  // Everything a peer tells us is untrusted input.
71
83
  function cleanShelf(items) {
72
84
  if (!Array.isArray(items)) return [];
@@ -81,6 +93,7 @@ function cleanShelf(items) {
81
93
  out.push({
82
94
  id,
83
95
  name: str(raw.name, 255) || 'file',
96
+ dir: raw.kind === 'text' ? undefined : cleanDir(raw.dir) || undefined,
84
97
  size: num(raw.size),
85
98
  type: /^[\w.+-]+\/[\w.+-]+$/.test(raw.type) ? raw.type.slice(0, 100) : 'application/octet-stream',
86
99
  kind: raw.kind === 'text' ? 'text' : 'file',