Claude / server /background.js
Cnass's picture
Claude Sonnet 5.5
Gemini oturum kaybı düzeltmesi, Gemini token sayımı ve bağlam çubuğu, kullanıcı kuralları/skill primer, sohbet arka planı
cc9c0d7
Raw History Blame Contribute Delete
2.88 kB
'use strict';
// The chat background picture the user chose (one image, kept in
// ~/.cc-web/background). The page downsizes it before uploading; the server
// still checks that the bytes really are a picture.
const fs = require('fs');
const path = require('path');
const { pipeline } = require('stream/promises');
const { Transform } = require('stream');
const MAX_UPLOAD = 12 * 1024 * 1024;
const TYPES = { png: 'image/png', jpg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif' };
function httpError(status, message) {
const err = new Error(message);
err.status = status;
return err;
}
function sniff(head) {
if (head.length >= 8 && head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpg';
if (head.length >= 12 && head.toString('ascii', 0, 4) === 'RIFF' && head.toString('ascii', 8, 12) === 'WEBP') return 'webp';
if (head.length >= 6 && /^GIF8[79]a$/.test(head.toString('ascii', 0, 6))) return 'gif';
return null;
}
class Background {
constructor({ home }) {
this.dir = path.join(home, '.cc-web', 'background');
}
// { file, type, ver } of the stored picture, or null.
current() {
for (const ext of Object.keys(TYPES)) {
const file = path.join(this.dir, `bg.${ext}`);
try {
const st = fs.statSync(file);
return { file, type: TYPES[ext], ver: Math.round(st.mtimeMs), size: st.size };
} catch {
// yok
}
}
return null;
}
async upload(req) {
const declared = Number(req.headers['content-length']);
if (declared > MAX_UPLOAD) throw httpError(413, 'Görsel çok büyük (en fazla 12 MB).');
fs.mkdirSync(this.dir, { recursive: true });
const tmp = path.join(this.dir, 'upload.part');
let size = 0;
let head = Buffer.alloc(0);
const meter = new Transform({
transform(chunk, _e, cb) {
size += chunk.length;
if (head.length < 16) head = Buffer.concat([head, chunk.subarray(0, 16 - head.length)]);
if (size > MAX_UPLOAD) cb(httpError(413, 'Görsel çok büyük (en fazla 12 MB).'));
else cb(null, chunk);
},
});
try {
await pipeline(req, meter, fs.createWriteStream(tmp));
} catch (err) {
fs.rmSync(tmp, { force: true });
throw err.status ? err : httpError(400, 'Yükleme yarıda kesildi.');
}
const ext = sniff(head);
if (!ext) {
fs.rmSync(tmp, { force: true });
throw httpError(400, 'Bu bir PNG, JPEG, WebP ya da GIF görseli değil.');
}
this.clear();
fs.renameSync(tmp, path.join(this.dir, `bg.${ext}`));
return this.current();
}
clear() {
for (const ext of Object.keys(TYPES)) fs.rmSync(path.join(this.dir, `bg.${ext}`), { force: true });
}
}
module.exports = { Background };