-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectFactory.js
More file actions
383 lines (355 loc) · 11.5 KB
/
ProjectFactory.js
File metadata and controls
383 lines (355 loc) · 11.5 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import Project from "./Project.js"
import Group from "../Group/Group.js"
import User from "../User/User.js"
import Layer from "../Layer/Layer.js"
import dbDriver from "../../database/driver.js"
import vault from "../../utilities/vault.js"
const database = new dbDriver("mongo")
export default class ProjectFactory {
constructor(data) {
this.data = data
}
static loadManifest = vault.loadManifest
/**
* processes a manifest object into a project object that can be saved into the Project tablein the DB
* @param {*} manifest : The manifest object to be processed
* @returns object of project data
*/
static async DBObjectFromManifest(manifest) {
if (!manifest) {
throw {
status: 404,
message: err.message ?? "No manifest found. Cannot process empty object"
}
}
const now = Date.now().toString().slice(-6)
const label = ProjectFactory.getLabelAsString(manifest.label) ?? now
const metadata = manifest.metadata ?? []
const layer = Layer.build( database.reserveId(), `First Layer - ${label}`, manifest.items )
// required properties: id, label, metadata, manifest, layers
return {
label,
metadata,
manifest: [ manifest.id ],
layers: [ layer.asProjectLayer() ]
}
}
static getLabelAsString(label) {
const defaultLanguage = typeof label === 'object' ? Object.keys(label)[0] : 'en'
return label[defaultLanguage]?.join(", ") ?? label.none?.join(",")
}
static async fromManifestURL(manifestId, creator) {
return vault.loadManifest(manifestId)
.then(async (manifest) => {
return await ProjectFactory.DBObjectFromManifest(manifest)
})
.then(async (project) => {
const projectObj = new Project()
const group = await Group.createNewGroup(
creator,
{
label: project.label ?? project.title ?? `Project ${new Date().toLocaleDateString()}`,
members: { [creator]: { roles: [] } }
})
.then((group) => group._id)
return await projectObj.create({ ...project, creator, group })
})
.catch((err) => {
throw {
status: err.status ?? 500,
message: err.message ?? "Internal Server Error"
}
})
}
/**
* Convert the Project.data into an Object ready for consumption by a TPEN interface,
* especially the GET /project/:id endpoint.
* @param {Object} projectData The loaded Project.data from the database.
*/
static async forInterface(projectData) {
if (!projectData) {
const err = new Error("No project data found")
err.status = 400
throw err
}
const project = {
_id: projectData._id,
label: projectData.label,
metadata: projectData.metadata ?? [],
layers: projectData.layers ?? [],
manifest: projectData.manifest,
creator: projectData.creator,
collaborators: {},
license: projectData.license,
tools: projectData.tools,
options: projectData.options,
roles: Object.assign(Group.defaultRoles, projectData.customRoles)
}
const group = new Group(projectData.group)
await group.getMembers()
.then(members => {
const loadMembers = []
Object.keys(members).forEach(memberId => {
project.collaborators[memberId] = {
roles: members[memberId]
}
loadMembers.push(new User(memberId).getPublicInfo().then(profile => {
project.collaborators[memberId].profile = profile
}))
})
return Promise.all(loadMembers)
})
return project
}
/**
* Exporting the IIIF manifest for a given project in its current state,
* manifest data is assembled, and the final JSON is saved to the filesystem.
*
* @param {string} projectId - Project ID for a specific project.
* @returns {Object} - Returns the assembled IIIF manifest object.
*
* The manifest follows the IIIF Presentation API 3.0 specification and includes:
* - Context, ID, Type, Label, Metadata, Items and Annotations
* - A dynamically fetched list of manifest items, including canvases and their annotations.
* - All elements are embedded in the manifest object.
*/
static async exportManifest(projectId) {
if (!projectId) {
throw { status: 400, message: "No project ID provided" }
}
const project = await ProjectFactory.loadAsUser(projectId, null)
const manifest = {
"@context": "http://iiif.io/api/presentation/3/context.json",
"id": `${process.env.TPENSTATIC}/${projectId}/manifest.json`,
type: "Manifest",
label: { none: [project.label] },
metadata: project.metadata,
items: await this.getManifestItems(project),
}
return manifest
}
static async getManifestItems(project) {
return Promise.all(
project.layers.map(async (layer) => {
try {
const canvasUrl = layer.pages[0].target
const canvasData = await this.fetchJson(canvasUrl)
if (!canvasData) return null
const canvasItems = {
id: canvasData.id ?? canvasData["@id"],
type: canvasData.type,
label: canvasData.label,
width: canvasData.width,
height: canvasData.height,
items: canvasData.items,
annotations: await this.getAnnotations(canvasData),
}
return canvasItems
} catch (error) {
console.error(`Error processing layer:`, error)
return null
}
})
)
}
static async getAnnotations(canvasData) {
return Promise.all(
canvasData.annotations.map(async (annotation) => {
try {
const annotationData = await this.fetchJson(annotation.id)
if (!annotationData) return null
const annotationItems = {
id: annotationData.id ?? annotationData["@id"],
type: annotationData.type,
label: annotationData.label,
items: await this.getLines(annotationData),
partOf: annotationData.partOf,
creator: annotationData.creator,
target: annotationData.target,
}
return annotationItems
} catch (error) {
console.error(`Error processing annotation:`, error)
return null
}
})
)
}
static async getLines(annotationData) {
return Promise.all(
annotationData.items.map(async (item) => {
try {
const lineData = await this.fetchJson(item.id)
if (!lineData) return null
const lineItems = {
id: lineData.id ?? lineData["@id"],
type: lineData.type,
motivation: lineData.motivation,
body: lineData.body,
target: lineData.target,
creator: lineData.creator
}
return lineItems
} catch (error) {
console.error(`Error processing line item:`, error)
return null
}
})
)
}
static async fetchJson(url) {
try {
const response = await fetch(url)
if (!response.ok) throw new Error(`Failed to fetch ${url}`)
return response.json()
} catch (error) {
console.error(`Fetch error: ${error.message}`)
return null
}
}
/**
* Uploads or updates the `manifest.json` file for a given project to a GitHub repository.
*
* @param {string} manifest - JSON Object representing the IIIF manifest.
* @param {string} projectId - Project ID for a specific project.
*
* The method performs the following steps:
* - Creates a GitHub API URL for the `manifest.json` file in the GitHub repository.
* - Checks if the `manifest.json` already exists in the GitHub repository to determine if it's a create or update action.
* - Uploads the file using the GitHub API, including the correct commit message and SHA for updates.
*/
static async uploadFileToGitHub(manifest, projectId) {
const manifestUrl = `https://api.github.com/repos/${process.env.REPO_OWNER}/${process.env.REPO_NAME}/contents/${projectId}/manifest.json`
const token = process.env.GITHUB_TOKEN
try {
let sha = null
const getResponse = await fetch(manifestUrl, {
headers: {
'Authorization': `token ${token}`,
'Accept': 'application/vnd.github.v3+json',
},
})
if (getResponse.ok) {
const fileData = await getResponse.json()
sha = fileData.sha
}
await fetch(manifestUrl, {
method: 'PUT',
headers: {
'Authorization': `token ${token}`,
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: sha ? `Updated ${projectId}/manifest.json` : `Created ${projectId}/manifest.json`,
content: Buffer.from(JSON.stringify(manifest)).toString('base64'),
branch: process.env.BRANCH,
...(sha && { sha }),
})
})
} catch (error) {
console.error(`Failed to upload ${projectId}/manifest.json:`, error)
}
}
static async loadAsUser(project_id, user_id) {
const pipeline = [
{ $match: { _id: project_id } },
{
$lookup: {
from: 'groups',
localField: 'group',
foreignField: '_id',
as: 'groupData'
}
},
{
$set: {
thisGroup: { $arrayElemAt: ['$groupData', 0] }
}
},
{
$lookup: {
from: 'users',
let: { memberIds: { $ifNull: [{ $objectToArray: '$thisGroup.members' }, []] } },
pipeline: [
{ $match: { $expr: { $in: ['$_id', '$$memberIds.k'] } } }
],
as: 'membersData'
}
},
{
$set: {
roles: { $mergeObjects: [{ $ifNull: ['$thisGroup.customRoles', {}] }, Group.defaultRoles] },
}
},
{
$set: {
collaborators: {
$arrayToObject: {
$map: {
input: { $objectToArray: { $ifNull: ['$thisGroup.members', {}] } },
as: 'collab',
in: {
k: '$$collab.k',
v: {
$mergeObjects: ['$$collab.v', {
profile: {
$getField: {
field: '$$collab.k', input: {
$arrayToObject: {
$map: {
input: '$membersData',
as: 'm',
in: { k: '$$m._id', v: '$$m.profile' }
}
}
}
}
}
}]
}
}
}
}
}
}
},
{
$lookup: {
from: "hotkeys",
localField: "_id",
foreignField: "_id",
as: "hotkeys"
},
},
{
$set: {
"options.hotkeys": { $arrayElemAt: ["$hotkeys.symbols", 0] }
}
},
{
$project: {
_id: 1,
label: 1,
title: 1,
creator: 1,
collaborators: 1,
roles: 1,
layers: { $ifNull: ['$layers', []] },
metadata: { $ifNull: ['$metadata', []] },
manifest: 1,
license: 1,
tools: 1,
options: 1,
}
}
]
try {
return (await database.controller.db.collection('projects').aggregate(pipeline).toArray())?.[0]
} catch (err) {
console.error(err)
err.status = 500
return err
}
}
}