File size: 11,695 Bytes
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51f94
f41aded
 
 
 
 
 
 
 
4a51f94
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51f94
 
f41aded
 
4a51f94
f41aded
 
 
4a51f94
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51f94
 
 
 
 
 
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import { randomUUID } from 'node:crypto';
import { Router } from 'express';
import { unzipSync, zipSync } from 'fflate';
import multer from 'multer';
import { SUPPORT_FILES } from './compile.js';
import { db, tx } from './db.js';
import { listFiles, maybeAutoSnapshot, nextRev, putFile, withProject } from './store.js';
import { getTemplate, templateList } from './templates.js';
import { HttpError, cleanPath, isTextPath, mimeOf, requireString } from './util.js';

const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 50 * 1024 * 1024, files: 30 } });
const utf8 = new TextDecoder('utf-8');
const decodeText = (bytes) => utf8.decode(bytes).replace(/^/, '');
// multer dosya adlarını latin1 olarak çözer; Türkçe karakterler için UTF-8'e çevrilir.
const originalName = (f) => Buffer.from(f.originalname, 'latin1').toString('utf8');

export function createProject(ownerId, title, files, mainFile) {
  const id = randomUUID();
  tx(() => {
    db.prepare('INSERT INTO projects (id, owner_id, title, main_file) VALUES (?, ?, ?, ?)').run(id, ownerId, title, mainFile);
    for (const [path, content] of Object.entries(files)) putFile(id, path, content, typeof content !== 'string');
  });
  return id;
}

export function pickMainFile(files) {
  const texFiles = Object.keys(files).filter((p) => p.endsWith('.tex'));
  const withClass = texFiles.filter((p) => typeof files[p] === 'string' && /\\documentclass/.test(files[p]));
  const candidates = withClass.length ? withClass : texFiles;
  return (
    candidates.find((p) => p === 'main.tex') ??
    candidates.sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b))[0] ??
    'main.tex'
  );
}

export const projectsRouter = Router();

projectsRouter.get('/templates', (_req, res) => res.json({ templates: templateList() }));

projectsRouter.get('/projects', (req, res) => {
  const projects = db.prepare(`
    SELECT p.id, p.title, p.updated_at AS updatedAt, u.name AS ownerName,
           CASE WHEN p.owner_id = :uid THEN 'owner' ELSE m.role END AS role
    FROM projects p
    JOIN users u ON u.id = p.owner_id
    LEFT JOIN project_members m ON m.project_id = p.id AND m.user_id = :uid
    WHERE p.owner_id = :uid OR m.user_id = :uid
    ORDER BY p.updated_at DESC
  `).all({ uid: req.user.id });
  res.json({ projects });
});

projectsRouter.post('/projects', (req, res) => {
  const title = requireString(req.body.title, 'Proje adı', { max: 120 });
  const template = getTemplate(req.body.templateId || 'bos');
  if (!template) throw new HttpError(400, 'Şablon bulunamadı.');
  res.json({ id: createProject(req.user.id, title, template.files, template.mainFile) });
});

/** Bir .zip arşivini proje dosyalarına çevirir (metinler string, diğerleri Buffer). */
export function filesFromZip(buffer) {
  let entries;
  try {
    entries = unzipSync(new Uint8Array(buffer));
  } catch {
    throw new HttpError(400, 'Dosya geçerli bir .zip arşivi değil.');
  }
  const names = Object.keys(entries).filter(
    (n) => !n.endsWith('/') && !n.startsWith('__MACOSX/') && !n.split('/').pop().startsWith('.DS_Store'),
  );
  if (!names.length) throw new HttpError(400, 'Arşivde dosya bulunamadı.');
  if (names.length > 1000) throw new HttpError(400, 'Arşivde çok fazla dosya var (en fazla 1000).');
  // Tüm dosyalar tek bir üst klasördeyse o klasör atılır.
  const top = names[0].split('/')[0];
  const strip = names.every((n) => n.startsWith(`${top}/`)) ? top.length + 1 : 0;
  const files = {};
  for (const name of names) {
    let path;
    try {
      path = cleanPath(name.slice(strip));
    } catch {
      continue; // geçersiz adlı girdiler atlanır
    }
    files[path] = isTextPath(path) ? decodeText(entries[name]) : Buffer.from(entries[name]);
  }
  return files;
}

