constsource=db.prepare("SELECT id,user_id,base_url,token_encrypted FROM sources WHERE id=?").get(id)as{id: number;user_id: number;base_url: string;token_encrypted: string}|undefined;
if(!owner)thrownewError("Only the owner can change source status");constenabled=String(form.get("enabled"))==="1";
db.prepare("UPDATE sources SET is_enabled=?,disabled_at=CASE WHEN ? THEN NULL ELSE CURRENT_TIMESTAMP END,sync_status=CASE WHEN ? THEN 'pending' ELSE 'disabled' END WHERE id=?").run(enabled?1 : 0,enabled?1 : 0,enabled?1 : 0,id);
db.prepare("UPDATE sources SET sync_tags_json=?,sync_from=?,sync_to=?,sync_attachment_mode=? WHERE id=?").run(JSON.stringify(tags),from||null,to||null,attachmentMode,id);
if(!owner)thrownewError("Only the owner can change attachment storage");constmode=String(form.get("mode")||"remote");constquotaMiB=Number(form.get("quotaMiB")||100);
db.prepare("UPDATE sources SET attachment_storage_mode=?,attachment_cache_limit_bytes=?,attachment_cache_error=NULL WHERE id=?").run(mode,Math.round(quotaMiB*1024*1024),id);queuePull(id,"manual");
db.prepare("UPDATE sources SET name=?,last_connection_at=CURRENT_TIMESTAMP,last_connection_error=NULL,remote_display_name=?,remote_avatar_url=? WHERE id=?").run(name,name,avatarUrl,id);
}catch(connectionError){constmessage=connectionErrorinstanceofError?connectionError.message:"Connection failed";db.prepare("UPDATE sources SET last_connection_error=? WHERE id=?").run(message,id);throwconnectionError;}
if(owner)thrownewError("Transfer ownership or delete the source before leaving");
db.prepare("DELETE FROM source_members WHERE source_id=? AND user_id=?").run(id,user.id);
}elseif(action==="transfer"){
if(!owner)thrownewError("Only the owner can transfer ownership");constusername=String(form.get("username")||"").trim();
consttarget=db.prepare("SELECT u.id FROM users u JOIN source_members sm ON sm.user_id=u.id WHERE sm.source_id=? AND u.username=?").get(id,username)as{id: number}|undefined;
if(!target||target.id===user.id)thrownewError("Choose another existing member");
consttransfer=db.transaction(()=>{db.prepare("UPDATE sources SET user_id=? WHERE id=?").run(target.id,id);db.prepare("UPDATE source_members SET role='member' WHERE source_id=? AND user_id=?").run(id,user.id);db.prepare("UPDATE source_members SET role='owner' WHERE source_id=? AND user_id=?").run(id,target.id);});
transfer();
}elseif(action==="delete"){
if(!owner)thrownewError("Only the owner can delete a source");
constremove=db.transaction(()=>{db.prepare("DELETE FROM posts WHERE source_id=? AND origin='memos'").run(id);db.prepare("UPDATE posts SET source_id=NULL WHERE source_id=? AND origin='hub'").run(id);db.prepare("DELETE FROM sources WHERE id=?").run(id);});