-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectFactory.js
More file actions
610 lines (566 loc) · 17.6 KB
/
ProjectFactory.js
File metadata and controls
610 lines (566 loc) · 17.6 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
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"
import imageSize from 'image-size';
import mime from 'mime-types';
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 tools = [
{
"name":"Page Tools",
"value":"page",
"state": false
},
{
"name":"Inspect",
"value":"inspector",
"state": false
},
{
"name":"Special Characters",
"value":"characters",
"state": false
},
{
"name":"XML Tags",
"value":"xml",
"state": false
},
{
"name":"View Full Page",
"value":"fullpage",
"state": false
},
{
"name":"History Tool",
"value":"history",
"state": false
},
{
"name":"Preview Tool",
"value":"preview",
"state": false
},
{
"name":"Parsing Adjustment",
"value":"parsing",
"state": false
},
{
"name":"Compare Pages",
"value":"compare",
"state": false
},
{
"name": "Cappelli's Abbreviation",
"value": "cappelli",
"url": "https://centerfordigitalhumanities.github.io/cappelli/",
"state": false
},
{
"name": "Enigma",
"value": "enigma",
"url": "https://ciham-digital.huma-num.fr/enigma/",
"state": false
},
{
"name": "Latin Dictionary",
"value": "latin",
"url": "https://www.perseus.tufts.edu/hopper/resolveform?lang=latin",
"state": false
},
{
"name": "Latin Vulgate",
"value": "vulgate",
"url": "https://vulsearch.sourceforge.net/cgi-bin/vulsearch",
"state": false
}
]
static async DBObjectFromManifest(manifest) {
if (!manifest) {
throw {
status: 404,
message: err.message ?? "No manifest found. Cannot process empty object"
}
}
const _id = database.reserveId()
const now = Date.now().toString().slice(-6)
const label = ProjectFactory.getLabelAsString(manifest.label) ?? now
const metadata = manifest.metadata ?? []
const layer = Layer.build( _id, `First Layer - ${label}`, manifest.items )
const firstPage = layer.pages[0]?.id.split('/').pop() ?? true
// required properties: id, label, metadata, manifest, layers
return {
_id,
label,
metadata,
manifest: [ manifest.id ],
layers: [ layer.asProjectLayer() ],
tools: this.tools,
_createdAt: now,
_modifiedAt: -1,
_lastModified: firstPage,
}
}
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"
}
})
}
/**
* Creates a new manifest from given image url and project label.
* @param {string} imageUrl - URL of the image to be used in the project.
* @param {string} label - Label for the project.
* @returns {Object} - Returns the created project object.
*/
static async getImageDimensions(imgUrl) {
try {
const response = await fetch(imgUrl)
if (!response.ok) {
throw {
status: response.status,
message: `Failed to fetch image: ${response.statusText}`
}
}
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const dimensions = imageSize(buffer)
return {
width: dimensions.width,
height: dimensions.height
}
} catch (err) {
console.error("Error fetching image dimensions:", err.message)
return
}
}
static async DBObjectFromImage(manifest) {
if (!manifest) {
throw {
status: 404,
message: err.message ?? "No manifest found. Cannot process empty object"
}
}
const _id = manifest.id.split('/').slice(-2, -1)[0]
const now = Date.now().toString().slice(-6)
const label = ProjectFactory.getLabelAsString(manifest.label)
const metadata = manifest.metadata ?? []
const layer = Layer.build( _id, `First Layer - ${label}`, manifest.items )
const firstPage = layer.pages[0]?.id.split('/').pop() ?? true
return {
_id,
label,
metadata,
manifest: [ manifest.id ],
layers: [ layer.asProjectLayer() ],
tools: this.tools,
_createdAt: now,
_modifiedAt: -1,
_lastModified: firstPage,
}
}
static async createManifestFromImage(imageURL, projectLabel, creator) {
if (!imageURL) {
throw {
status: 404,
message: "No image found. Cannot process further."
}
}
const _id = database.reserveId()
const now = Date.now().toString().slice(-6)
const label = projectLabel ?? now
const dimensions = await this.getImageDimensions(imageURL)
const canvasLayout = {
id: `${process.env.TPENSTATIC}/${_id}/canvas-1.json`,
type: "Canvas",
label: { "none": [`${label} Page 1`] },
width: dimensions.width,
height: dimensions.height,
items: [
{
id: `${process.env.TPENSTATIC}/${_id}/contentPage.json`,
type: "AnnotationPage",
items: [
{
id: `${process.env.TPENSTATIC}/${_id}/content.json`,
type: "Annotation",
motivation: "painting",
body: {
id: imageURL,
type: "Image",
format: mime.lookup(imageURL) || "image/jpeg",
width: dimensions.width,
height: dimensions.height
},
target: `${process.env.TPENSTATIC}/${_id}/canvas-1.json`
}
]
}
]
}
const projectManifest = {
"@context": "http://iiif.io/api/presentation/3/context.json",
id: `${process.env.TPENSTATIC}/${_id}/manifest.json`,
type: "Manifest",
label: { "none": [label] },
items: [ canvasLayout ]
}
const projectCanvas = {
"@context": "http://iiif.io/api/presentation/3/context.json",
...canvasLayout
}
await this.uploadFileToGitHub(projectManifest, _id)
await this.uploadFileToGitHub(projectCanvas, _id)
return await ProjectFactory.DBObjectFromImage(projectManifest)
.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 fileName = manifest?.id?.split('/').pop() ?? 'manifest.json'
const manifestUrl = `https://api.github.com/repos/${process.env.REPO_OWNER}/${process.env.REPO_NAME}/contents/${projectId}/${fileName}`
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
}
const putResponse = 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}/${fileName}` : `Created ${projectId}/${fileName}`,
content: Buffer.from(JSON.stringify(manifest)).toString('base64'),
branch: process.env.BRANCH,
...(sha && { sha }),
})
})
if (!putResponse.ok) {
const errText = await putResponse.text()
throw new Error(`GitHub upload failed: ${putResponse.status} - ${errText}`)
}
return await putResponse.json()
} catch (error) {
console.error(`Failed to upload ${projectId}/${fileName}:`, 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,
_createdAt:1,
_modifiedAt:1,
_lastModified:1
}
}
]
try {
return (await database.controller.db.collection('projects').aggregate(pipeline).toArray())?.[0]
} catch (err) {
console.error(err)
err.status = 500
return err
}
}
}