/
server.go
1378 lines (1291 loc) · 38.2 KB
/
server.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
/*
Copyright 2020 Center for Digital Matter HGK FHNW, Basel.
Copyright 2020 info-age GmbH, Basel.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package search
import (
"bufio"
"context"
"crypto/rsa"
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/Masterminds/sprig"
"github.com/bluele/gcache"
"github.com/drgrib/maps"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"github.com/htfy96/reformism"
"github.com/je4/utils/v2/pkg/JWTInterceptor"
"github.com/je4/utils/v2/pkg/zLogger"
"github.com/je4/zsearch/v2/pkg/amp"
"github.com/je4/zsearch/v2/pkg/translate"
"github.com/je4/zsearch/v2/web"
"github.com/pkg/errors"
"google.golang.org/api/customsearch/v1"
"html/template"
"io"
"io/fs"
"mime"
"net"
"net/http"
"net/url"
"os"
"regexp"
"runtime"
"runtime/debug"
"sort"
"strings"
"time"
)
type Notification struct {
Id template.JS
Message string
}
type BaseStatus struct {
OGPNamespace string
OGPMeta string
JsonLD string
Type string
Notifications []Notification
User *User
Self string
RawQuery string
Canonical string
Token string
BaseUrl string
Prefixes map[string]string
SelfPath string
RelPath string
AmpBase string
LoginUrl string
Title string
InstanceName string
server *Server
Plain bool
}
type DetailStatus struct {
BaseStatus
Doc *SourceData
MetaPublic bool
ContentPublic bool
MetaOK bool
ContentOK bool
IsAmp bool
MetaDescription string
Result *SearchResult
SearchResultRows int
SearchResultTotal int
FacebookAppId string
Plain bool
}
type FacetCountField struct {
Id string
Name string
ShortName string
Selected bool
}
type SearchStatus struct {
BaseStatus
SearchResult template.JS
Result *SearchResult
QueryApi template.URL
SearchResultStart int
SearchResultRows int
SearchResultTotal int
SearchString string
Filter map[string][]string
SearchResultVisible bool
Facet map[string]map[string]FacetCountField
CoreFacets []string
MetaDescription string
EmptySearch bool
Stats FacetCountResult
}
type CollectionsStatus struct {
BaseStatus
SearchResult template.JS
Result map[string][]*SourceData
Areas []string
QueryApi template.URL
SearchResultStart int
SearchResultRows int
SearchResultTotal int
SearchResultVisible bool
MetaDescription string
}
type ClusterStatus struct {
BaseStatus
SearchResult template.JS
Result []*SourceData
QueryApi template.URL
SearchResultStart int
SearchResultRows int
SearchResultTotal int
SearchResultVisible bool
MetaDescription string
}
type ImageSearchStatus struct {
Type string
Notifications []Notification
User *User
Self string
Token string
BaseUrl string
SelfPath string
AmpBase string
LoginUrl string
Title string
SearchResult template.JS
Result *SearchResult
QueryApi template.URL
SearchResultStart int
SearchResultRows int
SearchResultTotal int
SearchString string
MetaDescription string
}
type SubFilter struct {
Name string `toml:"Name"`
Label string `toml:"label"`
Filter string `toml:"filter"`
}
type NetGroups map[string][]*net.IPNet
type facetField struct {
Id string `json:"id"`
Name string `json:"Name"`
Selected bool `json:"Selected"`
}
type SearchResult struct {
Items []SearchResultItem `json:"items"`
Total int64 `json:"total"`
Start int64 `json:"SearchResultStart"`
Rows int64 `json:"Rows"`
Query string `json:"query"`
Search string `json:"search"`
Next string `json:"next"`
FacetFieldCount map[string]facetField `json:"facetfieldcount"`
}
type SearchResultItem struct {
Id string `json:"Id"`
Type string `json:"type"`
Title *translate.MultiLangString `json:"title"`
Text string `json:"text"`
Collection string `json:"collection"`
Authors []string `json:"authors"`
AuthorText string `json:"authortext"`
Link string `json:"link"`
FirstItem bool `json:"firstitem"`
Total int64 `json:"total,omitempty"`
Date string `json:"date"`
Icon string `json:"icon"`
Media map[string]int `json:"media"`
MetaPublic bool `json:"metapublic"`
ContentPublic bool `json:"contentpublic"`
MetaOK bool `json:"metaok"`
ContentOK bool `json:"contentok"`
Poster *Media `json:"poster"`
Highlight map[string][]string `json:"highlight"`
}
type KV struct{ Key, Name string }
func (bs BaseStatus) LinkSignatureCache(signature string) string {
urlstr := fmt.Sprintf("%s/%s/%s", bs.RelPath, bs.server.prefixes["detail"], signature)
urlstr = strings.TrimLeft(urlstr, "/")
var err error
if bs.server.ampCache != nil {
urlstr, err = bs.server.ampCache.BuildUrl(urlstr, amp.PAGE)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
}
return urlstr
}
func (bs BaseStatus) LinkSearch(query string, facets ...string) template.URL {
urlstr := fmt.Sprintf("%s/%s?searchtext=%s", bs.RelPath, bs.server.prefixes["search"], url.QueryEscape(query))
urlstr = strings.TrimLeft(urlstr, "/")
for _, f := range facets {
urlstr += fmt.Sprintf("&%s=true", url.QueryEscape(f))
}
if bs.User.LoggedIn {
_, err := NewJWT(
bs.server.jwtKey,
"search",
"HS256",
int64(bs.server.linkTokenExp.Seconds()),
"catalogue",
"mediathek",
bs.User.Id)
if err != nil {
return template.URL(fmt.Sprintf("ERROR: %v", err))
}
//urlstr += fmt.Sprintf("&token=%s", jwt)
} else {
if bs.server.ampCache != nil {
var err error
urlstr, err = bs.server.ampCache.BuildUrl(urlstr, amp.PAGE)
if err != nil {
return template.URL(fmt.Sprintf("ERROR: %v", err))
}
}
}
return template.URL(urlstr)
}
func (bs BaseStatus) LinkSignature(signature string) string {
urlstr := fmt.Sprintf("%s/%s/%s", bs.RelPath, bs.server.prefixes["detail"], signature)
urlstr = strings.TrimLeft(urlstr, "/")
if bs.User.LoggedIn {
_, err := NewJWT(
bs.server.jwtKey,
fmt.Sprintf("detail:%s", signature),
"HS256",
int64(bs.server.linkTokenExp.Seconds()),
"catalogue",
"mediathek",
bs.User.Id)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
//urlstr = fmt.Sprintf("%s?token=%s", urlstr, jwt)
} else {
if bs.server.ampCache != nil {
var err error
urlstr, err = bs.server.ampCache.BuildUrl(urlstr, amp.PAGE)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
}
}
return urlstr
}
func (bs BaseStatus) LinkCollections() string {
urlstr := fmt.Sprintf("%s/%s", bs.RelPath, bs.server.prefixes["collections"])
urlstr = strings.TrimLeft(urlstr, "/")
if bs.User.LoggedIn {
_, err := NewJWT(
bs.User.Server.jwtKey,
"collections",
"HS256",
int64(bs.server.linkTokenExp.Seconds()),
"catalogue",
"mediathek",
bs.User.Id)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
//urlstr = fmt.Sprintf("%s?token=%s", urlstr, jwt)
} else {
if bs.server.ampCache != nil {
var err error
urlstr, err = bs.server.ampCache.BuildUrl(urlstr, amp.PAGE)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
}
}
return urlstr
}
func (bs BaseStatus) LinkSubject(area, sub, subject string, params ...string) string {
prefix, ok := bs.server.prefixes[area]
if !ok {
bs.server.log.Error().Msgf("invalid area %s in link", area)
return fmt.Sprintf("#invalid area %s in link", area)
}
var urlstr string
if sub != "" {
urlstr = fmt.Sprintf("%s/%s/%s", bs.RelPath, prefix, sub)
} else {
urlstr = fmt.Sprintf("%s/%s", bs.RelPath, prefix)
}
urlstr = strings.TrimLeft(urlstr, "/")
if bs.User.LoggedIn {
_, err := NewJWT(
bs.server.jwtKey,
subject,
"HS256",
int64(bs.server.linkTokenExp.Seconds()),
"catalogue",
"mediathek",
bs.User.Id)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
//urlstr = fmt.Sprintf("%s?token=%s", urlstr, jwt)
if len(params) > 0 {
urlstr += "?" + strings.Join(params, "&")
}
} else {
if bs.server.ampCache != nil {
var err error
urlstr, err = bs.server.ampCache.BuildUrl(urlstr, amp.PAGE)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
}
if len(params) > 0 {
urlstr += "?" + strings.Join(params, "&")
}
}
return urlstr
}
func (ng NetGroups) Contains(str string) []string {
var groups []string
ip := net.ParseIP(str)
for grp, nets := range ng {
for _, n := range nets {
if n.Contains(ip) {
groups = append(groups, grp)
break
}
}
}
return groups
}
type Server struct {
service string
mts *Search
srv *http.Server
userCache *UserCache
host string
port string
addrExt *url.URL
prefixes map[string]string
staticDir string
sitemapDir string
staticCacheControl string
jwtKey string
jwtAlg []string
linkTokenExp time.Duration
loginUrl string
loginIssuer string
guestGroup string
adminGroup string
templates map[string]*template.Template
templatesFiles map[string][]string
templateDev bool
mediaserver string
mediaserverKey string
mediaTokenExp time.Duration
log zLogger.ZLogger
accesslog io.Writer
ampApiKey *rsa.PrivateKey
ampCache *amp.Cache
searchFields map[string]string
facets SolrFacetList
locations NetGroups
icons map[string]string
baseCatalog []string
subFilters []SubFilter
funcMap template.FuncMap
collectionsCatalog string
clusterCatalog string
queryCache gcache.Cache
google *customsearch.Service
googleCSEKey map[string]KV
instanceName string
cookieStore *sessions.CookieStore
cookieAuthKey []byte
cookieEncryptionKey []byte
sessionTimeout time.Duration
templateDir string
facebookAppId string
}
func NewServer(
service string,
mts *Search,
uc *UserCache,
google *customsearch.Service,
templateFiles map[string][]string,
templateDev bool,
InstanceName,
addr, addrExt,
mediaserver, mediaserverkey string,
mediatokenexp time.Duration,
log zLogger.ZLogger,
accesslog io.Writer,
prefixes map[string]string,
staticDir,
sitemapdir,
staticCacheControl,
templatedir,
jwtKey string, jwtAlg []string,
linkTokenExp,
sessionTimeout time.Duration,
loginUrl,
loginIssuer,
guestGroup,
adminGroup,
AmpCache,
ampApiKeyFile string,
searchFields map[string]string,
facets SolrFacetList,
locations NetGroups,
icons map[string]string,
baseCatalog []string,
subFilter []SubFilter,
collectionsCatalog,
clusterCatalog string,
googleCSEKey map[string]KV,
facebookAppId string,
) (*Server, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
//log.Panicf("cannot split address %s: %v", addr, err)
return nil, errors.Wrapf(err, "cannot split address %s", addr)
}
// load private api Key
privateKeyFile, err := os.Open(ampApiKeyFile)
if err != nil {
return nil, errors.Wrapf(err, "cannot open %s", ampApiKeyFile)
}
pemfileinfo, _ := privateKeyFile.Stat()
pembytes := make([]byte, pemfileinfo.Size())
buffer := bufio.NewReader(privateKeyFile)
_, err = buffer.Read(pembytes)
data, _ := pem.Decode([]byte(pembytes))
if err := privateKeyFile.Close(); err != nil {
log.Error().Err(err).Msgf("error closing private key file: %v", err)
}
ampApiKey, err := x509.ParsePKCS1PrivateKey(data.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "cannot parse private Key %s", string(data.Bytes))
}
aCaches, err := amp.GetCaches()
if err != nil {
return nil, err
}
ampCache, _ := aCaches[AmpCache]
extUrl, err := url.Parse(addrExt)
if err != nil {
return nil, errors.Wrapf(err, "cannot parse external address %s", addrExt)
}
authKey := securecookie.GenerateRandomKey(64)
encryptionKey := securecookie.GenerateRandomKey(32)
srv := &Server{
service: service,
mts: mts,
userCache: uc,
google: google,
host: host,
port: port,
addrExt: extUrl,
prefixes: prefixes,
mediaserver: mediaserver,
mediaserverKey: mediaserverkey,
mediaTokenExp: mediatokenexp,
log: log,
accesslog: accesslog,
staticDir: staticDir,
sitemapDir: sitemapdir,
templateDir: templatedir,
staticCacheControl: staticCacheControl,
templateDev: templateDev,
jwtKey: jwtKey,
jwtAlg: jwtAlg,
linkTokenExp: linkTokenExp,
sessionTimeout: sessionTimeout,
loginUrl: loginUrl,
loginIssuer: loginIssuer,
guestGroup: guestGroup,
adminGroup: adminGroup,
ampCache: ampCache,
ampApiKey: ampApiKey,
searchFields: searchFields,
facets: facets,
locations: locations,
icons: icons,
baseCatalog: baseCatalog,
subFilters: subFilter,
templates: make(map[string]*template.Template),
funcMap: template.FuncMap{},
collectionsCatalog: collectionsCatalog,
clusterCatalog: clusterCatalog,
queryCache: gcache.New(100).ARC().Expiration(time.Hour * 3).Build(),
googleCSEKey: googleCSEKey,
facebookAppId: facebookAppId,
templatesFiles: templateFiles,
instanceName: InstanceName,
cookieStore: sessions.NewCookieStore(
authKey,
nil,
//encryptionKey,
),
cookieAuthKey: authKey,
cookieEncryptionKey: encryptionKey,
}
srv.cookieStore.Options = &sessions.Options{
MaxAge: int(sessionTimeout / time.Second),
HttpOnly: true,
SameSite: http.SameSiteLaxMode, // http.SameSiteStrictMode,
Path: "/",
}
if err := srv.InitTemplates(); err != nil {
return nil, errors.Wrapf(err, "cannot initialize server")
}
return srv, nil
}
func initTemplate(filesystem fs.FS, tpl []string, name string, funcMap template.FuncMap) (*template.Template, error) {
newTpl, err := template.New(name).Funcs(funcMap).ParseFS(filesystem, tpl...)
if err != nil {
return nil, errors.Wrapf(err, "cannot parse error template %v - %v", name, tpl)
}
return newTpl, nil
}
func (s *Server) InitTemplates() (err error) {
mediaMatch := regexp.MustCompile(`^mediaserver:([^/]+)/([^/]+)$`)
for key, val := range sprig.FuncMap() {
s.funcMap[key] = val
}
s.funcMap["trimLeft"] = func(cutset, value string) string {
return strings.TrimLeft(value, cutset)
}
s.funcMap["trimRight"] = func(cutset, value string) string {
return strings.TrimRight(value, cutset)
}
s.funcMap["trimLength"] = func(value string, length int, suffix string) string {
return TrimLength(value, length, suffix)
}
for key, val := range reformism.FuncsHTML {
s.funcMap[key] = val
}
s.funcMap["url"] = func(value string) template.URL {
return template.URL(value)
}
s.funcMap["js"] = func(value string) template.JS {
return template.JS(value)
}
s.funcMap["nl2br"] = func(value string) template.HTML {
safe := template.HTMLEscapeString(value)
safe = strings.Replace(safe, "\n", "<br>", -1)
return template.HTML(safe)
}
s.funcMap["htmlattr"] = func(value string) template.HTMLAttr {
return template.HTMLAttr(value)
}
s.funcMap["jsstr"] = func(value string) template.JSStr {
return template.JSStr(value)
}
s.funcMap["html"] = func(value string) template.HTML {
return template.HTML(value)
}
s.funcMap["srcset"] = func(value string) template.Srcset {
return template.Srcset(value)
}
s.funcMap["resizeW"] = func(width, height, targetW, targetH int64) int64 {
aspect := float64(width) / float64(height)
targetAspect := float64(targetW) / float64(targetH)
if aspect > targetAspect {
w := float64(targetW)
//h := w/aspect
return int64(w)
} else {
h := float64(targetH)
w := h * aspect
return int64(w)
}
}
s.funcMap["resizeH"] = func(width, height, targetW, targetH int64) int64 {
aspect := float64(width) / float64(height)
targetAspect := float64(targetW) / float64(targetH)
if aspect > targetAspect {
w := float64(targetW)
h := w / aspect
return int64(h)
} else {
h := float64(targetH)
//w := h*aspect
return int64(h)
}
}
s.funcMap["mediachild"] = func(uri, child string) string {
matches := mediaMatch.FindStringSubmatch(uri)
if matches == nil {
return uri
}
return uri + child
}
s.funcMap["searchtokenparam"] = func(user *User) string {
if !user.LoggedIn {
return ""
}
_, err := NewJWT(
s.mediaserverKey,
"search",
"HS256",
int64(s.linkTokenExp.Seconds()),
"mediaserver",
"mediathek",
user.Id)
if err != nil {
return fmt.Sprintf("&error=%s", url.QueryEscape(fmt.Sprintf("ERROR-%v", err)))
}
return "" // fmt.Sprintf("&token=%s", jwt)
}
s.funcMap["medialink"] = func(uri, action, param string, token bool) string {
matches := mediaMatch.FindStringSubmatch(uri)
params := strings.Split(param, "/")
sort.Strings(params)
// if not matching, just return the uri
if matches == nil {
return uri
}
collection := matches[1]
signature := matches[2]
urlstr := fmt.Sprintf("%s/%s/%s/%s/%s", s.mediaserver, collection, signature, action, param)
if token {
jwt, err := NewJWT(
s.mediaserverKey,
strings.TrimRight(fmt.Sprintf("mediaserver:%s/%s/%s/%s", collection, signature, action, strings.Join(params, "/")), "/"),
"HS256",
int64(s.mediaTokenExp.Seconds()),
"mediaserver",
"mediathek",
"")
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
urlstr = fmt.Sprintf("%s?token=%s", urlstr, jwt)
} else {
if s.ampCache != nil {
urlstr, err = s.ampCache.BuildUrl(urlstr, amp.IMAGE)
if err != nil {
return fmt.Sprintf("ERROR: %v", err)
}
}
}
return urlstr
}
var filesystem fs.FS
if s.templateDir == "" {
filesystem, err = fs.Sub(web.TemplateFS, "template")
if err != nil {
return errors.Wrap(err, "cannot get subtree of embedded static")
}
} else {
filesystem = os.DirFS(s.templateDir)
}
for name, templateFiles := range s.templatesFiles {
tpl, err := initTemplate(filesystem, templateFiles, name, s.funcMap)
if err != nil {
return errors.Wrapf(err, "cannot initialize template")
}
s.templates[name] = tpl
}
return nil
}
var regexpMediaUri = regexp.MustCompile(`^mediaserver:([^/]+)/([^/]+)$`)
func (s *Server) mediaserverUri2Url(uri string, params ...string) (string, error) {
matches := regexpMediaUri.FindStringSubmatch(uri)
if matches == nil {
return "", fmt.Errorf("cannot parse uri %s", uri)
}
u := fmt.Sprintf("%s/%s/%s", s.mediaserver, matches[1], matches[2])
if len(params) > 0 {
u += "/" + strings.Join(params, "/")
}
return u, nil
}
func mediaserverUri2ColSig(uri string) (string, string, error) {
matches := regexpMediaUri.FindStringSubmatch(uri)
if matches == nil {
return "", "", fmt.Errorf("cannot parse uri %s", uri)
}
return matches[1], matches[2], nil
}
func (s *Server) DoPanicf(user *User, req *http.Request, writer http.ResponseWriter, status int, message string, json bool, a ...interface{}) (err error) {
msg := fmt.Sprintf(message, a...)
if json {
if err := s.DoPanicJSON(writer, status, msg); err != nil {
s.log.Error().Msgf("error sending panic json: %v", err)
}
} else {
if user == nil {
user = NewGuestUser(s)
}
data := struct {
BaseStatus
Error string
Message string
}{
BaseStatus: BaseStatus{
Type: "error",
User: user,
Self: fmt.Sprintf("%s/%s", s.addrExt, strings.TrimLeft(req.URL.Path, "/")),
BaseUrl: s.addrExt.String(),
RawQuery: req.URL.RawQuery,
SelfPath: req.URL.Path,
LoginUrl: s.loginUrl,
Notifications: []Notification{},
Token: "",
Prefixes: map[string]string{
"detail": s.prefixes["detail"],
"search": s.prefixes["search"],
"collections": s.prefixes["collections"],
"cluster": s.prefixes["cluster"],
"google": s.prefixes["cse"],
},
AmpBase: "",
Title: "",
InstanceName: s.instanceName,
},
Error: fmt.Sprintf("%v - %s", status, http.StatusText(status)),
Message: msg,
}
writer.WriteHeader(http.StatusNotFound)
if tpl, ok := s.templates["error.amp.gohtml"]; ok {
if err := tpl.Execute(writer, data); err != nil {
s.log.Error().Msgf("executing error.amp.gohtml template: %v", err)
}
}
}
return
}
func (s *Server) DoPanic(writer http.ResponseWriter, status int, message string) error {
type errData struct {
Status int
StatusText string
Message string
}
//debug.PrintStack()
s.log.Error().Msg(message)
data := errData{
Status: status,
StatusText: http.StatusText(status),
Message: message,
}
writer.WriteHeader(status)
// if there's no error Template, there's no help...
if tpl, ok := s.templates["error.gohtml"]; ok {
if err := tpl.Execute(writer, data); err != nil {
s.log.Error().Msgf("executing error.gohtml template: %v", err)
}
} else {
return fmt.Errorf("no error template found")
}
return nil
}
func (s *Server) DoPanicJSON(writer http.ResponseWriter, status int, message string) (err error) {
type errData struct {
Status int `json:"status"`
StatusText string `json:"statustext"`
Message string `json:"message"`
}
debug.PrintStack()
s.log.Error().Msg(message)
data := errData{
Status: status,
StatusText: http.StatusText(status),
Message: message,
}
writer.WriteHeader(status)
jenc := json.NewEncoder(writer)
if err := jenc.Encode(data); err != nil {
s.log.Error().Msgf("error encoding json [%v]: %v", data, err)
}
return
}
func (s *Server) userFromToken(tokenstring, signature string) (*User, error) {
// jwt valid?
claims, err := CheckJWTValid(tokenstring, s.jwtKey, s.jwtAlg)
if err != nil {
return nil, errors.Wrapf(err, "invalid access token")
}
// check whether token is from login gsearch
issuer, ok := claims["iss"]
if !ok {
return nil, errors.Wrapf(err, "no iss in token %v", tokenstring)
}
issuerstr, ok := issuer.(string)
if !ok {
return nil, errors.Wrapf(err, "iss not a string in token %v", tokenstring)
}
// token from login
var user *User
if issuerstr == s.loginIssuer {
user, err = s.GetClaimUser(claims)
if err != nil {
return nil, errors.Wrapf(err, "cannot extract userdata from token %v", tokenstring)
}
user.LoggedIn = true
user.LoggedOut = false
if err := s.userCache.SetUser(user, user.Id); err != nil {
s.log.Error().Msgf("error adding user to cache: %v", err)
}
} else {
// sub given?
sub, err := GetClaim(claims, "sub")
if err != nil {
return nil, errors.Wrapf(err, "no sub in token")
}
// sub correct?
if signature != "" && strings.ToLower(sub) != strings.ToLower(signature) {
return nil, errors.Wrapf(err, "invalid sub %s (should be %s) in token", sub, signature)
}
// user given?
userstr, err := GetClaim(claims, "user")
if err != nil {
return nil, errors.Wrapf(err, "no user in token")
}
// user is string?
user, err = s.userCache.GetUser(userstr)
// user not found --> log out and become a guest
if err != nil {
return nil, errors.Wrapf(err, "user timed out")
} else {
user.LoggedOut = false
user.LoggedIn = true
}
}
return user, nil
}
/*
const (
acceptEncoding string = "Accept-Encoding"
gzipEncoding = "gzip"
flateEncoding = "deflate"
)
*/
func (s *Server) ListenAndServe(cert, key string) error {
router := mux.NewRouter()
// https://data.mediathek.hgk.fhnw.ch/search
searchRegexp := regexp.MustCompile(fmt.Sprintf("/%s(/(.+))?$", s.prefixes["search"]))
searchMatcher := func(r *http.Request, rm *mux.RouteMatch) bool {
matches := searchRegexp.FindSubmatch([]byte(r.URL.Path))
if len(matches) == 0 {
return false
}
rm.Vars = map[string]string{}
if len(matches) >= 3 {
if matches[2] != nil {
filter := string(matches[2])
rm.Vars = map[string]string{}
rm.Vars["subfilter"] = filter
}
}
return true
}
router.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, fmt.Sprintf("%s/%s", s.addrExt, s.prefixes["search"]), http.StatusMovedPermanently)
}))
router.
MatcherFunc(searchMatcher).
Handler(handlers.CompressHandler(func() http.Handler { return http.HandlerFunc(s.searchHandler) }())).
Methods("GET")
collectionsRegexp := regexp.MustCompile(fmt.Sprintf("/%s(/(?P<subfilter>.+))?$", s.prefixes["collections"]))
router.
MatcherFunc(buildMatcher(collectionsRegexp)).
Handler(handlers.CompressHandler(func() http.Handler { return http.HandlerFunc(s.collectionsHandler) }())).
Methods("GET")
// https://data.mediathek.hgk.fhnw.ch/detail/[signature]/embed/[embedCollection|/[embedSignature]
embedRegexp := regexp.MustCompile(fmt.Sprintf("/%s/(?P<signature>[^/]+)/embed/(?P<embedCollection>[^/]+)/(?P<embedSignature>[^/]+)(/(?P<rest>.*))?$", s.prefixes["detail"]))
router.
MatcherFunc(buildMatcher(embedRegexp)).
Handler(handlers.CompressHandler(func() http.Handler { return http.HandlerFunc(s.detailEmbedHandler) }())).
Methods("GET")
// https://data.mediathek.hgk.fhnw.ch/detail/[signature]
detailRegexp := regexp.MustCompile(fmt.Sprintf("/%s/(?P<signature>[^/]+)(/(?P<collection>[^/]+-[^/]+))?(/(?P<data>data))?(/(?P<plain>plain))?(/(?P<rest>.*))?$", s.prefixes["detail"]))
router.
MatcherFunc(buildMatcher(detailRegexp)).
Handler(handlers.CompressHandler(func() http.Handler { return http.HandlerFunc(s.detailHandler) }())).
Methods("GET")
// https://data.mediathek.hgk.fhnw.ch/update/[signature]
updateRegexp := regexp.MustCompile(fmt.Sprintf("^/%s/(.+)$", s.prefixes["update"]))
router.
MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
matches := updateRegexp.FindSubmatch([]byte(r.URL.Path))
if len(matches) == 0 {
return false
}
rm.Vars = map[string]string{}
rm.Vars["signature"] = string(matches[1])
return true
}).
Handler(handlers.CompressHandler(func() http.Handler { return http.HandlerFunc(s.updateHandler) }())).
Methods("GET")
// the static fileserver
// trouble with mimetypes on windows
if runtime.GOOS == "windows" {
if err := mime.AddExtensionType(".js", "application/javascript; charset=utf-8"); err != nil {
s.log.Error().Msgf("cannot add mime extension type: %v", err)
}
if err := mime.AddExtensionType(".css", "text/css; charset=utf-8"); err != nil {
s.log.Error().Msgf("cannot add mime extension type: %v", err)
}
}
var httpStaticServer http.Handler
if s.staticDir == "" {
fsys, err := fs.Sub(web.StaticFS, "static")
if err != nil {
return errors.Wrap(err, "cannot get subtree of embedded static")