projectsRouter.post('/projects/import', upload.single('file'), (req, res) => {
  if (!req.file) throw new HttpError(400, 'Bir .zip dosyası seçin.');
  const files = filesFromZip(req.file.buffer);
  const fallbackTitle = originalName(req.file).replace(/\.zip$/i, '');
  const title = requireString(req.body.title || fallbackTitle || 'İçe aktarılan proje', 'Proje adı', { max: 120 });
  res.json({ id: createProject(req.user.id, title, files, pickMainFile(files)) });
});

projectsRouter.get('/projects/:id', withProject(), (req, res) => {
  const p = req.project;
  const owner = db.prepare('SELECT id, name, email FROM users WHERE id = ?').get(p.owner_id);
  const members = db.prepare(`
    SELECT u.id, u.name, u.email, m.role FROM project_members m JOIN users u ON u.id = m.user_id
    WHERE m.project_id = ? ORDER BY u.name
  `).all(p.id);
  res.json({
    project: { id: p.id, title: p.title, mainFile: p.main_file, role: req.role, owner },
    files: listFiles(p.id),
    members,
  });
});

projectsRouter.patch('/projects/:id', withProject('editor'), (req, res) => {
  const { title, mainFile } = req.body;
  if (title !== undefined) {
    db.prepare(`UPDATE projects SET title = ?, updated_at = datetime('now') WHERE id = ?`)
      .run(requireString(title, 'Proje adı', { max: 120 }), req.project.id);
  }
  if (mainFile !== undefined) {
    const path = cleanPath(mainFile);
    if (!db.prepare('SELECT 1 FROM files WHERE project_id = ? AND path = ?').get(req.project.id, path)) {
      throw new HttpError(400, 'Ana dosya projede bulunamadı.');
    }
    db.prepare('UPDATE projects SET main_file = ? WHERE id = ?').run(path, req.project.id);
  }
  res.json({ ok: true });
});

projectsRouter.delete('/projects/:id', withProject('owner'), (req, res) => {
  db.prepare('DELETE FROM projects WHERE id = ?').run(req.project.id);
  res.json({ ok: true });
});

projectsRouter.get('/projects/:id/export', withProject(), (req, res) => {
  const rows = db.prepare('SELECT path, content FROM files WHERE project_id = ?').all(req.project.id);
  const archive = {};
  for (const r of rows) archive[r.path] = typeof r.content === 'string' ? Buffer.from(r.content, 'utf8') : r.content;
  // Thoth'un derlemede eklediği destek dosyaları (APA 7 Türkçe yerelleştirmesi) arşive de konur;
  // böylece proje başka bir LaTeX kurulumunda da aynı biçimde derlenir.
  if (rows.some((r) => typeof r.content === 'string' && /\{biblatex\}/.test(r.content))) {
    for (const s of SUPPORT_FILES) archive[s.name] ??= s.content;
  }
  res.attachment(`${req.project.title}.zip`).type('application/zip').send(Buffer.from(zipSync(archive)));
});

// ---- Dosyalar ----

projectsRouter.get('/projects/:id/file', withProject(), (req, res) => {
  const path = cleanPath(req.query.path);
  const row = db.prepare('SELECT content, is_binary, rev FROM files WHERE project_id = ? AND path = ?').get(req.project.id, path);
  if (!row) throw new HttpError(404, 'Dosya bulunamadı.');
  if (row.is_binary) throw new HttpError(400, 'Bu dosya metin olarak açılamaz.');
  res.json({ path, content: row.content, rev: row.rev });
});

projectsRouter.get('/projects/:id/raw', withProject(), (req, res) => {
  const path = cleanPath(req.query.path);
  const row = db.prepare('SELECT content FROM files WHERE project_id = ? AND path = ?').get(req.project.id, path);
  if (!row) throw new HttpError(404, 'Dosya bulunamadı.');
  // SVG gibi etkin içerik barındırabilen dosyalar tarayıcıda çalıştırılmasın diye sandbox uygulanır.
  res.set('Content-Security-Policy', 'sandbox').type(mimeOf(path)).send(Buffer.from(row.content));
});

