sharerare 0.1.1 → 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
@@ -10,12 +10,14 @@ import os from 'node:os';
10
10
  import path from 'node:path';
11
11
  import { Readable } from 'node:stream';
12
12
  import { pipeline } from 'node:stream/promises';
13
+ import readline from 'node:readline';
13
14
  import { parseArgs } from 'node:util';
14
15
  import { RTCPeerConnection } from 'node-datachannel/polyfill';
15
16
  import { filterSdp, fmtSize, freePath, isAllowedCandidate, looksBinary, safeName, typeOf } from './lan.js';
17
+ import { buildRows, initialState, press, render, selectedEntries, withRows } from './picker.js';
16
18
 
17
19
  globalThis.RTCPeerConnection = RTCPeerConnection;
18
- const { Mesh, isCode, randomCode, randomId } = await import('../public/js/mesh.js');
20
+ const { Mesh, cleanDir, isCode, randomCode, randomId } = await import('../public/js/mesh.js');
19
21
  const { buildZip, cleanSegment, crc32, uniquePath } = await import('../public/js/zip.js');
20
22
  const { renderUnicodeCompact } = await import('../public/vendor/uqr.js');
21
23
 
@@ -24,9 +26,10 @@ const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.met
24
26
  const HELP = `Sharerare: send files between devices on the same network.
25
27
 
26
28
  Usage
27
- sharerare send <file...> Share files until you press Ctrl+C
29
+ sharerare send <file|folder...> Share files or whole folders until Ctrl+C
28
30
  sharerare note <text...> Share a note or a link (or pipe text in)
29
31
  sharerare ls List nearby devices and what they share
32
+ sharerare get Pick what to download from a list
30
33
  sharerare get <name...> Download files by name (or part of it)
31
34
  sharerare get --all [--zip] Download everything, optionally as one .zip
32
35
  sharerare cat <name> Print a shared file or note to the terminal
@@ -232,12 +235,13 @@ function pick(list, queries) {
232
235
  const picked = [];
233
236
  for (const query of queries) {
234
237
  const q = query.toLowerCase();
235
- const exact = list.filter(({ item }) => item.name === query || item.id === query);
236
- 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));
237
241
  if (!loose.length) { err(`No shared file matches "${query}". Run "sharerare ls" to see what is shared.`); stop(1); return null; }
238
242
  if (loose.length > 1) {
239
243
  err(`"${query}" matches ${loose.length} files. Be more specific, or add --from <device>:`);
240
- 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)})`);
241
245
  stop(2);
242
246
  return null;
243
247
  }
@@ -271,11 +275,11 @@ async function ls() {
271
275
  }
272
276
  if (list.length) {
273
277
  // Notes are shown as written (links keep their slashes); file names are cleaned.
274
- const label = (item) => (item.kind === 'text' ? item.text.split('\n')[0].replace(/[\u0000-\u001f\u007f]/g, '') : safeName(item.name));
275
- 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)));
276
280
  out('\nShared');
277
281
  for (const { peer, item } of list) {
278
- 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)}`);
279
283
  }
280
284
  }
281
285
  stop(peers.some((p) => p.state === 'connected') || !peers.length ? 0 : 1);
@@ -330,14 +334,69 @@ function fileSink(target) {
330
334
  return sink;
331
335
  }
332
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
+
333
391
  async function get() {
334
- 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);
335
393
  const dir = path.resolve(opt.out || '.');
336
394
  if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) fail(`${dir} is not a folder`, 2);
337
395
  const list = await nearby();
338
396
  if (!list) return;
339
- const wanted = opt.all ? list : pick(list, rest);
397
+ const wanted = opt.all ? list : rest.length ? pick(list, rest) : await choose();
340
398
  if (!wanted) return;
399
+ if (!wanted.length) { err('Nothing selected.'); return stop(0); }
341
400
  if (zipName !== null) return getZip(wanted, dir);
342
401
 
343
402
  let failed = 0;
@@ -346,7 +405,7 @@ async function get() {
346
405
  out(item.text ?? '');
347
406
  continue;
348
407
  }
349
- const target = freePath(dir, safeName(item.name), fs.existsSync);
408
+ const target = freePath(folderFor(dir, item), safeName(item.name), fs.existsSync);
350
409
  let sink;
351
410
  try { sink = fileSink(target); } catch (e) { failed++; err(`✗ can't write ${target}: ${e.code || e.message}`); continue; }
352
411
  const result = await receive(peer, item, sink);
@@ -378,7 +437,7 @@ async function getZip(wanted, dir) {
378
437
  const result = await receive(peer, item, sink);
379
438
  if (!result.ok) { failed++; err(`✗ ${safeName(item.name)}: ${result.error}`); continue; }
380
439
  entries.push({
381
- 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),
382
441
  blob: await fs.openAsBlob(file),
383
442
  crc: sink.crc,
384
443
  size: result.size,
@@ -483,7 +542,8 @@ async function share() {
483
542
  mesh.addEventListener('upload', (e) => {
484
543
  const u = e.detail;
485
544
  if (!u) return;
486
- 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';
487
547
  const who = peerName(mesh.peers.get(u.peerId));
488
548
  if (!seen.has(u)) { seen.set(u, 'started'); logLink(`→ ${who} is ${u.preview ? 'previewing' : 'downloading'} ${name}`); }
489
549
  if (!mesh.uploads.has(u) && seen.get(u) !== 'ended') {
@@ -502,7 +562,10 @@ async function share() {
502
562
  logLink = (text) => report.push(text); // hold until the header is out, so the log reads in order
503
563
  await start();
504
564
  const items = [...shelf.values()].map((x) => x.meta);
505
- 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)})`;
506
569
  err(`Sharing ${what} as "${myName}"${opt.hidden ? ' (hidden from the network)' : where()}.`);
507
570
  if (myCode) showPairing();
508
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.');
@@ -511,21 +574,56 @@ async function share() {
511
574
  for (const line of report) realLog(line);
512
575
  }
513
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
+
514
597
  async function send() {
515
- if (!rest.length) fail('say which files to share: sharerare send <file...>', 2);
516
- 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) {
517
602
  let stat;
518
- try { stat = fs.statSync(file); } catch { fail(`${file}: no such file`, 2); }
519
- 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()) {
520
614
  const id = randomId(16);
521
615
  const name = path.basename(file);
616
+ const size = fs.statSync(file).size;
522
617
  shelf.set(id, {
523
618
  blob: await fs.openAsBlob(file),
524
- 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 },
525
621
  });
526
622
  }
623
+ sharedFolders = folders;
527
624
  await share();
528
625
  }
626
+ let sharedFolders = [];
529
627
 
530
628
  async function readStdin() {
531
629
  const chunks = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sharerare",
3
- "version": "0.1.1",
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',