forked from yu-i-i/overleaf-cep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitBridgeApiController.mjs
More file actions
301 lines (262 loc) · 8.14 KB
/
GitBridgeApiController.mjs
File metadata and controls
301 lines (262 loc) · 8.14 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Controller for API v0 endpoints used by git-bridge
// These endpoints provide git-bridge with access to project data, versions, and snapshots
import { callbackify } from 'node:util'
import { expressify } from '@overleaf/promise-utils'
import logger from '@overleaf/logger'
import { fetchJson } from '@overleaf/fetch-utils'
import settings from '@overleaf/settings'
import ProjectGetter from '../Project/ProjectGetter.mjs'
import HistoryManager from '../History/HistoryManager.mjs'
import UserGetter from '../User/UserGetter.js'
import { Snapshot } from 'overleaf-editor-core'
import Errors from '../Errors/Errors.js'
/**
* GET /api/v0/docs/:project_id
* Returns the latest version info for a project
*/
async function getDoc(req, res, next) {
const projectId = req.params.project_id
try {
// Get project
const project = await ProjectGetter.promises.getProject(projectId, {
name: 1,
owner_ref: 1,
})
if (!project) {
return res.status(404).json({ message: 'Project not found' })
}
// Get latest history version
const historyId = await HistoryManager.promises.getHistoryId(projectId)
const latestHistory = await HistoryManager.promises.getLatestHistory(
projectId
)
if (!latestHistory || !latestHistory.updates) {
// No history yet, return minimal response
return res.json({
latestVerId: 0,
latestVerAt: new Date().toISOString(),
latestVerBy: null,
})
}
// Get the most recent update
const updates = latestHistory.updates
const latestUpdate = updates[0] // updates are sorted newest first
let latestVerBy = null
if (latestUpdate.meta && latestUpdate.meta.users) {
const userId = latestUpdate.meta.users[0]
if (userId) {
const user = await UserGetter.promises.getUser(userId, {
email: 1,
first_name: 1,
last_name: 1,
})
if (user) {
const name = [user.first_name, user.last_name]
.filter(Boolean)
.join(' ')
latestVerBy = {
email: user.email,
name: name || user.email,
}
}
}
}
const response = {
latestVerId: latestUpdate.toV || 0,
latestVerAt: latestUpdate.meta.end_ts
? new Date(latestUpdate.meta.end_ts).toISOString()
: new Date().toISOString(),
latestVerBy,
}
res.json(response)
} catch (err) {
logger.error({ err, projectId }, 'Error getting doc info')
next(err)
}
}
/**
* GET /api/v0/docs/:project_id/saved_vers
* Returns the list of saved versions (labels) for a project
*/
async function getSavedVers(req, res, next) {
const projectId = req.params.project_id
try {
// Get project to verify it exists
const project = await ProjectGetter.promises.getProject(projectId, {
name: 1,
})
if (!project) {
return res.status(404).json({ message: 'Project not found' })
}
// Get labels from project-history service
let labels
try {
labels = await fetchJson(
`${settings.apis.project_history.url}/project/${projectId}/labels`
)
} catch (err) {
// If no labels exist, return empty array
if (err.response?.status === 404) {
labels = []
} else {
throw err
}
}
// Enrich labels with user information
labels = await enrichLabels(labels)
// Transform to git-bridge format
const savedVers = labels.map(label => ({
versionId: label.version,
comment: label.comment,
user: {
email: label.user_display_name || label.user?.email || 'unknown',
name: label.user_display_name || label.user?.name || 'unknown',
},
createdAt: label.created_at,
}))
res.json(savedVers)
} catch (err) {
logger.error({ err, projectId }, 'Error getting saved versions')
next(err)
}
}
/**
* GET /api/v0/docs/:project_id/snapshots/:version
* Returns the snapshot (file contents) for a specific version
*/
async function getSnapshot(req, res, next) {
const projectId = req.params.project_id
const version = parseInt(req.params.version, 10)
try {
// Get project to verify it exists
const project = await ProjectGetter.promises.getProject(projectId, {
name: 1,
})
if (!project) {
return res.status(404).json({ message: 'Project not found' })
}
// Get snapshot content from history service
const snapshotRaw = await HistoryManager.promises.getContentAtVersion(
projectId,
version
)
const snapshot = Snapshot.fromRaw(snapshotRaw)
// Build response in git-bridge format
// Note: srcs and atts are arrays of arrays: [[content, path], [content, path], ...]
const srcs = []
const atts = []
// Process all files in the snapshot
const files = snapshot.getFileMap()
for (const [pathname, file] of files) {
if (file.isEditable()) {
// Text file - include content directly as [content, path] array
srcs.push([file.getContent(), pathname])
} else {
// Binary file - provide URL to download as [url, path] array
const hash = file.getHash()
// Build URL to blob endpoint (already exists in web service)
const blobUrl = `${settings.siteUrl}/project/${projectId}/blob/${hash}`
atts.push([blobUrl, pathname])
}
}
const response = {
srcs,
atts,
}
res.json(response)
} catch (err) {
if (err instanceof Errors.NotFoundError) {
return res.status(404).json({ message: 'Version not found' })
}
logger.error({ err, projectId, version }, 'Error getting snapshot')
next(err)
}
}
/**
* POST /api/v0/docs/:project_id/snapshots
* Receives a push from git-bridge with file changes
*/
async function postSnapshot(req, res, next) {
const projectId = req.params.project_id
const { latestVerId, files, postbackUrl } = req.body
try {
// Get project to verify it exists
const project = await ProjectGetter.promises.getProject(projectId, {
name: 1,
})
if (!project) {
return res.status(404).json({ message: 'Project not found' })
}
// TODO: Implement snapshot push logic
// This would involve:
// 1. Validating the latestVerId matches current version
// 2. Processing the files array (downloading from URLs if modified)
// 3. Updating the project with new content
// 4. Posting back results to postbackUrl
// For now, return "not implemented" response
logger.warn(
{ projectId, latestVerId },
'Snapshot push not yet implemented'
)
res.status(501).json({
status: 501,
code: 'notImplemented',
message: 'Snapshot push not yet implemented',
})
} catch (err) {
logger.error({ err, projectId }, 'Error posting snapshot')
next(err)
}
}
/**
* Enrich labels with user information
*/
async function enrichLabels(labels) {
if (!labels || !labels.length) {
return []
}
// Get unique user IDs
const uniqueUsers = new Set(labels.map(label => label.user_id))
uniqueUsers.delete(null)
uniqueUsers.delete(undefined)
// Fetch user details
const userDetailsMap = new Map()
for (const userId of uniqueUsers) {
try {
const user = await UserGetter.promises.getUser(userId, {
email: 1,
first_name: 1,
last_name: 1,
})
if (user) {
const name = [user.first_name, user.last_name]
.filter(Boolean)
.join(' ')
userDetailsMap.set(userId.toString(), {
email: user.email,
name: name || user.email,
})
}
} catch (err) {
logger.warn({ err, userId }, 'Failed to get user details for label')
}
}
// Enrich labels
return labels.map(label => {
const enrichedLabel = { ...label }
if (label.user_id) {
const userDetails = userDetailsMap.get(label.user_id.toString())
if (userDetails) {
enrichedLabel.user = userDetails
enrichedLabel.user_display_name = userDetails.name
}
}
return enrichedLabel
})
}
export default {
getDoc: expressify(getDoc),
getSavedVers: expressify(getSavedVers),
getSnapshot: expressify(getSnapshot),
postSnapshot: expressify(postSnapshot),
}