File size: 2,876 Bytes
cc9c0d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'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 };