-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
658 lines (596 loc) · 19.7 KB
/
main.go
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package main
import (
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"github.com/SwissOpenEM/Depositor/depositions/onedep"
docs "github.com/SwissOpenEM/Depositor/docs"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
parser "github.com/osc-em/converter-OSCEM-to-mmCIF/parser"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
// @title OpenEm Depositor API
// @version api/v1
// @description Rest API for communication between SciCat frontend and depositor backend. Backend service enables deposition of datasets to OneDep API.
var version string = "DEV"
var PORT string = "8080"
// Convert multipart.File to *os.File by saving it to a temporary file
func convertMultipartFileToFile(file multipart.File) (*os.File, error) {
tempFile, err := os.CreateTemp("", "uploaded-*")
if err != nil {
return nil, err
}
defer file.Close()
// Copy the contents of the multipart.File to the temporary file
if _, err := io.Copy(tempFile, file); err != nil {
tempFile.Close()
return nil, err
}
// Close and reopen the file to reset the read pointer for future operations
if err := tempFile.Close(); err != nil {
return nil, err
}
return os.Open(tempFile.Name())
}
// Create handles the creation of a new deposition
// @Summary Create a new deposition to OneDep
// @Description Create a new deposition by uploading experiment and user details to OneDep API.
// @Tags deposition
// @Accept application/json
// @Produce json
// @Param request body onedep.RequestCreate true "User information"
// @Success 200 {object} onedep.CreatedDeposition "Success response with Deposition ID"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep [post]
func Create(c *gin.Context) {
var body onedep.RequestCreate
// Bind JSON payload to the struct
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "invalid_request_body",
"message": err.Error(),
})
return
}
email := body.Email
var experiments []onedep.EmMethod
if exp, ok := onedep.EmMethods[body.Method]; ok {
experiments = []onedep.EmMethod{exp}
} else {
c.JSON(http.StatusBadRequest, gin.H{
"status": "method_unknown",
"message": fmt.Sprintf("unknown EM method %v", body.Method),
})
return
}
bearer := body.JWTToken
depData := onedep.UserInfo{
Email: email,
Users: body.OrcidIds,
Country: "United States", // body.country
Experiments: experiments,
Password: body.Password,
}
client := &http.Client{}
deposition, resp := onedep.CreateDeposition(client, depData, bearer)
if resp != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": resp.Status,
"message": resp.Message,
})
return
} else {
c.JSON(http.StatusCreated, gin.H{"depID": deposition.Id})
return
}
}
// AddFiles handles adding files to an existing deposition. It also opens a header of mrc files and extracts the pixel spacing
// @Summary Add file, pixel spacing, contour level and description to deposition in OneDep
// @Description Uploading file, and metadata to OneDep API.
// @Tags deposition
// @Accept multipart/form-data
// @Produce json
// @Param depID path string true "Deposition ID to which a file should be uploaded"
// @Param file formData []file true "File to upload" collectionFormat(multi)
// @Param fileMetadata formData string true "File metadata as a JSON string"
// @Param jwtToken formData string true "JWT token for OneDep API"
// @Success 200 {object} onedep.UploadedFile "File ID"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep/{depID}/file [post]
func AddFile(c *gin.Context) {
err := c.Request.ParseMultipartForm(10 << 20)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "form_invalid",
"message": "Failed to parse Form data.",
})
return
}
depID := c.Param("depID")
bearer := c.PostForm("jwtToken")
fileHeader := c.Request.MultipartForm.File["file"][0] //file
metadataFilesStr := c.PostForm("fileMetadata") //files Metadata
if metadataFilesStr == "{}" {
c.JSON(http.StatusBadRequest, gin.H{
"status": "form_invalid",
"message": "Missing metadata for files information.",
})
return
}
var fileMetadata onedep.FileUpload
err = json.Unmarshal([]byte(metadataFilesStr), &fileMetadata)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "JSON_invalid",
"message": fmt.Sprintf("error decoding JSON: %v", err.Error()),
})
return
}
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "file_header_invalid",
"message": fmt.Sprintf("failed to open file header: %v", err.Error()),
})
return
}
defer file.Close()
client := &http.Client{}
var fileDeposited onedep.DepositionFile
fileDeposited, errResp := onedep.AddFileToDeposition(client, depID, fileMetadata, file, bearer)
if errResp != nil {
c.JSON(http.StatusBadRequest, errResp)
return
}
// c.JSON(http.StatusOK, gin.H{"depID": depID, "fileID": fileDeposited.Id})
for j := range onedep.NeedMeta {
if fileMetadata.Type == onedep.NeedMeta[j] {
fileDeposited, errResp := onedep.AddMetadataToFile(client, fileDeposited, bearer)
if errResp != nil {
c.JSON(http.StatusBadRequest, errResp)
return
}
c.JSON(http.StatusOK, gin.H{"depID": depID, "fileID": fileDeposited.Id})
return
}
}
c.JSON(http.StatusOK, gin.H{"depID": depID, "fileID": fileDeposited.Id})
}
// AddMetadata handles adding metadata to an existing deposition.
// @Summary Add a cif file with metadata to deposition in OneDep
// @Description Uploading metadata file to OneDep API. This is created by parsing the JSON metadata into the converter.
// @Tags deposition
// @Accept multipart/form-data
// @Produce json
// @Param depID path string true "Deposition ID to which a file should be uploaded"
// @Param jwtToken formData string true "JWT token for OneDep API"
// @Param scientificMetadata formData string true "Scientific metadata as a JSON string; expects elements from OSCEM on the top level"
// @Success 200 {object} onedep.UploadedFile "File ID"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep/{depID}/metadata [post]
func AddMetadata(c *gin.Context) {
err := c.Request.ParseMultipartForm(10 << 20)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Failed to parse Form data.",
})
return
}
depID := c.Param("depID")
bearer := c.PostForm("jwtToken")
// FIX ME add a OSCEM SCHEMA
// Extract entries from multipart form
metadataStr := c.PostForm("scientificMetadata")
if metadataStr == "{}" {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Missing scientific metadata.",
})
return
}
// Parse JSON string into the Metadata
var scientificMetadata map[string]any
err = json.Unmarshal([]byte(metadataStr), &scientificMetadata)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Failed to parse scientific metadata to JSON.",
})
return
}
// create a temporary cif file that will be used for a deposition
fileScientificMeta, err := os.CreateTemp("", "metadata.cif")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "cif_creation_fails",
"message": "Failed to create a file to write cif file with metadata.",
})
return
}
fileScientificMetaPath := fileScientificMeta.Name()
// convert OSCEM-JSON to mmCIF
cifText, err := parser.EMDBconvert(
scientificMetadata,
"",
"conversions.csv",
"mmcif_pdbx_v50.dic",
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "conversion_to_cif_fails",
"message": err.Error(),
})
return
}
err = parser.WriteCif(cifText, fileScientificMetaPath)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "writing_cif_fails",
"message": err.Error(),
})
return
}
client := &http.Client{}
metadataFile := onedep.FileUpload{
Name: "metadata.cif",
Type: "co-cif", // FIX ME add appropriate type once it's implemented in OneDep API
}
cifFile, err := os.Open(fileScientificMetaPath)
if err != nil {
c.JSON(http.StatusBadRequest, &onedep.ResponseType{
Status: "cif_file_issue",
Message: err.Error(),
})
}
defer cifFile.Close()
fileDeposited, errResp := onedep.AddFileToDeposition(client, depID, metadataFile, cifFile, bearer)
if errResp != nil {
c.JSON(http.StatusBadRequest, errResp)
return
}
defer os.Remove(fileScientificMetaPath)
c.JSON(http.StatusOK, gin.H{"depID": depID, "fileID": fileDeposited.Id})
}
// AddCoordinates handles adding coordinates files to an existing deposition.
// @Summary Add coordinates and description to deposition in OneDep
// @Description Uploading file to OneDep API.
// @Tags deposition
// @Accept multipart/form-data
// @Produce json
// @Param depID path string true "Deposition ID to which a file should be uploaded"
// @Param jwtToken formData string true "JWT token for OneDep API"
// @Param file formData file true "File to upload"
// @Param scientificMetadata formData string true "Scientific metadata as a JSON string; expects elements from OSCEM on the top level"
// @Success 200 {object} onedep.UploadedFile "File ID"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep/{depID}/pdb [post]
func AddCoordinates(c *gin.Context) {
err := c.Request.ParseMultipartForm(10 << 20)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Failed to parse Form data.",
})
return
}
depID := c.Param("depID")
bearer := c.PostForm("jwtToken")
fileHeader := c.Request.MultipartForm.File["file"][0] //file
metadataStr := c.PostForm("scientificMetadata")
if metadataStr == "{}" {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Missing scientific metadata.",
})
return
}
// Parse JSON string into the Metadata
var scientificMetadata map[string]any
err = json.Unmarshal([]byte(metadataStr), &scientificMetadata)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Failed to parse scientific metadata to JSON.",
})
return
}
// create a temporary cif file that will be used for a deposition
fileScientificMeta, err := os.CreateTemp("", "metadata.cif")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "cif_invalid",
"message": "Failed to create a file to write new cif file.",
})
return
}
fileScientificMetaPath := fileScientificMeta.Name()
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "file_invalid",
"message": fmt.Sprintf("Failed to open file header: %v", err.Error()),
})
return
}
defer file.Close()
fileTmp, err := convertMultipartFileToFile(file)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "file_invalid",
"message": fmt.Sprintf("failed to open cif file to read coordinates: %v", err.Error()),
})
return
}
defer file.Close()
cifText, err := parser.PDBconvertFromFile(
scientificMetadata,
"",
"conversions.csv",
"mmcif_pdbx_v50.dic",
fileTmp,
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "conversion_to_cif_fails",
"message": err.Error(),
})
return
}
err = parser.WriteCif(cifText, fileScientificMetaPath)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "writing_cif_fails",
"message": err.Error(),
})
return
}
client := &http.Client{}
mockFileUpload := onedep.FileUpload{
Name: "coordinates.cif",
Type: "co-cif",
Details: "",
}
cifFile, err := os.Open(fileScientificMetaPath)
if err != nil {
c.JSON(http.StatusBadRequest, &onedep.ResponseType{
Status: "cif_file_issue",
Message: err.Error(),
})
}
defer cifFile.Close()
fileDeposited, errResp := onedep.AddFileToDeposition(client, depID, mockFileUpload, cifFile, bearer)
if errResp != nil {
c.JSON(http.StatusBadRequest, errResp)
return
}
defer file.Close()
// add in web UI no such fields for coordinates
// if fileMetadata.Details != "" {
// fileDeposited, errResp := onedep.AddMetadataToFile(client, fileDeposited, bearer)
// if errResp != nil {
// c.JSON(http.StatusBadRequest, errResp)
// return
// }
// c.JSON(http.StatusOK, gin.H{"depID": depID, "fileID": fileDeposited.Id})
// }
defer os.Remove(fileScientificMetaPath)
c.JSON(http.StatusOK, gin.H{
"depID": depID,
"fileID": fileDeposited.Id,
})
}
// DownloadMetadata handles getting a cif file with metadata.
// @Summary Get a cif file with metadata for manual deposition in OneDep
// @Description Downloading a metadata file. Invokes converter and starts download.
// @Tags deposition
// @Accept application/json
// @Produce application/octet-stream
// @Param scientificMetadata body object true "Scientific metadata as a JSON string; expects elements from OSCEM on the top level"
// @Success 200 {file} application/octet-stream "File download for the generated metadata.cif"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep/metadata [post]
func DownloadMetadata(c *gin.Context) {
var scientificMetadata map[string]interface{}
// Bind the JSON payload into a metadata
if err := c.ShouldBindJSON(&scientificMetadata); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "invalid_request_body",
"message": fmt.Sprintf("Failed to parse metadata body: %v", err.Error()),
})
return
}
// create a temporary cif file that will be used for a deposition
fileScientificMeta, err := os.CreateTemp("", "metadata.cif")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "cif_creation_fails",
"message": "Failed to create a file to write cif file with metadata.",
})
return
}
fileScientificMetaPath := fileScientificMeta.Name()
// convert OSCEM-JSON to mmCIF
cifText, err := parser.EMDBconvert(
scientificMetadata,
"",
"conversions.csv",
"mmcif_pdbx_v50.dic",
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "conversion_to_cif_fails",
"message": err.Error(),
})
return
}
err = parser.WriteCif(cifText, fileScientificMetaPath)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "writing_cif_fails",
"message": err.Error(),
})
return
}
c.Header("Content-Type", "application/octet-stream")
c.FileAttachment(fileScientificMetaPath, "metadata.cif")
defer os.Remove(fileScientificMetaPath)
}
// DownloadCoordinates handles parsing an existing cif and metadata and downloading a new cif file.
// @Summary Get a cif file with metadata and coordinates for manual deposition in OneDep
// @Description Downloading a metadata file. Invokes converter and starts download.
// @Tags deposition
// @Accept multipart/form-data
// @Produce application/octet-stream
// @Param scientificMetadata formData string true "Scientific metadata as a JSON string; expects elements from OSCEM on the top level"
// @Param file formData file true "File to upload"
// @Success 200 {file} application/octet-stream "File download for the generated metadata.cif"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep/pdb [post]
func DownloadCoordinatesWithMetadata(c *gin.Context) {
err := c.Request.ParseMultipartForm(10 << 20)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Failed to parse Form data.",
})
return
}
fileHeader := c.Request.MultipartForm.File["file"][0]
// Extract entries from multipart form
metadataStr := c.PostForm("scientificMetadata")
if metadataStr == "{}" {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Missing scientific metadata.",
})
return
}
// Parse JSON string into the Metadata
var scientificMetadata map[string]any
err = json.Unmarshal([]byte(metadataStr), &scientificMetadata)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "body_invalid",
"message": "Failed to parse scientific metadata to JSON.",
})
return
}
// create a temporary cif file that will be used for a deposition
fileScientificMeta, err := os.CreateTemp("", "metadata.cif")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "cif_invalid",
"message": "Failed to create a file to write new cif file.",
})
return
}
fileScientificMetaPath := fileScientificMeta.Name()
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "file_invalid",
"message": fmt.Sprintf("Failed to open file header: %v", err.Error()),
})
return
}
defer file.Close()
fileTmp, err := convertMultipartFileToFile(file)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "file_invalid",
"message": fmt.Sprintf("failed to open cif file to read coordinates: %v", err.Error()),
})
return
}
defer file.Close()
cifText, err := parser.PDBconvertFromFile(
scientificMetadata,
"",
"conversions.csv",
"mmcif_pdbx_v50.dic",
fileTmp,
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "conversion_to_cif_fails",
"message": err.Error(),
})
return
}
err = parser.WriteCif(cifText, fileScientificMetaPath)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "writing_cif_fails",
"message": err.Error(),
})
return
}
c.Header("Content-Type", "application/octet-stream")
c.FileAttachment(fileScientificMetaPath, "metadata.cif")
defer os.Remove(fileScientificMetaPath)
}
// Create handles the creation of a new deposition
// @Summary Process deposition to OneDep
// @Description Process a deposition in OneDep API.
// @Tags deposition
// @Accept application/json
// @Produce json
// @Param depID path string true "Deposition ID to which a file should be uploaded"
// @Param jwtToken formData string true "JWT token for OneDep API"
// @Success 200 {object} onedep.CreatedDeposition "Deposition ID"
// @Failure 400 {object} onedep.ResponseType "Error response"
// @Failure 500 {object} onedep.ResponseType "Internal server error"
// @Router /onedep/{depID}/process [post]
func StartProcess(c *gin.Context) {
depID := c.Param("depID")
client := &http.Client{}
bearer := c.PostForm("jwtToken")
_, err := onedep.ProcessDeposition(client, depID, bearer)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, gin.H{"fileID": depID})
}
// returns the current version of the depositor
//
// @Summary Return current version
// @Description Create a new deposition by uploading experiments, files, and metadata to OneDep API.
// @Tags version
// @Produce json
// @Success 200 {string} string "Depositior version"
// @Router /version [get]
func GetVersion(c *gin.Context) {
c.JSON(http.StatusOK, version)
}
func main() {
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:4200"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept"},
}))
docs.SwaggerInfo.BasePath = router.BasePath()
router.GET("/docs/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
router.GET("/version", GetVersion)
router.POST("/onedep", Create)
router.POST("/onedep/:depID/file", AddFile)
router.POST("/onedep/:depID/metadata", AddMetadata)
router.POST("/onedep/:depID/pdb", AddCoordinates)
router.POST("/onedep/:depID/process", StartProcess)
router.POST("/onedep/metadata", DownloadMetadata)
router.POST("/onedep/pdb", DownloadCoordinatesWithMetadata)
router.Run("localhost:" + PORT)
}