projectsRouter.put('/projects/:id/file', withProject('editor'), (req, res) => {
  const path = cleanPath(req.body.path);
  const { content, baseRev } = req.body;
  if (typeof content !== 'string') throw new HttpError(400, 'Dosya içeriği gerekli.');
  if (!isTextPath(path)) throw new HttpError(400, 'Bu uzantıda metin dosyası oluşturulamaz.');
  const rev = tx(() => {
    const current = db.prepare('SELECT rev, content FROM files WHERE project_id = ? AND path = ?').get(req.project.id, path);
    if (current && baseRev == null) throw new HttpError(409, 'Bu adda bir dosya zaten var.');
    if (current && baseRev !== current.rev) {
      throw new HttpError(409, 'Dosya bu sırada başka biri tarafından değiştirildi.', {
        conflict: { rev: current.rev, content: current.content },
      });
    }
    const newRev = putFile(req.project.id, path, content, false);
    maybeAutoSnapshot(req.project.id, req.user.id);
    return newRev;
  });
  res.json({ rev });
});

projectsRouter.post('/projects/:id/upload', withProject('editor'), upload.array('files'), (req, res) => {
  if (!req.files?.length) throw new HttpError(400, 'Yüklenecek dosya seçin.');
  const dir = req.body.dir ? `${cleanPath(req.body.dir)}/` : '';
  tx(() => {
    for (const f of req.files) {
      const path = cleanPath(dir + originalName(f));
      const text = isTextPath(path);
      putFile(req.project.id, path, text ? decodeText(f.buffer) : f.buffer, !text);
    }
  });
  res.json({ files: listFiles(req.project.id) });
});

/** Tek bir dosyayı ya da bir klasörün (yol önekinin) tamamını seçen WHERE koşulu. */
const underPath = `project_id = ? AND (path = ? OR substr(path, 1, length(?) + 1) = ? || '/')`;

projectsRouter.post('/projects/:id/rename', withProject('editor'), (req, res) => {
  const from = cleanPath(req.body.from);
  const to = cleanPath(req.body.to);
  tx(() => {
    const rows = db.prepare(`SELECT path FROM files WHERE ${underPath}`).all(req.project.id, from, from, from);
    if (!rows.length) throw new HttpError(404, 'Dosya bulunamadı.');
    for (const { path } of rows) {
      const target = to + path.slice(from.length);
      if (db.prepare('SELECT 1 FROM files WHERE project_id = ? AND path = ?').get(req.project.id, target)) {
        throw new HttpError(409, `"${target}" adında bir dosya zaten var.`);
      }
      db.prepare('UPDATE files SET path = ?, rev = ? WHERE project_id = ? AND path = ?')
        .run(target, nextRev(req.project.id), req.project.id, path);
      if (req.project.main_file === path) {
        db.prepare('UPDATE projects SET main_file = ? WHERE id = ?').run(target, req.project.id);
      }
    }
  });
  res.json({ files: listFiles(req.project.id) });
});

projectsRouter.delete('/projects/:id/file', withProject('editor'), (req, res) => {
  const path = cleanPath(req.query.path);
  if (path === req.project.main_file) throw new HttpError(400, 'Ana dosya silinemez. Önce başka bir ana dosya seçin.');
  const { changes } = db.prepare(`DELETE FROM files WHERE ${underPath}`).run(req.project.id, path, path, path);
  if (!changes) throw new HttpError(404, 'Dosya bulunamadı.');
  nextRev(req.project.id);
  res.json({ files: listFiles(req.project.id) });
});

// ---- Paylaşım ----

projectsRouter.post('/projects/:id/members', withProject('owner'), (req, res) => {
  const email = requireString(req.body.email, 'E-posta', { max: 120 });
  const role = req.body.role === 'viewer' ? 'viewer' : 'editor';
  const user = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
  if (!user) throw new HttpError(404, 'Bu e-posta adresiyle kayıtlı bir kullanıcı yok. Önce hesap açması gerekir.');
  if (user.id === req.user.id) throw new HttpError(400, 'Projenin sahibi zaten sizsiniz.');
  db.prepare(`
    INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, ?)
    ON CONFLICT (project_id, user_id) DO UPDATE SET role = excluded.role
  `).run(req.project.id, user.id, role);
  res.json({ ok: true });
});

projectsRouter.delete('/projects/:id/members/:userId', withProject('owner'), (req, res) => {
  db.prepare('DELETE FROM project_members WHERE project_id = ? AND user_id = ?').run(req.project.id, Number(req.params.userId));
  res.json({ ok: true });
});