'use strict'; const conf = require('>/conf'); const organize = require('>/controller/organize'); let lock = false; // Poll unorganized Movie/TV downloads; when Transmission reports one finished, file it. async function tick(){ if(lock) return; lock = true; try{ const { Torrent } = require('>/models'); let where = { organizedAt: null, category: ['Movie', 'TV'] }; if(!conf.organize.includePrivate) where.isPrivate = false; let pending = await Torrent.findAll({ where }); if(!pending.length) return; let byHash = {}; for(let t of pending) byHash[t.hashString.toLowerCase()] = t; let res = await Torrent.trClient.get(pending.map(t => t.hashString), ['hashString', 'percentDone', 'isFinished']); for(let tor of res.torrents){ if(!(tor.isFinished || tor.percentDone === 1)) continue; let t = byHash[String(tor.hashString).toLowerCase()]; if(!t) continue; if(t.metadata && t.metadata.organizeError) continue; // already tried; needs manual fix await organize.fileTorrent(t); } }catch(error){ // Transmission down / transient — just try again next tick. console.error('organizeWatcher tick failed:', error.name, error.message); if(error.stack) console.error(error.stack); }finally{ lock = false; } } setInterval(tick, conf.organize.interval || 10000); tick(); // reconcile once on boot module.exports = { tick };