// Where each person has got to in each thing they listen to (audiobooks, podcast episodes), kept on the server so every device agrees. // One file per person; for each item the newest report wins, so an old device cannot overwrite a newer position. const fs = require('fs'), path = require('path'); const users = require('./users'); module.exports = name => { const file = () => path.join(users.dir(), name); const load = () => { try { return JSON.parse(fs.readFileSync(file(), 'utf8')); } catch { return {}; } }; const merge = body => { const mine = load(); for (const [k, v] of Object.entries(body || {})) if (/^[\w.:-]{1,80}$/.test(k) && v && typeof v === 'object' && (v.t || 0) >= ((mine[k] || {}).t || 0)) mine[k] = { pos: +v.pos || 0, dur: +v.dur || 0, t: +v.t || 0 }; const f = file(), tmp = f + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(mine), { mode: 0o600 }); fs.renameSync(tmp, f); return mine; }; return { load, merge }; };