-
Notifications
You must be signed in to change notification settings - Fork 2
/
gocontentfulvolib.go
1784 lines (1674 loc) · 52.7 KB
/
gocontentfulvolib.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
// Code generated by https://github.com/foomo/gocontentful v1.0.23 - DO NOT EDIT.
package testapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"os"
"regexp"
"strings"
"sync"
"time"
"unicode"
"github.com/foomo/contentful"
"golang.org/x/sync/errgroup"
)
type cacheEntryMaps struct {
brand map[string]*CfBrand
category map[string]*CfCategory
product map[string]*CfProduct
}
type ClientMode string
type ContentfulCache struct {
assets assetCacheMap
contentTypes []string
entryMaps cacheEntryMaps
idContentTypeMap map[string]string
parentMap map[string][]EntryReference
}
type ContentfulCacheMutex struct {
fullCacheGcLock sync.RWMutex
sharedDataGcLock sync.RWMutex
assetsGcLock sync.RWMutex
idContentTypeMapGcLock sync.RWMutex
parentMapGcLock sync.RWMutex
brandGcLock sync.RWMutex
categoryGcLock sync.RWMutex
productGcLock sync.RWMutex
}
type assetCacheMap map[string]*contentful.Asset
type ContentfulClient struct {
Cache *ContentfulCache
cacheInit bool
cacheMutex *ContentfulCacheMutex
cacheQueue chan struct{}
cacheDone chan struct{}
cacheUpdateTimeout int64
cacheWorkerOnce sync.Once
clientMode ClientMode
Client *contentful.Contentful
locales []Locale
logFn func(
fields map[string]interface{},
level int,
args ...interface{},
)
logLevel int
optimisticPageSize uint16
SpaceID string
offline bool
offlineTemp offlineTemp
sync bool
syncToken string
textJanitor bool
}
type offlineTemp struct {
Entries []contentful.Entry `json:"entries"`
Assets []contentful.Asset `json:"assets"`
}
type ContentTypeResult struct {
EntryID string
ContentType string
References map[string][]EntryReference
}
type ContentTypeInfo struct {
ContentType string
Title string
Description string
}
type ContentTypeInfoMap map[string]ContentTypeInfo
type EntryReference struct {
ContentType string
ID string
VO interface{}
FromField string
}
type BrokenReference struct {
ParentID string `json:"parentId"`
ParentType string `json:"parentType"`
FromField string `json:"fromField"`
ChildID string `json:"childId"`
}
type ImageResolverFunc func(assetID string, locale Locale) (attrs map[string]string, customHTML string, resolveError error)
type EntryLinkResolverFunc func(entryID string, locale Locale) (resolvedAttrs map[string]string, resolveError error)
type LinkResolverFunc func(url string) (resolvedAttrs map[string]string, resolveError error)
type EmbeddedEntryResolverFunc func(entryID string, locale Locale) (htmlSnippet string, resolveError error)
type Locale string
const (
ClientModeCDA ClientMode = "CDA"
ClientModeCPA ClientMode = "CPA"
ClientModeCMA ClientMode = "CMA"
)
const (
LogDebug = 0
LogInfo = 1
LogWarn = 2
LogError = 3
)
const SpaceLocaleGerman Locale = "de"
const SpaceLocaleFrench Locale = "fr"
var SpaceLocales = []Locale{
"de",
"fr",
}
const DefaultLocale Locale = SpaceLocaleGerman
var localeFallback = map[Locale]Locale{SpaceLocaleGerman: "", SpaceLocaleFrench: ""}
const (
assetPageSize = 1000
assetWorkerType = "_asset"
)
const cacheUpdateConcurrency = 4
const (
sysTypeEntry = "Entry"
sysTypeAsset = "Asset"
sysTypeDeletedEntry = "DeletedEntry"
sysTypeDeletedAsset = "DeletedAsset"
)
var (
ErrLocaleUnsupported = errors.New("locale not supported by this space")
ErrNotSet = errors.New("field value not set")
ErrNotSetNoFallback = errors.New("field value not set and no fallback locale available")
ErrRefNotIncludes = errors.New("referenced entry not found in includes")
ErrNoTypeOfRefEntry = errors.New("couldn't get contentType of referenced entry")
ErrNoTypeOfRefAsset = errors.New("couldn't get contentType of referenced asset")
InfoUpdatedEntityCache = "updated cache for entity"
InfoCachedAllEntries = "cached all entries of content type"
InfoCachedAllAssets = "cached all assets"
InfoFallingBackToFile = "gonna use a local file"
InfoLoadingFromFile = "loading space from local file"
InfoCacheWorkerStart = "contentful cache worker starting"
InfoCacheUpdateQueued = "contentful cache update queued"
InfoCacheUpdateCanceled = "contentful cache update canceled"
InfoCacheUpdateDone = "contentful cache update returning"
InfoCacheUpdateSkipped = "contentful cache update skipped, already one in the queue"
InfoOfflineEntitiesLoaded = "downloaded entries and assets from offline file"
InfoPreservingExistingCache = "could not connect for cache update, preserving the existing cache"
InfoUpdateCacheTime = "space caching done, time recorded"
ErrorEnvironmentSetToMaster = "environment was empty string, set to master"
ErrorEntryIsNil = "entry is nil"
ErrorEntrySysIsNil = "entry.Sys is nil"
ErrorEntrySysContentTypeIsNil = "entry.Sys.ContentType is nil"
ErrorEntrySysContentTypeSysIsNil = "entry.Sys.ContentType.Sys is nil"
)
var spaceContentTypes = []string{ContentTypeBrand, ContentTypeCategory, ContentTypeProduct}
var SpaceContentTypeInfoMap = ContentTypeInfoMap{
"brand": ContentTypeInfo{
ContentType: "brand",
Title: "Brand",
Description: "",
},
"category": ContentTypeInfo{
ContentType: "category",
Title: "Category",
Description: "",
},
"product": ContentTypeInfo{
ContentType: "product",
Title: "Product",
Description: "",
},
}
func (cc *ContentfulClient) BrokenReferences() (brokenReferences []BrokenReference) {
if cc.Cache == nil || cc.cacheMutex == nil {
return
}
cc.cacheMutex.parentMapGcLock.Lock()
defer cc.cacheMutex.parentMapGcLock.Unlock()
cc.cacheMutex.idContentTypeMapGcLock.Lock()
defer cc.cacheMutex.idContentTypeMapGcLock.Unlock()
for childID, parents := range cc.Cache.parentMap {
if _, okGotEntry := cc.Cache.idContentTypeMap[childID]; !okGotEntry {
for _, parent := range parents {
brokenReferences = append(brokenReferences, BrokenReference{
ParentID: parent.ID,
ParentType: parent.ContentType,
FromField: parent.FromField,
ChildID: childID,
})
}
}
}
return
}
func (cc *ContentfulClient) CacheHasContentType(contentTypeID string) bool {
if cc.Cache == nil {
return false
}
cc.cacheMutex.sharedDataGcLock.RLock()
defer cc.cacheMutex.sharedDataGcLock.RUnlock()
for _, cachedContentType := range cc.Cache.contentTypes {
if cachedContentType == contentTypeID {
return true
}
}
return false
}
func (cc *ContentfulClient) ClientStats() {
if cc == nil {
cc.logFn(nil, LogWarn, "ClientStats: no client available")
return
}
cc.cacheMutex.sharedDataGcLock.RLock()
defer cc.cacheMutex.sharedDataGcLock.RUnlock()
if cc.logFn != nil {
fieldsMap := map[string]interface{}{
"space ID": cc.SpaceID,
"environment": cc.Client.Environment,
"clientMode": cc.clientMode,
"contentTypes": strings.Join(cc.Cache.contentTypes, ","),
"locales": cc.locales,
"cached": cc.cacheInit,
}
if cc.cacheInit {
fieldsMap["cache asset count"] = len(cc.Cache.assets)
fieldsMap["cache entry count"] = len(cc.Cache.idContentTypeMap)
fieldsMap["cache parentMap children"] = len(cc.Cache.parentMap)
cc.cacheMutex.parentMapGcLock.RLock()
defer cc.cacheMutex.parentMapGcLock.RUnlock()
referenceCount := 0
for _, parents := range cc.Cache.parentMap {
referenceCount += len(parents)
}
fieldsMap["cache parentMap parents"] = referenceCount
}
cc.logFn(fieldsMap, LogInfo, "Contentful ClientStats")
}
}
func (ref ContentfulReferencedEntry) ContentType() (contentType string) {
return ref.Entry.Sys.ContentType.Sys.ID
}
func (cc *ContentfulClient) DeleteAsset(asset *contentful.Asset) error {
if cc == nil || cc.Client == nil {
return errors.New("DeleteAsset: No client available")
}
if cc.clientMode != ClientModeCMA {
return errors.New("DeleteAsset: Only available in ClientModeCMA")
}
errUnpublish := cc.Client.Assets.Unpublish(cc.SpaceID, asset)
if errUnpublish != nil && !strings.Contains(errUnpublish.Error(), "Not published") {
return errUnpublish
}
errDelete := cc.Client.Assets.Delete(cc.SpaceID, asset)
if errDelete != nil {
return errDelete
}
return nil
}
func (cc *ContentfulClient) DeleteAssetFromCache(key string) error {
return cc.deleteAssetFromCache(key)
}
func (cc *ContentfulClient) DisableTextJanitor() {
cc.textJanitor = false
}
func (cc *ContentfulClient) EnableTextJanitor() {
cc.textJanitor = true
}
func (cc *ContentfulClient) GetAllAssets() (map[string]*contentful.Asset, error) {
return cc.getAllAssets(true)
}
func (cc *ContentfulClient) GetAssetByID(id string, forceNoCache ...bool) (*contentful.Asset, error) {
if cc == nil || cc.Client == nil {
return nil, errors.New("GetAssetByID: No client available")
}
cc.cacheMutex.sharedDataGcLock.Lock()
cacheInit := cc.cacheInit
cc.cacheMutex.sharedDataGcLock.Unlock()
cc.cacheMutex.assetsGcLock.Lock()
defer cc.cacheMutex.assetsGcLock.Unlock()
if cacheInit && cc.Cache.assets != nil && (len(forceNoCache) == 0 || !forceNoCache[0]) {
asset, okAsset := cc.Cache.assets[id]
if okAsset {
return asset, nil
} else {
return nil, errors.New("GetAssetByID: not found")
}
}
col := cc.Client.Assets.List(cc.SpaceID)
col.Query.Locale("*").Equal("sys.id", id)
_, err := col.Next()
if err != nil {
return nil, err
}
if len(col.Items) == 0 {
return nil, errors.New("GetAssetByID: Not found " + id)
}
item := col.Items[0]
asset := contentful.Asset{}
byt, err := json.Marshal(item)
if err != nil {
return nil, err
}
err = json.Unmarshal(byt, &asset)
if err != nil {
return nil, err
}
for _, loc := range []Locale{SpaceLocaleGerman, SpaceLocaleFrench} {
if _, ok := asset.Fields.File[string(loc)]; ok {
asset.Fields.File[string(loc)].URL = "https:" + asset.Fields.File[string(loc)].URL
}
}
return &asset, nil
}
func (cc *ContentfulClient) GetContentTypeOfID(id string) (string, error) {
if cc == nil || cc.Client == nil {
return "", errors.New("GetContentTypeOfID: No client available")
}
if cc.cacheInit {
okVo := false
cc.cacheMutex.brandGcLock.Lock()
_, okVo = cc.Cache.entryMaps.brand[id]
cc.cacheMutex.brandGcLock.Unlock()
if okVo {
return ContentTypeBrand, nil
}
cc.cacheMutex.categoryGcLock.Lock()
_, okVo = cc.Cache.entryMaps.category[id]
cc.cacheMutex.categoryGcLock.Unlock()
if okVo {
return ContentTypeCategory, nil
}
cc.cacheMutex.productGcLock.Lock()
_, okVo = cc.Cache.entryMaps.product[id]
cc.cacheMutex.productGcLock.Unlock()
if okVo {
return ContentTypeProduct, nil
}
return "", fmt.Errorf("GetContentTypeOfID: %s Not found in cache", id)
}
col := cc.Client.Entries.List(cc.SpaceID)
col.Query.Include(0).Equal("sys.id", id)
_, err := col.GetAll()
if err != nil {
return "", errors.New("GetContentTypeOfID: " + err.Error())
}
if len(col.Items) == 0 {
return "", fmt.Errorf("GetContentTypeOfID: %s Not found online", id)
}
var vo genericEntryNoFields
byteArray, _ := json.Marshal(col.Items[0])
err = json.NewDecoder(bytes.NewReader(byteArray)).Decode(&vo)
if err != nil {
return "", errors.New("GetContentTypeOfID: " + err.Error())
}
return vo.Sys.ContentType.Sys.ID, nil
}
func (ref *EntryReference) GetParents(cc *ContentfulClient) (parents []EntryReference, err error) {
if ref == nil {
return nil, errors.New("GetParents: reference is nil")
}
if cc == nil {
return nil, errors.New("GetParents: Contentful client is nil")
}
if cc.Cache == nil {
return nil, errors.New("GetParents: only available in cached mode")
}
return cc.Cache.parentMap[ref.ID], nil
}
func HtmlToRichText(htmlSrc string) *RichTextNode {
htmlClean := strings.TrimSpace(htmlSrc)
htmlClean = strings.ReplaceAll(htmlClean, ` `, ` `)
htmlClean = strings.ReplaceAll(htmlClean, "&", "&")
htmlClean = strings.ReplaceAll(htmlClean, "\t", "")
htmlClean = regexp.MustCompile(`[\s]{2,}`).ReplaceAllString(htmlClean, " ")
re := regexp.MustCompile(`>([^\n])`)
htmlClean = re.ReplaceAllString(htmlClean, fmt.Sprintf(">\n"+`$1`))
re = regexp.MustCompile(`(.{1})<`)
htmlClean = re.ReplaceAllString(htmlClean, `$1`+"\n<")
htmlLines := strings.Split(htmlClean, "\n")
rtnd := &RichTextNode{
NodeType: RichTextNodeDocument,
}
var isBasic bool
rtnd.Content, _, isBasic = richTextHtmlLinesToNode(htmlLines, 0, "", nil, true)
if isBasic {
basicRich := &RichTextNode{
NodeType: RichTextNodeDocument,
Content: rtnd.Content,
}
return basicRich
}
return rtnd
}
func NewAssetFromURL(id string, uploadUrl string, imageFileType string, title string, locale ...Locale) *contentful.Asset {
autoID := fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond))
if id == "" {
id = autoID
}
if title == "" {
title = id
}
var loc Locale
if len(locale) != 0 {
loc = locale[0]
if localeFallback[loc] != "" {
return nil
}
} else {
loc = DefaultLocale
}
asset := &contentful.Asset{
Sys: &contentful.Sys{
ID: id,
},
Fields: &contentful.FileFields{
File: map[string]*contentful.File{
string(loc): {
UploadURL: uploadUrl,
ContentType: imageFileType,
Name: id,
},
},
Title: map[string]string{
string(loc): title,
},
},
}
return asset
}
func NewContentfulClient(spaceID string, clientMode ClientMode, clientKey string, optimisticPageSize uint16, logFn func(fields map[string]interface{}, level int, args ...interface{}), logLevel int, debug bool) (*ContentfulClient, error) {
if spaceID == "" {
return nil, errors.New("NewContentfulClient: SpaceID cannot be empty")
}
if clientMode != ClientModeCMA && clientMode != ClientModeCPA && clientMode != ClientModeCDA {
return nil, errors.New("NewContentfulClient: clientMode not supported")
}
if optimisticPageSize < 10 {
return nil, errors.New("NewContentfulClient: optimisticPageSize must be 10 or bigger")
}
if logLevel < 0 || logLevel > 3 {
return nil, errors.New("NewContentfulClient: logLevel must be between 0 and 3")
}
if clientKey == "" {
return nil, errors.New("NewContentfulClient: Please provide an API key")
}
apiClient, err := getContentfulAPIClient(clientMode, clientKey)
if err != nil {
return nil, err
}
apiClient.Debug = debug
cc := &ContentfulClient{
clientMode: clientMode,
Client: apiClient,
Cache: &ContentfulCache{
assets: assetCacheMap{},
contentTypes: []string{},
entryMaps: cacheEntryMaps{},
idContentTypeMap: map[string]string{},
parentMap: map[string][]EntryReference{},
},
cacheMutex: &ContentfulCacheMutex{
fullCacheGcLock: sync.RWMutex{},
sharedDataGcLock: sync.RWMutex{},
assetsGcLock: sync.RWMutex{},
idContentTypeMapGcLock: sync.RWMutex{},
parentMapGcLock: sync.RWMutex{},
brandGcLock: sync.RWMutex{},
categoryGcLock: sync.RWMutex{},
productGcLock: sync.RWMutex{},
},
cacheQueue: make(chan struct{}, 1),
cacheDone: make(chan struct{}, 1),
cacheUpdateTimeout: 120,
locales: []Locale{SpaceLocaleGerman, SpaceLocaleFrench},
logFn: logFn,
logLevel: logLevel,
optimisticPageSize: optimisticPageSize,
SpaceID: spaceID,
sync: clientMode == ClientModeCDA,
}
_, err = cc.Client.Spaces.Get(spaceID)
if err != nil {
_, ok := err.(contentful.NotFoundError)
if ok {
return nil, errors.New("NewContentfulClient: That is not the space you're looking for")
}
return nil, errors.New("NewContentfulClient: " + err.Error())
}
return cc, nil
}
func NewOfflineContentfulClient(filename string, logFn func(fields map[string]interface{}, level int, args ...interface{}), logLevel int, cacheAssets bool, textJanitor bool) (*ContentfulClient, error) {
offlineTemp, err := getOfflineSpaceFromFile(filename)
if err != nil {
return nil, fmt.Errorf("NewOfflineContentfulClient could not parse space export file: %v", err)
}
cc := &ContentfulClient{
clientMode: ClientModeCDA,
Client: contentful.NewCDA(""),
Cache: &ContentfulCache{
contentTypes: []string{},
idContentTypeMap: map[string]string{},
parentMap: map[string][]EntryReference{},
},
cacheMutex: &ContentfulCacheMutex{
fullCacheGcLock: sync.RWMutex{},
sharedDataGcLock: sync.RWMutex{},
assetsGcLock: sync.RWMutex{},
idContentTypeMapGcLock: sync.RWMutex{},
parentMapGcLock: sync.RWMutex{},
brandGcLock: sync.RWMutex{},
categoryGcLock: sync.RWMutex{},
productGcLock: sync.RWMutex{},
},
cacheQueue: make(chan struct{}, 1),
cacheDone: make(chan struct{}, 1),
cacheUpdateTimeout: 120,
locales: []Locale{
SpaceLocaleGerman,
SpaceLocaleFrench,
},
logFn: logFn,
logLevel: logLevel,
SpaceID: "OFFLINE",
offline: true,
offlineTemp: *offlineTemp,
textJanitor: textJanitor,
}
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"entries": len(offlineTemp.Entries), "assets": len(offlineTemp.Assets)}, LogInfo, InfoLoadingFromFile)
}
err = cc.UpdateCache(context.TODO(), spaceContentTypes, cacheAssets)
if err != nil {
return nil, fmt.Errorf("NewOfflineContentfulClient could not cache offline space: %v", err)
}
return cc, nil
}
func RichTextToHtml(rt interface{}, linkResolver LinkResolverFunc, entryLinkResolver EntryLinkResolverFunc, imageResolver ImageResolverFunc, embeddedEntryResolver EmbeddedEntryResolverFunc, locale Locale) (string, error) {
w := bytes.NewBuffer([]byte{})
node := &RichTextGenericNode{}
byt, err := json.Marshal(rt)
if err != nil {
return "", err
}
err = json.Unmarshal(byt, node)
if err != nil {
return "", err
}
err = node.richTextRenderHTML(w, linkResolver, entryLinkResolver, imageResolver, embeddedEntryResolver, locale)
if err != nil {
return "", err
}
out := w.String()
if out == "<p></p>" {
return "", nil
}
return out, nil
}
func (cc *ContentfulClient) SetCacheUpdateTimeout(seconds int64) {
cc.cacheUpdateTimeout = seconds
}
func (cc *ContentfulClient) SetEnvironment(environment string) {
if environment == "" {
cc.Client.Environment = "master"
if cc.logFn != nil && cc.logLevel <= LogWarn {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogWarn, ErrorEnvironmentSetToMaster)
}
return
}
cc.Client.Environment = environment
}
func (cc *ContentfulClient) SetOfflineFallback(filename string) error {
offlineTemp, err := getOfflineSpaceFromFile(filename)
if err != nil {
return err
}
cc.offlineTemp = *offlineTemp
return nil
}
func (cc *ContentfulClient) SetSyncMode(mode bool) error {
cc.cacheMutex.sharedDataGcLock.RLock()
defer cc.cacheMutex.sharedDataGcLock.RUnlock()
if cc.offline {
return errors.New("SetSyncMode: client is set offline, can't enable sync")
}
cc.sync = mode
return nil
}
func (cc *ContentfulClient) ResetSync() {
cc.syncToken = ""
}
func (cc *ContentfulClient) UpdateCache(ctx context.Context, contentTypes []string, cacheAssets bool) error {
cc.cacheMutex.sharedDataGcLock.RLock()
ctxAtWork, cancel := context.WithTimeout(ctx, time.Second*time.Duration(cc.cacheUpdateTimeout))
defer cancel()
localOffline := cc.offline
cc.cacheMutex.sharedDataGcLock.RUnlock()
if localOffline {
ctxAtWork = ctx
}
if !localOffline {
time.Sleep(time.Second * 2)
}
if contentTypes == nil {
contentTypes = spaceContentTypes
} else {
for _, contentType := range contentTypes {
if !stringSliceContains(spaceContentTypes, contentType) {
return fmt.Errorf("UpdateCache: Content Type %q not available in this space", contentType)
}
}
}
if cc.sync {
return cc.syncCache(ctxAtWork, contentTypes)
}
cc.cacheWorkerOnce.Do(func() {
go cc.cacheWorker(ctx, contentTypes, cacheAssets)
})
if len(cc.cacheQueue) == 0 {
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoCacheUpdateQueued)
}
cc.cacheQueue <- struct{}{}
select {
case <-cc.cacheDone:
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoCacheUpdateDone)
}
case <-ctxAtWork.Done():
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoCacheUpdateCanceled)
}
}
cc.cacheInit = true
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoCacheUpdateDone)
}
return nil
}
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoCacheUpdateSkipped)
}
return nil
}
func (cc *ContentfulClient) syncCache(ctx context.Context, contentTypes []string) error {
start := time.Now()
cc.cacheMutex.sharedDataGcLock.Lock()
cc.Cache.contentTypes = contentTypes
cc.cacheMutex.sharedDataGcLock.Unlock()
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "syncCache"}, LogInfo, InfoCacheUpdateQueued)
}
for {
col := cc.Client.Entries.Sync(
cc.SpaceID,
cc.syncToken == "",
cc.syncToken,
)
col.GetAll()
cc.cacheMutex.sharedDataGcLock.Lock()
cc.syncToken = col.SyncToken
cc.cacheInit = true
cc.cacheMutex.sharedDataGcLock.Unlock()
if len(col.Items) == 0 {
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"time elapsed": fmt.Sprint(time.Since(start)), "task": "syncCache"}, LogInfo, InfoUpdateCacheTime)
}
return nil
}
var entries []*contentful.Entry
var assets []*contentful.Asset
for _, item := range col.Items {
entry := &contentful.Entry{}
byteArray, _ := json.Marshal(item)
errEntry := json.NewDecoder(bytes.NewReader(byteArray)).Decode(entry)
if errEntry == nil && entry.Sys != nil && (entry.Sys.Type == sysTypeAsset || entry.Sys.Type == sysTypeDeletedAsset) {
asset := &contentful.Asset{}
errAsset := json.NewDecoder(bytes.NewReader(byteArray)).Decode(asset)
if errAsset != nil {
continue
}
if asset.Sys != nil {
assets = append(assets, asset)
}
continue
}
if entry.Sys != nil {
entries = append(entries, entry)
}
}
for _, entry := range entries {
switch entry.Sys.Type {
case sysTypeEntry:
if !stringSliceContains(spaceContentTypes, entry.Sys.ContentType.Sys.ID) {
continue
}
updateCacheForContentTypeAndEntity(ctx, cc, entry.Sys.ContentType.Sys.ID, entry.Sys.ID, entry, false)
case sysTypeDeletedEntry:
cc.cacheMutex.idContentTypeMapGcLock.RLock()
contentType := cc.Cache.idContentTypeMap[entry.Sys.ID]
cc.cacheMutex.idContentTypeMapGcLock.RUnlock()
updateCacheForContentTypeAndEntity(ctx, cc, contentType, entry.Sys.ID, entry, true)
default:
}
}
for _, asset := range assets {
switch asset.Sys.Type {
case sysTypeAsset:
updateCacheForContentTypeAndEntity(ctx, cc, assetWorkerType, asset.Sys.ID, asset, false)
case sysTypeDeletedAsset:
updateCacheForContentTypeAndEntity(ctx, cc, assetWorkerType, asset.Sys.ID, nil, true)
default:
}
}
}
}
func (cc *ContentfulClient) cacheWorker(ctx context.Context, contentTypes []string, cacheAssets bool) {
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoCacheWorkerStart)
}
for range cc.cacheQueue {
cc.cacheSpace(ctx, contentTypes, cacheAssets)
cc.cacheDone <- struct{}{}
}
}
func (cc *ContentfulClient) cacheSpace(ctx context.Context, contentTypes []string, cacheAssets bool) {
start := time.Now()
tempCache := &ContentfulCache{
contentTypes: contentTypes,
idContentTypeMap: map[string]string{},
parentMap: map[string][]EntryReference{},
}
if cacheAssets {
contentTypes = append([]string{assetWorkerType}, contentTypes...)
}
_, errCanWeEvenConnect := cc.Client.Spaces.Get(cc.SpaceID)
cc.cacheMutex.sharedDataGcLock.RLock()
offlinePreviousState := cc.offline
cc.cacheMutex.sharedDataGcLock.RUnlock()
if errCanWeEvenConnect != nil {
if len(cc.offlineTemp.Entries) > 0 && (cc.Cache == nil || offlinePreviousState) {
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoFallingBackToFile)
}
cc.cacheMutex.sharedDataGcLock.Lock()
cc.offline = true
cc.cacheMutex.sharedDataGcLock.Unlock()
} else {
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogInfo, InfoPreservingExistingCache)
}
}
}
results := make(chan ContentTypeResult, 16)
resultsDone := make(chan struct{})
contentTypeChan := make(chan string)
group, gctx := errgroup.WithContext(ctx)
for i := 0; i < cacheUpdateConcurrency; i++ {
group.Go(func() error {
for contentType := range contentTypeChan {
err := updateCacheForContentType(gctx, results, cc, tempCache, contentType)
if err != nil {
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache", "contentType": contentType}, LogError, err.Error())
}
return err
}
}
return nil
})
}
go func() {
for _, contentType := range contentTypes {
contentTypeChan <- contentType
}
close(contentTypeChan)
}()
go func() {
for res := range results {
tempCache.idContentTypeMap[res.EntryID] = res.ContentType
for childID, references := range res.References {
tempCache.parentMap[childID] = append(tempCache.parentMap[childID], references...)
}
}
resultsDone <- struct{}{}
}()
err := group.Wait()
close(results)
if err != nil {
// drain contentTypeChan
for range contentTypeChan {
}
cc.cacheMutex.sharedDataGcLock.Lock()
cc.offline = offlinePreviousState
cc.cacheMutex.sharedDataGcLock.Unlock()
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"task": "UpdateCache"}, LogError, err.Error())
}
return
}
// Signal that the cache build is done
<-resultsDone
if cc.logFn != nil && cc.logLevel <= LogInfo {
cc.logFn(map[string]interface{}{"time elapsed": fmt.Sprint(time.Since(start)), "task": "UpdateCache"}, LogInfo, InfoUpdateCacheTime)
}
cc.cacheMutex.fullCacheGcLock.Lock()
cc.cacheMutex.sharedDataGcLock.Lock()
cc.cacheMutex.assetsGcLock.Lock()
cc.cacheMutex.idContentTypeMapGcLock.Lock()
cc.cacheMutex.parentMapGcLock.Lock()
cc.cacheMutex.brandGcLock.Lock()
cc.cacheMutex.categoryGcLock.Lock()
cc.cacheMutex.productGcLock.Lock()
cc.Cache = tempCache
cc.offline = offlinePreviousState
cc.cacheMutex.brandGcLock.Unlock()
cc.cacheMutex.categoryGcLock.Unlock()
cc.cacheMutex.productGcLock.Unlock()
cc.cacheMutex.parentMapGcLock.Unlock()
cc.cacheMutex.idContentTypeMapGcLock.Unlock()
cc.cacheMutex.assetsGcLock.Unlock()
cc.cacheMutex.sharedDataGcLock.Unlock()
cc.cacheMutex.fullCacheGcLock.Unlock()
}
func ToAssetReference(asset *contentful.Asset) (refSys ContentTypeSys) {
refSys.Sys.ID = asset.Sys.ID
refSys.Sys.Type = FieldTypeLink
refSys.Sys.LinkType = FieldLinkTypeAsset
return
}
func (cc *ContentfulClient) UpdateCacheForEntity(ctx context.Context, sysType string, contentType string, entityID string) error {
if sysType == sysTypeEntry && cc.entryMapForContentTypeIsNil(contentType) {
return fmt.Errorf("UpdateCacheForEntity: Content Type %q not available in cache", contentType)
}
if sysType == sysTypeAsset {
contentType = assetWorkerType
}
if contentType != assetWorkerType && !stringSliceContains(spaceContentTypes, contentType) {
return fmt.Errorf("UpdateCache: Content Type %q not available in this space", contentType)
}
return updateCacheForContentTypeAndEntity(ctx, cc, contentType, entityID, nil, false)
}
func FieldToObject(jsonField interface{}, targetObject interface{}) error {
byteArray, err := json.Marshal(jsonField)
if err != nil {
return err
}
err = json.Unmarshal(byteArray, &targetObject)
if err != nil {
return err
}
return nil
}
func (cc *ContentfulClient) cacheGcAssetByID(ctx context.Context, id string, asset *contentful.Asset) error {
if asset == nil {
if cc.Client == nil {
return errors.New("cacheGcAssetByID: No client available")
}
col := cc.Client.Assets.List(cc.SpaceID)
col.Query.Locale("*").Equal("sys.id", id)
_, err := col.Next()
if err != nil {
return err
}
if len(col.Items) == 0 {
return errors.New("cacheGcAssetByID: Not found " + id)
}
item := col.Items[0]
byt, err := json.Marshal(item)
if err != nil {
return err
}
err = json.Unmarshal(byt, &asset)
if err != nil {
return err
}
}
for _, loc := range []Locale{SpaceLocaleGerman, SpaceLocaleFrench} {
if _, ok := asset.Fields.File[string(loc)]; ok {
asset.Fields.File[string(loc)].URL = "https:" + asset.Fields.File[string(loc)].URL
}
}
cc.cacheMutex.assetsGcLock.Lock()
cc.Cache.assets[id] = asset
cc.cacheMutex.assetsGcLock.Unlock()
return nil
}
func (cc *ContentfulClient) deleteAssetFromCache(key string) error {
if cc.Cache == nil || cc.cacheMutex == nil {
return errors.New("no cache available")
}
cc.cacheMutex.assetsGcLock.Lock()
if _, ok := cc.Cache.assets[key]; ok {
delete(cc.Cache.assets, key)
cc.cacheMutex.assetsGcLock.Unlock()
return nil
}
cc.cacheMutex.assetsGcLock.Unlock()
return errors.New("asset not found in cache, could not delete")
}
func (cc *ContentfulClient) entryMapForContentTypeIsNil(contentType string) bool {
switch contentType {
case ContentTypeBrand:
if cc.Cache.entryMaps.brand == nil {
return true
}
case ContentTypeCategory:
if cc.Cache.entryMaps.category == nil {
return true
}
case ContentTypeProduct:
if cc.Cache.entryMaps.product == nil {
return true
}
}
return false
}
func getContentfulAPIClient(clientMode ClientMode, clientKey string) (*contentful.Contentful, error) {
switch clientMode {
case ClientModeCDA:
return contentful.NewCDA(clientKey), nil
case ClientModeCPA:
return contentful.NewCPA(clientKey), nil
case ClientModeCMA:
return contentful.NewCMA(clientKey), nil
default:
return nil, errors.New("NewContentfulClient: Unknown ClientMode")
}