-
Notifications
You must be signed in to change notification settings - Fork 1
/
invenio_api.go
2115 lines (2002 loc) · 61.2 KB
/
invenio_api.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// irdmtools is a package for working with institutional repositories and
// data management systems. Current implementation targets Invenio-RDM.
//
// @author R. S. Doiel, <[email protected]>
// @author Tom Morrell, <[email protected]>
//
// Copyright (c) 2023, Caltech
// All rights not granted herein are expressly reserved by Caltech.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package irdmtools
import (
"bytes"
"database/sql"
"encoding/xml"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
// 3rd Party packages
_ "github.com/lib/pq"
// Caltech Library Packages
"github.com/caltechlibrary/simplified"
)
const (
// pageSize sets the number of responses when accessing the
// Invenio JSON API.
pageSize = 250
)
// OAIListIdendifiersResponse
type OAIListIdentifiersResponse struct {
XMLName xml.Name `xml:"OAI-PMH" json:"-"`
XMLNS string `xml:"xmlns,attr,omitempty" json:"xmlns,omitempty"`
ResponseDate string `xml:"responseDate,omitempty" json:"response_date,omitempty"`
Request string `xml:"request,omitempty" json:"request,omitempty"`
RequestAttr map[string]string `xml:"request,attr,omitempty" json:"request_attr,omitempty"`
ListIdentifiers *OAIListIdentifiers `xml:"ListIdentifiers,omitempty" json:"list_identifiers,omitempty"`
}
type OAIListIdentifiers struct {
Headers []OAIHeader `xml:"header,omitempty" json:"header,omitempty"`
ResumptionToken string `xml:"resumptionToken,omitempty" json:"resumption_token,omitempty"`
}
// OAIHeader holds the response items for
type OAIHeader struct {
Status string `xml:"status,attr,omitempty" json:"status,omitempty"`
Identifier string `xml:"identifier,omitempty" json:"identifier,omitempty"`
DateStamp string `xml:"datestamp,omitempty" json:"datestamp,omitempty"`
SetSpec []string `xml:"setSpec,omitempty" json:"set_spec,omitempty"`
}
// QueryResponse holds the response to /api/records?q=...
type QueryResponse struct {
//
Hits *Hits `json:"hits,omitepmty"`
Links *Links `json:"links,omitempty"`
SortBy string `json:"sortBy,omitempty"`
}
type Hits struct {
Hits []map[string]interface{} `json:"hits,omitempty"`
Total int `json:"total,omitempty"`
}
type Links struct {
Self string `json:"self,omitempty"`
Next string `json:"next,omitempty"`
Prev string `json:"prev,omitempty"`
}
func dbgPrintf(cfg *Config, s string, args ...interface{}) {
if cfg.Debug {
if strings.HasSuffix(s, "\n") {
fmt.Fprintf(os.Stderr, s, args...)
} else {
fmt.Fprintf(os.Stderr, s+"\n", args...)
}
}
}
// errorToString
func errorToString(err error) string {
if err == nil {
return ""
}
return fmt.Sprintf("%s", err)
}
// getJSON sends a request to the InvenioAPI using
// a token, url and values as parameters. It return a
// JSON encoded response as byte slice, the response header and error
func getJSON(token string, uri string) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.Header == nil {
return nil, nil, fmt.Errorf("nil response header")
}
if resp.StatusCode != 200 {
return nil, resp.Header, fmt.Errorf("%s %s", resp.Status, uri)
}
src, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.Header, err
}
return src, resp.Header, nil
}
// getXML sends a request to the Invenio API (e.g. OAI-PMH) using
// a token, url and values as parameters. It returns an
// xml encoded response as byte slice, the response header and error
func getXML(token string, uri string) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-type", "application/xml")
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.Header == nil {
return nil, nil, fmt.Errorf("nil response header")
}
if resp.StatusCode != 200 {
return nil, resp.Header, fmt.Errorf("%s %s", resp.Status, uri)
}
src, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.Header, err
}
return src, resp.Header, nil
}
// getRawFile sends a request to the Invenio API using a token, url
// and values as parameters. It retrieves the file contents and returns
// it as a byte array along with response header and error.
func getRawFile(token string, uri string, contentType string) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-Type", contentType)
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.Header == nil {
return nil, nil, fmt.Errorf("nil response header")
}
if resp.StatusCode != 200 {
return nil, resp.Header, fmt.Errorf("%s %s", resp.Status, uri)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.Header, err
}
return data, resp.Header, err
}
// postJSON takes a token, uri and JSON source as byte slice
// and sends it to the RDM instance for processing.
func postJSON(token string, uri string, src []byte, expectedStatusCode int, debug bool) ([]byte, http.Header, error) {
var (
req *http.Request
err error
)
client := &http.Client{}
if src == nil || len(src) == 0 {
req, err = http.NewRequest("POST", uri, nil)
} else {
req, err = http.NewRequest("POST", uri, bytes.NewBuffer(src))
}
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
if resp != nil && resp.Header != nil {
return nil, resp.Header, err
}
return nil, nil, err
}
defer resp.Body.Close()
if resp.Header == nil {
return nil, nil, fmt.Errorf("nil response header")
}
if debug {
fmt.Fprintf(os.Stderr, "DEBUG postJSON(token, %q, src, true) -> %d, %s\n", uri, resp.StatusCode, resp.Status)
}
if resp.StatusCode != expectedStatusCode {
return nil, resp.Header, fmt.Errorf("POST %s %s, expected %d\n\tpayload\n%s\n", resp.Status, uri, expectedStatusCode, src)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
if resp.Header != nil {
return nil, resp.Header, err
}
return nil, nil, err
}
return data, resp.Header, err
}
// putJSON takes a token, uri and JSON source as byte slice
// and sends it to RDM instance for processing.
func putJSON(token string, uri string, src []byte, expectedStatusCode int, debug bool) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("PUT", uri, bytes.NewBuffer(src))
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.Header == nil {
return nil, nil, fmt.Errorf("nil response header")
}
if debug {
fmt.Fprintf(os.Stderr, "DEBUG putJSON(token, %q, src, true) -> %d, %s\n", uri, resp.StatusCode, resp.Status)
}
if resp.StatusCode != expectedStatusCode {
return nil, resp.Header, fmt.Errorf("PUT %s %s, expected %d\n\tpayload\n%s\n", resp.Status, uri, expectedStatusCode, src)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.Header, err
}
return data, resp.Header, err
}
// patchJSON takes a token, a uri and JSON source as byte slice
// and sends it to RDM instance for processing.
func patchJSON(token string, uri string, src []byte, expectedStatusCode int, debug bool) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("PATCH", uri, bytes.NewBuffer(src))
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.Header == nil {
return nil, nil, fmt.Errorf("nil response header")
}
if resp.StatusCode != expectedStatusCode {
return nil, resp.Header, fmt.Errorf("PATCH %s %s, expected %d\n\tpayload\n%s\n", resp.Status, uri, expectedStatusCode, src)
}
if debug {
fmt.Fprintf(os.Stderr, "DEBUG patchJSON(token, %q, %s, %d, true) ->%d %s\n", uri, src, expectedStatusCode, resp.StatusCode, resp.Status)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.Header, err
}
return data, resp.Header, err
}
// delJSON takes a token, uri and sends it to RDM instance
// for processing.
func delJSON(token string, uri string, expectedStatusCode int, debug bool) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("DELETE", uri, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := client.Do(req)
if err != nil {
return nil, resp.Header, err
}
defer resp.Body.Close()
if resp.StatusCode != expectedStatusCode {
return nil, resp.Header, fmt.Errorf("%s %s, expected %d", resp.Status, uri, expectedStatusCode)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, resp.Header, err
}
return data, resp.Header, err
}
func putFile(token string, uri string, fName string, expectedStatusCode int, debug bool) ([]byte, http.Header, error) {
client := &http.Client{}
src, err := os.ReadFile(fName)
if err != nil {
return nil, nil, err
}
req, err := http.NewRequest("PUT", uri, bytes.NewBuffer(src))
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-Type", "application/octet-stream")
resp, err := client.Do(req)
if err != nil {
return nil, resp.Header, err
}
if debug {
fmt.Fprintf(os.Stderr, "DEBUG putFile(tokan, %q, %q, %d, true) -> %d, %s", uri, fName, expectedStatusCode, resp.StatusCode, resp.Status)
}
if resp.StatusCode != expectedStatusCode {
return nil, resp.Header, fmt.Errorf("%s %s, expected %d", resp.Status, uri, expectedStatusCode)
}
return nil, resp.Header, err
}
func deleteFile(token string, uri string, fName string, expectedStatusCode int, debug bool) ([]byte, http.Header, error) {
client := &http.Client{}
req, err := http.NewRequest("DELETE", uri, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := client.Do(req)
if err != nil {
return nil, resp.Header, err
}
if resp.StatusCode != expectedStatusCode {
return nil, resp.Header, fmt.Errorf("%s %s, expected %d", resp.Status, uri, expectedStatusCode)
}
if debug {
fmt.Fprintf(os.Stderr, "DEBUG deleteFile(token, %q, %q, %d, true) -> %d, %s\n", uri, fName, expectedStatusCode, resp.StatusCode, resp.Status)
}
return nil, resp.Header, err
}
// CheckDOI takes a DOI and does a lookup to see if there are any
// matching .pids.doi.indentifier values.
//
// ```
// doi := "10.1126/science.82.2123.219"
// records, err := CheckDOI(cfg, doi)
// if err != nil {
// // ... handle error ...
// }
// for _, rec := ranges {
// // ... process results ...
// }
// ```
func CheckDOI(cfg *Config, doi string) ([]map[string]interface{}, error) {
// Make sure we have a URL
u, err := url.Parse(cfg.InvenioAPI)
if err != nil {
return nil, err
}
hName := u.Host
// Setup our query parameters, i.e. q=*
// ?q=pids.doi.identifier:"10.1126/science.82.2123.219"&allversions=true
u.Path = "/api/records"
q := url.Values{}
q.Set("q", fmt.Sprintf("pids.doi.identifier:%q", doi))
q.Set("allversions", "true")
uri := fmt.Sprintf("%s?%s", u.String(), q.Encode())
tot := 0
t0 := time.Now()
reportProgress := false
iTime := time.Now()
results := new(QueryResponse)
records := []map[string]interface{}{}
for i := 0; uri != ""; i++ {
if iTime, reportProgress = CheckWaitInterval(iTime, time.Minute); reportProgress || (i == 0) {
log.Printf("%s (%d/%d) %s", hName, len(records), tot, ProgressETA(t0, len(records), tot))
}
dbgPrintf(cfg, "requesting %s", uri)
src, headers, err := getJSON(cfg.InvenioToken, uri)
if err != nil {
return nil, err
}
cfg.rl.FromHeader(headers)
// NOTE: Need to unparse the response structure and
// then extract the IDs from the individual Hits results
if err := JSONUnmarshal(src, &results); err != nil {
return nil, err
}
if results != nil && results.Hits != nil &&
results.Hits.Hits != nil && len(results.Hits.Hits) > 0 {
for _, hit := range results.Hits.Hits {
records = append(records, hit)
}
tot = results.Hits.Total
dbgPrintf(cfg, "(%d/%d) %s\n", len(records), tot, doi)
}
if results.Links != nil && results.Links.Self != results.Links.Next {
uri = results.Links.Next
} else {
uri = ""
}
if uri != "" {
// NOTE: We need to respect the rate limits of RDM's API
cfg.rl.Throttle(i, tot)
}
}
return records, nil
}
// getRecordIdsFromPg will return all record ids found by querying Invenio RDM's Postgres
// database.
func getRecordIdsFromPg(db *sql.DB) ([]string, error) {
if db == nil {
return nil, fmt.Errorf("postgres connection not open")
}
keys := []string{}
stmt := `SELECT json->>'id' AS rdmid
FROM rdm_records_metadata
LEFT JOIN rdm_versions_state
ON (rdm_records_metadata.id = rdm_versions_state.latest_id)
WHERE json->'access'->>'record' = 'public'
AND latest_id IS NOT NULL`
rows, err := db.Query(stmt)
if err != nil {
return nil, err
}
for rows.Next() {
var rdmid string
if err := rows.Scan(&rdmid); err != nil {
return nil, err
}
keys = append(keys, rdmid)
}
err = rows.Err()
return keys, err
}
// getRecordStaleIdsFromPg will return all record ids found by querying Invenio RDM's Postgres
// database.
func getRecordStaleIdsFromPg(db *sql.DB) ([]string, error) {
if db == nil {
return nil, fmt.Errorf("postgres connection not open")
}
keys := []string{}
stmt := `SELECT json->>'id' AS rdmid
FROM rdm_records_metadata
LEFT JOIN rdm_versions_state
ON (rdm_records_metadata.id = rdm_versions_state.latest_id)
WHERE json->'access'->>'record' = 'public'
AND latest_id IS NULL`
rows, err := db.Query(stmt)
if err != nil {
return nil, err
}
for rows.Next() {
var rdmid string
if err := rows.Scan(&rdmid); err != nil {
return nil, err
}
keys = append(keys, rdmid)
}
err = rows.Err()
return keys, err
}
// getModifiedRecordIdsFromPg will return of record ids found in date range by querying
// Invenio RDM's Postgres database.
func getModifiedRecordIdsFromPg(db *sql.DB, startDate string, endDate string) ([]string, error) {
if db == nil {
return nil, fmt.Errorf("postgres connection not open")
}
keys := []string{}
/*
// Filter records based on the .metadata.dates found in the JSON
stmt := fmt.Sprintf(`with t as (
select json->>'id' as rdmid,
json->'access'->>'record' as status,
jsonb_path_query(json->'metadata'->'dates', '$.type')::jsonb->>'id' as date_type,
to_date(jsonb_path_query(json->'metadata'->'dates', '$.date') #>> '{}', 'YYYY-MM-DD') as dt
from rdm_records_metadata
where json->'access'->>'record' = 'public'
) select rdmid
from t
where date_type = 'updated'
and (dt between '%s' and '%s')
order by dt;`, startDate, endDate)
*/
stmt := `SELECT json->>'id' AS rdmid FROM rdm_records_metadata
WHERE json->'access'->>'record' = 'public' AND (updated between $1 AND $2)`
rows, err := db.Query(stmt, startDate, endDate)
if err != nil {
return nil, err
}
for rows.Next() {
var rdmid string
if err := rows.Scan(&rdmid); err != nil {
return nil, err
}
keys = append(keys, rdmid)
}
err = rows.Err()
return keys, err
}
// GetRecordIds takes a configuration object, contacts am RDM
// instance and returns a list of ids and error. If the RDM
// database connection is included in the configuration the faster
// method of querrying Postgres is used, otherwise OAI-PMH is used
// to get the id list.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set. It is highly recommended that the
// InvenioDbUser, InvenioDbPassword and InvenioDbHost is configured.
//
// NOTE: This method relies on OAI-PMH, this is a rate limited process
// so results can take quiet some time.
func GetRecordIds(cfg *Config) ([]string, error) {
return getRecordIdsFromPg(cfg.pgDB)
}
// GetRecordStaleIds takes a configuration object, contacts am RDM
// instance and returns a list of ids and error. If the RDM
// database connection is included in the configuration the faster
// method of querrying Postgres is used, otherwise OAI-PMH is used
// to get the id list.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set. It is highly recommended that the
// InvenioDbUser, InvenioDbPassword and InvenioDbHost is configured.
//
// NOTE: This method relies on OAI-PMH, this is a rate limited process
// so results can take quiet some time.
func GetRecordStaleIds(cfg *Config) ([]string, error) {
return getRecordStaleIdsFromPg(cfg.pgDB)
}
// GetModifiedRecordIds takes a configuration object, contacts am RDM
// instance and returns a list of ids created, deleted or updated in
// the time range specififed. I problem is encountered returns an error.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// NOTE: This method relies on OAI-PMH, this is a rate limited process
// so results can take quiet some time.
func GetModifiedRecordIds(cfg *Config, start string, end string) ([]string, error) {
if start == "" {
start = time.Now().Format("2006-01-02")
}
if end == "" {
end = time.Now().Format("2006-01-02")
}
return getModifiedRecordIdsFromPg(cfg.pgDB, start, end)
}
// getRecordFromPg will return all record ids found by querying Invenio RDM's Postgres
// database.
func getRecordFromPg(db *sql.DB, rdmID string, draft bool) (*simplified.Record, error) {
var (
err error
)
if db == nil {
return nil, fmt.Errorf("postgres connection is not open")
}
stmt := `SELECT id as record_id, jsonb_strip_nulls(jsonb_build_object(
'created', created::timestamp (0) with time zone,
'updated', updated::timestamp (0) with time zone,
'is_published', json->'is_publshed',
'metadata', json->'metadata',
'access', json->'access',
'files', json->'files',
'parent', json->'parent',
'id', json->'id',
'custom_fields', json->'custom_fields',
'status', json->'status',
'revision_id', json->'revision_id',
'pids', json->'pids'
)) as record
FROM rdm_records_metadata
WHERE json->>'id' = $1 LIMIT 1;`
if draft {
stmt = `SELECT id as uuid, json AS record
FROM rdm_drafts_metadata
WHERE json->>'id' = $1 LIMIT 1;`
}
rows, err := db.Query(stmt, rdmID)
if err != nil {
return nil, err
}
defer rows.Close()
var (
src []byte
rdmUUID string
)
for rows.Next() {
if err := rows.Scan(&rdmUUID, &src); err != nil {
return nil, err
}
}
err = rows.Err()
if err != nil {
return nil, err
}
rec := &simplified.Record{}
err = JSONUnmarshal(src, &rec)
if err != nil {
return nil, err
}
//fmt.Fprintf(os.Stderr, "DEBUG (rdmID) %q -> (uuid) %q\n", rdmID, uuid)
// Now we try to add Files.Entries to Record.
//
// NOTE: We use the UUID to avoid a join with our rdm_recorrds_metadata table, this speeds up
// the query by a factor of three.
stmt = `SELECT
(CASE WHEN fd.json->'files'->>'default_preview' = fo.key THEN TRUE else FALSE END) AS is_default_preview,
fo.key AS key
FROM rdm_records_files fd
JOIN files_object fo ON (fd.key = fo.key)
WHERE fd.record_id = $1
ORDER BY fo.key ASC`
entries, err := db.Query(stmt, rdmUUID)
if err != nil {
return nil, err
}
defer entries.Close()
var (
isDefaultPreview bool
fName string
)
fileEntries := map[string]*simplified.Entry{}
for entries.Next() {
if err := entries.Scan(&isDefaultPreview, &fName); err != nil {
return nil, err
}
fileEntries[fName] = &simplified.Entry{
Key: fName,
}
if isDefaultPreview {
if rec.Files == nil {
rec.Files = &simplified.Files{}
}
rec.Files.DefaultPreview = fName
}
}
if len(fileEntries) > 0 {
if rec.Files == nil {
rec.Files = &simplified.Files{}
}
rec.Files.Entries = fileEntries
}
return rec, err
}
// getRecordVersionsFromPg will return all record versions by querying Invenio RDM's Postgres
// database.
func getRecordVersionsFromPg(db *sql.DB, rdmID string) ([]*map[string]interface{}, error) {
var (
err error
)
if db == nil {
return nil, fmt.Errorf("postgres connection is not open")
}
stmt := `SELECT jsonb_strip_nulls(jsonb_build_object(
'id', json->>'id',
'metadata', json,
'created', created,
'updated', updated,
'version', version_id,
'index', index,
'uuid_id', id,
'parent_id', parent_id,
'bucket_id', bucket_id,
'operation_type', operation_type
)) AS src
FROM rdm_records_metadata_version
WHERE json->>'id' = $1
ORDER BY version_id`
rows, err := db.Query(stmt, rdmID)
if err != nil {
//fmt.Fprintf(os.Stderr, "%s", stmt)
return nil, err
}
defer rows.Close()
var src []byte
records := []*map[string]interface{}{}
for rows.Next() {
if err := rows.Scan(&src); err != nil {
return nil, err
}
rec := &map[string]interface{}{}
err = JSONUnmarshal(src, &rec)
if err != nil {
return nil, err
}
records = append(records, rec)
}
err = rows.Err()
if err != nil {
return nil, err
}
return records, err
}
// GetRecord takes a configuration object and record id,
// contacts an RDM instance and returns a simplified record
// and an error value.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id := "qez01-2309a"
// record, err := GetRecord(cfg, id, false)
// if err != nil {
// // ... handle error ...
// }
// ```
func GetRecord(cfg *Config, id string, draft bool) (*simplified.Record, error) {
return getRecordFromPg(cfg.pgDB, id, draft)
}
// GetRecordVersions takes a configuration object and record id,
// queries the Postgres database and returns the matching json
// blogs in the rdm_records_medata_version table as a JSON array.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id := "qez01-2309a"
// record, err := GetRecordVersions(cfg, id)
// if err != nil {
// // ... handle error ...
// }
// ```
func GetRecordVersions(cfg *Config, id string) ([]*map[string]interface{}, error) {
return getRecordVersionsFromPg(cfg.pgDB, id)
}
// GetFile takes a configuration object, record id and filename,
// contacts an RDM instance and returns the specific file metadata
// and an error value.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id := "qez01-2309a"
// fName := "article.pdf"
// entry, err := GetFile(cfg, id, fName)
//
// if err != nil {
// // ... handle error ...
// }
//
// ```
func GetFile(cfg *Config, id string, fName string) (*simplified.Entry, error) {
// Make sure we have a valid URL
u, err := url.Parse(cfg.InvenioAPI)
if err != nil {
return nil, err
}
// Setup API request for a record
uri := fmt.Sprintf("%s/api/records/%s/files/%s", u.String(), id, fName)
src, headers, err := getJSON(cfg.InvenioToken, uri)
if err != nil {
return nil, err
}
cfg.rl.FromHeader(headers)
obj := new(simplified.Entry)
if err := JSONUnmarshal(src, &obj); err != nil {
return nil, err
}
return obj, nil
}
// RetrieveFile takes a configuration object, record id and filename,
// contacts an RDM instance and returns the specific file
// and an error value.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id := "qez01-2309a"
// fName := "article.pdf"
// data, err := RetrieveFile(cfg, id, fName)
// if err != nil {
// // ... handle error ...
// }
// os.WriteFile(fName, data, 0664)
// ```
func RetrieveFile(cfg *Config, id string, fName string) ([]byte, error) {
// Make sure we have a valid URL
u, err := url.Parse(cfg.InvenioAPI)
if err != nil {
return nil, err
}
// NOTE: We need to get the metadata to know the mime-type to request.
obj, err := GetFile(cfg, id, fName)
if err != nil {
return nil, err
}
// Setup API request for a record
uri := fmt.Sprintf("%s/records/%s/files/%s?download=1", u.String(), id, fName)
data, headers, err := getRawFile(cfg.InvenioToken, uri, obj.MimeType)
if err != nil {
return nil, err
}
cfg.rl.FromHeader(headers)
return data, nil
}
// GetVersions takes a configuration object and record id,
// contacts an RDM instance and returns the versons metadata
// and an error value.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id := "qez01-2309a"
// versions, err := GetVersions(cfg, id)
// if err != nil {
// // ... handle error ...
// }
//
// ```
func GetVersions(cfg *Config, id string) (map[string]interface{}, error) {
// FIXME: Need to figure out how to get versions via database access.
// Make sure we have a valid URL
u, err := url.Parse(cfg.InvenioAPI)
if err != nil {
return nil, err
}
// Setup API request for a record
uri := fmt.Sprintf("%s/api/records/%s/versions", u.String(), id)
src, headers, err := getJSON(cfg.InvenioToken, uri)
if err != nil {
return nil, err
}
cfg.rl.FromHeader(headers)
obj := map[string]interface{}{}
if err := JSONUnmarshal(src, &obj); err != nil {
return nil, err
}
return obj, nil
}
// GetVersionLatest takes a configuration object and record id,
// contacts an RDM instance and returns the versons metadata
// and an error value.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id := "qez01-2309a"
// versions, err := GetVersionLatest(cfg, id)
// if err != nil {
// // ... handle error ...
// }
//
// ```
func GetVersionLatest(cfg *Config, id string) (map[string]interface{}, error) {
// FIXME: Need to figure out how to get latest version via database access
// Make sure we have a valid URL
u, err := url.Parse(cfg.InvenioAPI)
if err != nil {
return nil, err
}
// Setup API request for a record
uri := fmt.Sprintf("%s/api/records/%s/versions/latest", u.String(), id)
src, headers, err := getJSON(cfg.InvenioToken, uri)
if err != nil {
return nil, err
}
cfg.rl.FromHeader(headers)
obj := map[string]interface{}{}
if err := JSONUnmarshal(src, &obj); err != nil {
return nil, err
}
return obj, nil
}
// NewRecord takes a configuration object and JSON record values.
// It contacts an RDM instance and create a new record return the
// JSON for the newly created record with a record id. When records
// are created they are in "draft" state.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// fName := "new_record.json" // A new record in JSON
// src, _ := os.ReadFile(fName)
// record, err := NewRecord(cfg, src)
// if err != nil {
// // ... handle error ...
// }
// fmt.Printf("%+v\n", record)
// ```
func NewRecord(cfg *Config, src []byte) (map[string]interface{}, error) {
// Make sure we have a valid URL
u, err := url.Parse(cfg.InvenioAPI)
if err != nil {
return nil, err
}
// Setup API request for a new record, the JSON returned is supposed
// to contain the record id and rest of record.
uri := fmt.Sprintf("%s/api/records", u.String())
src, headers, err := postJSON(cfg.InvenioToken, uri, src, http.StatusCreated, false)
if err != nil {
return nil, err
}
cfg.rl.FromHeader(headers)
obj := map[string]interface{}{}
if err := JSONUnmarshal(src, &obj); err != nil {
return nil, err
}
return obj, nil
}
// NewRecordVersion takes a configuration object and record id to
// create the new version draft. The returns JSON record values includes
// the new record id identifying the new version.
//
// The configuration object must have the InvenioAPI and
// InvenioToken attributes set.
//
// ```
// cfg, _ := LoadConfig("config.json")
// id = "38rg4-36m04"
// record, err := NewRecordVersion(cfg, id)
// if err != nil {
// // ... handle error ...
// }
// fmt.Printf("%+v\n", record)