-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcnweb.go
1516 lines (1444 loc) · 48.5 KB
/
cnweb.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
// 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.
//
// Web application for Chinese-English dictionary lookup, translation memory,
// and finding documents in a corpus. Settings in for the app are controlled
// through the file config.yaml, located in the project home directory, which
// is found through the env variable CNREADER_HOME or the present working
// directory.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"cloud.google.com/go/firestore"
"cloud.google.com/go/storage"
"github.com/alexamies/chinesenotes-go/config"
"github.com/alexamies/chinesenotes-go/dictionary"
"github.com/alexamies/chinesenotes-go/dicttypes"
"github.com/alexamies/chinesenotes-go/find"
"github.com/alexamies/chinesenotes-go/fulltext"
"github.com/alexamies/chinesenotes-go/httphandling"
"github.com/alexamies/chinesenotes-go/identity"
"github.com/alexamies/chinesenotes-go/templates"
"github.com/alexamies/chinesenotes-go/termfreq"
"github.com/alexamies/chinesenotes-go/transmemory"
"github.com/alexamies/chinesenotes-go/transtools"
)
const (
deepLKeyName = "DEEPL_AUTH_KEY" // Only needed if using machine translation
defTitle = "Chinese Notes Translation Portal"
glossaryKeyName = "TRANSLATION_GLOSSARY" // Google Translation API glossary
projectIDKey = "PROJECT_ID" // For GCP project
colFileName = "collections.csv"
titleIndexFN = "documents.tsv"
translationTemplFile = "web-resources/translation.html"
)
var (
b *backends
)
// backends holds dependencies that access remote resources
type backends struct {
appConfig config.AppConfig
docMap map[string]find.DocInfo
df find.DocFinder
dict *dictionary.Dictionary
parser find.QueryParser
reverseIndex dictionary.ReverseIndex
substrIndex dictionary.SubstringIndex
templates map[string]*template.Template
tmSearcher transmemory.Searcher
webConfig config.WebAppConfig
deepLApiClient, translateApiClient, glossaryApiClient transtools.ApiClient
translationProcessor transtools.Processor
docTitleFinder find.TitleFinder
authenticator identity.Authenticator
sessionEnforcer httphandling.SessionEnforcer
pageDisplayer httphandling.PageDisplayer
}
// htmlContent holds content for HTML template
type htmlContent struct {
Title string
Query string
ErrorMsg string
Results find.QueryResults
TMResults *transmemory.Results
Data interface{}
}
// Content for change password page
type ChangePasswordHTML struct {
Title string
OldPasswordValid bool
ChangeSuccessful bool
ShowNewForm bool
}
// Data for displaying the translation page.
type translationPage struct {
SourceText, TranslatedText, SuggestedText, Message, Title string
Notes []transtools.Note
DeepLChecked, GCPChecked, GlossaryChecked, PostProcessing string
}
func initApp(ctx context.Context) (*backends, error) {
log.Println("initApp Initializing cnweb")
appConfig := config.InitConfig()
cnwebHome := config.GetCnWebHome()
fileName := fmt.Sprintf("%s/webconfig.yaml", cnwebHome)
webConfig := config.WebAppConfig{}
configFile, err := os.Open(fileName)
if err != nil {
path, er := os.Getwd()
if er != nil {
log.Printf("cannot find cwd: %v", er)
path = ""
}
log.Printf("initApp error loading file '%s' (%s): %v", fileName, path, err)
} else {
defer configFile.Close()
webConfig = config.InitWeb(configFile)
}
var substrIndex dictionary.SubstringIndex
var fsClient *firestore.Client
projectID, ok := os.LookupEnv(projectIDKey)
if !ok {
log.Println("initApp: PROJECT_ID not set not set")
} else {
fsClient, err = firestore.NewClient(ctx, projectID)
if err != nil {
log.Printf("initApp: cannot instantiate Firestore client: %v", err)
}
}
cnReaderHome := os.Getenv("CNREADER_HOME")
var dict *dictionary.Dictionary
if len(cnReaderHome) > 0 {
var err error
dict, err = dictionary.LoadDictFile(appConfig)
if err != nil {
return nil, fmt.Errorf("main.initApp() unable to load dictionary locally: %v", err)
}
} else {
// Load from web for zero-config Quickstart
const url = "https://github.com/alexamies/chinesenotes.com/blob/master/data/cnotes_zh_en_dict.tsv?raw=true"
var err error
dict, err = dictionary.LoadDictURL(appConfig, url)
if err != nil {
return nil, fmt.Errorf("main.initApp() unable to load dictionary from net: %v", err)
}
}
parser := find.NewQueryParser(dict.Wdict)
var tms transmemory.Searcher
var titleFinder find.TitleFinder
var colMap map[string]string
var docMap map[string]find.DocInfo
titleFinder, err = initDocTitleFinder(ctx, appConfig, projectID)
indexCorpus, ok := appConfig.IndexCorpus()
if !ok {
log.Printf("initApp: indexCorpus not set in config.yaml")
}
indexGen := appConfig.IndexGen()
if err != nil {
log.Printf("main.initApp() unable to load titleFinder: %v", err)
} else {
colMap = titleFinder.ColMap()
docMap = titleFinder.DocMap()
log.Printf("main.initApp() doc map loaded with %d cols and %d docs", len(colMap), len(docMap))
}
extractor, err := dictionary.NewNotesExtractor(webConfig.NotesExtractorPattern())
if err != nil {
log.Printf("initApp, non-fatal error, unable to initialize NotesExtractor: %v", err)
}
reverseIndex := dictionary.NewReverseIndex(dict, extractor)
if fsClient != nil {
substrIndex, err = initDictSSIndexFS(fsClient, appConfig, dict)
if err != nil {
log.Printf("initApp, non-fatal error, unable to initialize dictionary substrIndex: %v", err)
}
tms, err = transmemory.NewFSSearcher(fsClient, indexCorpus, indexGen, reverseIndex)
if err != nil {
return nil, fmt.Errorf("main.initApp() unable to create new TM searcher: %v", err)
}
}
var tfDocFinder find.TermFreqDocFinder
if fsClient != nil {
log.Println("fsClient set, configuring full text search")
addDirectory := webConfig.AddDirectoryToCol()
tfDocFinder = termfreq.NewFirestoreDocFinder(fsClient, indexCorpus, indexGen, addDirectory, termfreq.QueryLimit)
}
var authenticator identity.Authenticator
if config.PasswordProtected() {
authenticator = identity.NewAuthenticator(fsClient, indexCorpus)
}
templates := templates.NewTemplateMap(webConfig)
pageDisplayer := httphandling.NewPageDisplayer(templates)
sessionEnforcer := httphandling.NewSessionEnforcer(authenticator, pageDisplayer)
bends := &backends{
appConfig: appConfig,
docMap: docMap,
df: find.NewDocFinder(tfDocFinder, titleFinder),
dict: dict,
parser: parser,
reverseIndex: reverseIndex,
substrIndex: substrIndex,
templates: templates,
tmSearcher: tms,
webConfig: webConfig,
authenticator: authenticator,
sessionEnforcer: sessionEnforcer,
pageDisplayer: pageDisplayer,
}
return bends, nil
}
// initDocTitleFinder initializes the document title finder
func initDocTitleFinder(ctx context.Context, appConfig config.AppConfig, project string) (find.TitleFinder, error) {
if b != nil && b.docTitleFinder != nil {
return b.docTitleFinder, nil
}
colFileName := appConfig.CorpusDataDir() + "/" + colFileName
cr, err := os.Open(colFileName)
if err != nil {
return nil, fmt.Errorf("initDocTitleFinder: Error opening %s: %v", colFileName, err)
}
defer cr.Close()
colMap, err := find.LoadColMap(cr)
if err != nil {
return nil, fmt.Errorf("initDocTitleFinder: Error loading col map: %v", err)
}
titleFileName := appConfig.IndexDir() + "/" + titleIndexFN
r, err := os.Open(titleFileName)
if err != nil {
return nil, fmt.Errorf("initDocTitleFinder: Error opening %s: %v", titleFileName, err)
}
defer r.Close()
var dInfoCN, docMap map[string]find.DocInfo
dInfoCN, docMap = find.LoadDocInfo(r)
log.Printf("initDocTitleFinder loaded %d cols and %d docs", len(colMap), len(docMap))
var docTitleFinder find.TitleFinder
if len(project) > 0 {
log.Println("initDocTitleFinder creating a FirebaseTitleFinder")
client, err := firestore.NewClient(ctx, project)
if err != nil {
log.Printf("initDocTitleFinder, failed to create firestore client: %v", err)
} else {
indexCorpus, ok := appConfig.IndexCorpus()
if !ok {
log.Printf("initDocTitleFinder, IndexCorpus must be set in config.yaml")
} else {
indexGen := appConfig.IndexGen()
docTitleFinder = find.NewFirestoreTitleFinder(client, indexCorpus, indexGen, colMap, dInfoCN, docMap)
if b != nil {
b.docTitleFinder = docTitleFinder
}
return docTitleFinder, nil
}
}
}
log.Println("initDocTitleFinder fall back to a file based TitleFinder")
docTitleFinder = find.NewFileTitleFinder(colMap, dInfoCN, docMap)
if b != nil {
b.docTitleFinder = docTitleFinder
}
return docTitleFinder, nil
}
func initDictSSIndexFS(client *firestore.Client, c config.AppConfig, dict *dictionary.Dictionary) (dictionary.SubstringIndex, error) {
log.Println("initDictSSIndexFS: initializing dictionary substring index for Firestore")
if client == nil {
log.Printf("Firestore client not set, set project env variable to initiate it")
}
indexCorpus, ok := c.IndexCorpus()
if !ok {
log.Fatalf("IndexCorpus must be set in config.yaml")
}
return dictionary.NewSubstringIndexFS(client, indexCorpus, c.IndexGen(), dict)
}
// Process a change password request
func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
log.Print("changePasswordHandler enter")
ctx := context.Background()
if b.authenticator == nil {
var err error
b.authenticator, err = initAuth(ctx)
if err != nil {
log.Printf("changePasswordHandler authenticator could not be initialized: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
}
sessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)
if sessionInfo.Authenticated != 1 {
log.Printf("changePasswordHandler not authenticated: %d", sessionInfo.Authenticated)
http.Error(w, "Not authenticated", http.StatusForbidden)
return
} else {
oldPassword := r.PostFormValue("OldPassword")
password := r.PostFormValue("Password")
result := b.authenticator.ChangePassword(ctx, sessionInfo.User, oldPassword,
password)
if strings.Contains(r.Header.Get("Accept"), "application/json") {
sendJSON(w, result)
} else {
title := b.webConfig.GetVarWithDefault("Title", defTitle)
content := ChangePasswordHTML{
Title: title,
OldPasswordValid: result.OldPasswordValid,
ChangeSuccessful: result.ChangeSuccessful,
ShowNewForm: result.ShowNewForm,
}
b.pageDisplayer.DisplayPage(w, "change_password_form.html", content)
}
}
}
// Display change password form
func changePasswordFormHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
sessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)
if sessionInfo.Authenticated != 1 {
log.Printf("changePasswordHandler not authenticated: %d", sessionInfo.Authenticated)
http.Error(w, "Not authenticated", http.StatusForbidden)
return
} else {
title := b.webConfig.GetVarWithDefault("Title", defTitle)
result := ChangePasswordHTML{
Title: title,
OldPasswordValid: false,
ChangeSuccessful: false,
ShowNewForm: true,
}
b.pageDisplayer.DisplayPage(w, "change_password_form.html", result)
}
}
// Custom 404 page handler
func custom404(w http.ResponseWriter, r *http.Request, url string) {
log.Printf("custom404: sending 404 for %s", url)
b.pageDisplayer.DisplayPage(w, "404.html", nil)
}
func initAuth(ctx context.Context) (identity.Authenticator, error) {
var fsClient *firestore.Client
projectID, ok := os.LookupEnv(projectIDKey)
if !ok {
return nil, fmt.Errorf("changePasswordHandler: PROJECT_ID not set not set")
} else {
var err error
fsClient, err = firestore.NewClient(ctx, projectID)
if err != nil {
log.Printf("changePasswordHandler: cannot instantiate Firestore client: %v", err)
return nil, fmt.Errorf("changePasswordHandler: cannot instantiate Firestore client: %v", err)
}
}
indexCorpus, ok := b.appConfig.IndexCorpus()
if !ok {
return nil, fmt.Errorf("initApp: indexCorpus not set in config.yaml")
}
return identity.NewAuthenticator(fsClient, indexCorpus), nil
}
// displayHome shows a simple page, for health checks and testing.
// End users may also to see this when accessing direct from the browser
func displayHome(w http.ResponseWriter, r *http.Request) {
log.Printf("displayHome: url %s", r.URL.Path)
// Tell health check probes that we are alive
if !httphandling.AcceptHTML(r) {
fmt.Fprintln(w, "OK")
return
}
title := b.webConfig.GetVarWithDefault("Title", defTitle)
content := htmlContent{
Title: title,
}
if config.PasswordProtected() {
ctx := context.Background()
if b.authenticator == nil {
var err error
b.authenticator, err = initAuth(ctx)
if err != nil {
log.Print("displayHome authenticator could not be initialized")
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
}
sessionInfo := identity.InvalidSession()
cookie, err := r.Cookie("session")
if err == nil {
sessionInfo = b.authenticator.CheckSession(ctx, cookie.Value)
} else {
log.Printf("displayHome error getting cookie: %v", err)
b.pageDisplayer.DisplayPage(w, "login_form.html", content)
return
}
if !sessionInfo.Valid {
log.Printf("displayHome no session, URL: %v", r.URL.Path)
b.pageDisplayer.DisplayPage(w, "login_form.html", content)
return
} else {
log.Printf("displayHome: using index_auth.html for url %s", r.URL.Path)
b.pageDisplayer.DisplayPage(w, "index_auth.html", content)
return
}
}
log.Printf("displayHome: template index.html for url %s", r.URL.Path)
b.pageDisplayer.DisplayPage(w, "index.html", content)
}
// Finds documents matching the given query with search in text body
func findFullText(response http.ResponseWriter, request *http.Request) {
log.Println("findFullText, enter")
q := getSingleValue(request, "query")
if len(q) == 0 {
q = getSingleValue(request, "text")
}
if len(q) == 0 {
if httphandling.AcceptHTML(request) {
title := b.webConfig.GetVarWithDefault("Title", defTitle)
content := htmlContent{
Title: title,
}
b.pageDisplayer.DisplayPage(response, "full_text_search.html", content)
return
}
}
ctx := context.Background()
if b == nil {
log.Println("main.findFullText re-initializing app")
var err error
b, err = initApp(ctx)
if err != nil {
log.Printf("main.findFullText error initializing app: %v", err)
http.Error(response, "Internal error", http.StatusInternalServerError)
return
}
}
findDocs(ctx, response, request, b, true)
}
// findDocs finds documents matching the given query.
func findDocs(ctx context.Context, response http.ResponseWriter, request *http.Request, b *backends, fullText bool) {
if config.PasswordProtected() {
sessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, response, request)
if !sessionInfo.Valid {
return
}
}
q := getSingleValue(request, "query")
if len(q) == 0 {
q = getSingleValue(request, "text")
}
// No query, eg someone nativated directly to the HTML page, redisplay it
var err error
if len(q) == 0 && httphandling.AcceptHTML(request) {
log.Print("main.findDocs No query provided")
templateFile := "find_results.html"
if fullText {
templateFile = "full_text_search.html"
}
err = showQueryResults(response, b, find.QueryResults{}, templateFile)
if err != nil {
log.Printf("main.findDocs error displaying empty results %v", err)
http.Error(response, "Internal error", http.StatusInternalServerError)
return
}
return
}
findTitle := getSingleValue(request, "title")
log.Printf("main.findDocs q: %s, title: %s", q, findTitle)
var results *find.QueryResults
c := getSingleValue(request, "collection")
if len(c) > 0 {
results, err = b.df.FindDocumentsInCol(ctx, b.reverseIndex, b.parser, q, c)
} else if len(findTitle) > 0 {
projectID, ok := os.LookupEnv(projectIDKey)
if !ok {
log.Printf("main.findDocs, %s not set", projectIDKey)
}
docTitleFinder, err := initDocTitleFinder(ctx, b.appConfig, projectID)
if err == nil {
docs, err := docTitleFinder.FindDocsByTitle(ctx, q)
results = &find.QueryResults{
Query: q,
Documents: docs,
}
if err != nil {
log.Printf("main.findDocs Error finding docs, %v", err)
http.Error(response, "Internal error", http.StatusInternalServerError)
return
}
}
} else {
results, err = b.df.FindDocuments(ctx, b.reverseIndex, b.parser, q, fullText)
}
if err != nil {
log.Printf("main.findDocs Error searching docs, %v", err)
http.Error(response, "Internal error", http.StatusInternalServerError)
return
}
// Add similar results from translation memory, only do this when more than
// one term is found and when the query string is between 2 and 8 characters
// in length
if !fullText && (b != nil) && (len([]rune(q)) > 1) && (len([]rune(q)) < 9) && (len(results.Terms) > 1) && (b.tmSearcher != nil) {
log.Println("main.findDocs similar results from translation memory")
tmResults, err := b.tmSearcher.Search(ctx, q, "", false, b.dict.Wdict)
if err != nil {
// Not essential to the main request
log.Printf("main.findDocs translation memory error, ignoring: %v", err)
} else if len(tmResults.Words) > 0 {
similarTerms := []find.TextSegment{}
for _, w := range tmResults.Words {
chinese := w.Simplified
if (len(w.Traditional) > 0) && (w.Traditional != "\\N") {
chinese += " (" + w.Traditional + ")"
}
seg := find.TextSegment{
QueryText: chinese,
DictEntry: w,
}
similarTerms = append(similarTerms, seg)
}
results.SimilarTerms = similarTerms
log.Printf("main.findDocs, for query %s, found %d similar phrases",
q, len(results.SimilarTerms))
}
}
// Return HTML if method is post
if httphandling.AcceptHTML(request) {
templateFile := "find_results.html"
if len(findTitle) > 0 {
templateFile = "doc_results.html"
} else if fullText {
templateFile = "full_text_search.html"
r := highlightMatches(*results)
results = &r
// Transform notes field with regular expressions
} else if len(results.Terms) > 0 {
log.Println("main.findDocs, processing notes")
match := b.webConfig.GetVar("NotesReMatch")
replace := b.webConfig.GetVar("NotesReplace")
processor := dictionary.NewNotesProcessor(match, replace)
terms := []find.TextSegment{}
for _, t := range results.Terms {
word := processor.Process(t.DictEntry)
term := find.TextSegment{
QueryText: t.QueryText,
DictEntry: word,
Senses: t.Senses,
}
terms = append(terms, term)
}
results.Terms = terms
}
err = showQueryResults(response, b, *results, templateFile)
if err != nil {
log.Printf("main.findDocs Error displaying results: %v", err)
http.Error(response, "Internal error", http.StatusInternalServerError)
return
}
return
}
// Return JSON
resultsJson, err := json.Marshal(results)
if err != nil {
log.Printf("main.findDocs error marshalling JSON, %v", err)
http.Error(response, "Error marshalling results",
http.StatusInternalServerError)
} else {
if q != "hello" && q != "Eight" { // Health check monitoring probe
log.Printf("main.findDocs, results: %q", string(resultsJson))
}
response.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(response, string(resultsJson))
}
}
func getSingleValue(r *http.Request, key string) string {
var q string
if r.Method == http.MethodPost {
q = r.FormValue(key)
} else {
url := r.URL
queryString := url.Query()
query := queryString[key]
if len(query) > 0 {
q = query[0]
}
}
return q
}
// highlightMatches adds a HTML span element with highlight for matches in the
// snippets of full texts search results
func highlightMatches(r find.QueryResults) find.QueryResults {
results := find.QueryResults{
Query: r.Query,
CollectionFile: r.CollectionFile,
NumCollections: r.NumCollections,
NumDocuments: r.NumDocuments,
Collections: r.Collections,
Terms: r.Terms,
SimilarTerms: r.SimilarTerms,
}
documents := []find.Document{}
for _, d := range r.Documents {
lm := d.MatchDetails.LongestMatch
span := fmt.Sprintf("<span class='usage-highlight'>%s</span>", lm)
s := strings.Replace(d.MatchDetails.Snippet, lm, span, 1)
md := fulltext.MatchingText{
Snippet: s,
LongestMatch: lm,
ExactMatch: d.MatchDetails.ExactMatch,
}
doc := find.Document{
GlossFile: d.GlossFile,
Title: d.Title,
CollectionFile: d.CollectionFile,
CollectionTitle: d.CollectionTitle,
ContainsWords: d.ContainsWords,
ContainsBigrams: d.ContainsBigrams,
SimTitle: d.SimTitle,
SimWords: d.SimWords,
SimBigram: d.SimBigram,
SimBitVector: d.SimBigram,
Similarity: d.Similarity,
ContainsTerms: d.ContainsTerms,
MatchDetails: md,
TitleCNMatch: d.TitleCNMatch,
}
documents = append(documents, doc)
}
results.Documents = documents
return results
}
// initTranslationClients initializes translation API clients and processing utility.
func initTranslationClients(b *backends) {
log.Println("cnweb.initTranslationClients enter")
deepLKey, ok := os.LookupEnv(deepLKeyName)
if !ok {
log.Printf("%s not set\n", deepLKeyName)
} else {
b.deepLApiClient = transtools.NewDeepLClient(deepLKey)
}
b.translateApiClient = transtools.NewGoogleClient()
glossaryName, ok := os.LookupEnv(glossaryKeyName)
if !ok {
log.Printf("%s not set\n", glossaryKeyName)
} else {
projectID, ok := os.LookupEnv(projectIDKey)
if !ok {
log.Printf("%s not set\n", projectIDKey)
} else {
b.glossaryApiClient = transtools.NewGlossaryClient(projectID, glossaryName)
}
}
fExpected, err := os.Open(transtools.ExpectedDataFile)
if err != nil {
log.Printf("initTranslationClients: Error opening expected file: %v", err)
return
}
fReplace, err := os.Open(transtools.ReplaceDataFile)
if err != nil {
log.Printf("initTranslationClients: Error opening replace file: %v", err)
return
}
defer func() {
if err = fExpected.Close(); err != nil {
log.Printf("Error closing expected file: %v", err)
}
if err = fReplace.Close(); err != nil {
log.Printf("Error closing replace file: %v", err)
}
}()
b.translationProcessor = transtools.NewProcessor(fExpected, fReplace)
}
// processTranslation performs translation and post processing of source text.
func processTranslation(w http.ResponseWriter, r *http.Request) {
title := b.webConfig.GetVarWithDefault("Title", defTitle)
if b.translationProcessor == nil {
p := &translationPage{
Message: "Translation service not initialized",
Title: title,
PostProcessing: "on",
}
showTranslationPage(w, b, p)
}
source := r.FormValue("source")
translated := ""
message := ""
notes := []transtools.Note{}
deepLChecked := "checked"
gcpChecked := ""
glossaryChecked := ""
platform := r.FormValue("platform")
if platform == "gcp" {
deepLChecked = ""
gcpChecked = "checked"
glossaryChecked = ""
} else if platform == "withGlossary" {
deepLChecked = ""
gcpChecked = ""
glossaryChecked = "checked"
}
log.Printf("processTranslation, glossaryChecked %s, source: %s", glossaryChecked, source)
processingChecked := r.FormValue("processing")
if len(source) > 0 {
log.Printf("platform: %s", platform)
trText, err := translate(b, source, platform)
if err != nil {
log.Printf("Translation error: %v", err)
message = err.Error()
} else {
log.Printf("Translation result: %s", *trText)
translated = *trText
}
} else {
message = "Please enter translated text or click Translate for a machine translation"
}
if len(translated) > 0 && processingChecked == "on" {
result := b.translationProcessor.Suggest(source, translated)
translated = result.Replacement
notes = result.Notes
log.Printf("suggestion notes: %s, suggested translation: %s", notes, translated)
}
log.Printf("deepLChecked: %s, gcpChecked: %s, glossaryChecked: %s, processingChecked: %s, len(translated) = %d",
deepLChecked, gcpChecked, glossaryChecked, processingChecked, len(translated))
if config.PasswordProtected() {
ctx := context.Background()
sessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)
if !sessionInfo.Valid {
return
}
}
postProcessing := ""
if processingChecked == "on" {
postProcessing = "checked"
}
p := &translationPage{
SourceText: source,
TranslatedText: translated,
Message: message,
Title: title,
Notes: notes,
DeepLChecked: deepLChecked,
GCPChecked: gcpChecked,
GlossaryChecked: glossaryChecked,
PostProcessing: postProcessing,
}
showTranslationPage(w, b, p)
}
// showQueryResults displays query results on a HTML page
func showQueryResults(w io.Writer, b *backends, results find.QueryResults, templateFile string) error {
res := results
staticDir := b.appConfig.GetVar("GoStaticDir")
if len(staticDir) > 0 && len(results.Documents) > 0 {
log.Printf("showQueryResults, len(Documents): %d", len(results.Documents))
docs := []find.Document{}
for _, doc := range results.Documents {
d := find.Document{
GlossFile: "/" + staticDir + "/" + doc.GlossFile,
Title: doc.Title,
CollectionFile: "/" + staticDir + "/" + doc.CollectionFile,
CollectionTitle: doc.CollectionTitle,
ContainsWords: doc.ContainsWords,
ContainsBigrams: doc.ContainsBigrams,
SimTitle: doc.SimTitle,
SimWords: doc.SimWords,
SimBigram: doc.SimBigram,
SimBitVector: doc.SimBitVector,
Similarity: doc.Similarity,
ContainsTerms: doc.ContainsTerms,
MatchDetails: doc.MatchDetails,
TitleCNMatch: doc.TitleCNMatch,
}
log.Printf("showQueryResults, adding: %s", d.Title)
docs = append(docs, d)
}
res = find.QueryResults{
Query: results.Query,
CollectionFile: staticDir + "/" + results.CollectionFile,
NumCollections: results.NumCollections,
NumDocuments: results.NumDocuments,
Collections: results.Collections,
Documents: docs,
Terms: results.Terms,
SimilarTerms: results.SimilarTerms,
}
}
title := b.webConfig.GetVarWithDefault("Title", defTitle)
content := htmlContent{
Title: title,
Results: res,
}
var tmpl *template.Template
var err error
tmpl = b.templates[templateFile]
if err != nil {
return fmt.Errorf("showQueryResults: error parsing template %v", err)
}
if tmpl == nil {
return fmt.Errorf("showQueryResults: %s", "Template is nil")
}
err = tmpl.Execute(w, content)
if err != nil {
return fmt.Errorf("showQueryResults: error rendering template %v", err)
}
return nil
}
// Displays the translation page.
func showTranslationPage(w http.ResponseWriter, b *backends, p *translationPage) {
b.pageDisplayer.DisplayPage(w, "translation.html", p)
}
// findHandler finds documents matching the given query.
func findHandler(response http.ResponseWriter, request *http.Request) {
log.Printf("findHandler: url %s", request.URL.Path)
ctx := context.Background()
findDocs(ctx, response, request, b, false)
}
// findSubstring finds terms matching the given query with a substring match.
func findSubstring(response http.ResponseWriter, request *http.Request) {
log.Println("main.findSubstring, enter")
url := request.URL
queryString := url.Query()
query := queryString["query"]
q := ""
if len(query) > 0 {
q = query[0]
}
topic := queryString["topic"]
t := ""
if len(topic) > 0 {
t = topic[0]
}
subtopic := queryString["subtopic"]
st := "placeholder"
if len(subtopic) > 0 {
st = subtopic[0]
}
if b.substrIndex == nil {
log.Println("main.findSubstring index not configured")
http.Error(response, "Error, index not configured", http.StatusInternalServerError)
return
}
ctx := context.Background()
results, err := b.substrIndex.LookupSubstr(ctx, q, t, st)
if err != nil {
log.Printf("main.findSubstring Error looking up term, %v", err)
http.Error(response, "Error looking up term", http.StatusInternalServerError)
return
}
resultsJson, err := json.Marshal(results)
if err != nil {
log.Printf("main.findSubstring error marshalling JSON, %v", err)
http.Error(response, "Error marshalling results",
http.StatusInternalServerError)
} else {
response.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(response, string(resultsJson))
}
}
// Health check for monitoring or load balancing system, checks reachability
func healthcheck(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "OK")
fmt.Fprintf(w, "Password protected: %t", config.PasswordProtected())
}
// Display library page for digital texts
func library(w http.ResponseWriter, r *http.Request) {
log.Printf("library: url %s", r.URL.Path)
title := b.webConfig.GetVarWithDefault("Title", defTitle)
content := htmlContent{
Title: title,
}
if config.PasswordProtected() {
ctx := context.Background()
if b.authenticator == nil {
var err error
b.authenticator, err = initAuth(ctx)
if err != nil {
log.Print("library authenticator could not be initialized")
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
}
sessionInfo := identity.InvalidSession()
cookie, err := r.Cookie("session")
if err == nil {
sessionInfo = b.authenticator.CheckSession(ctx, cookie.Value)
} else {
log.Printf("displayHome error getting cookie: %v", err)
b.pageDisplayer.DisplayPage(w, "login_form.html", content)
return
}
if !sessionInfo.Valid {
b.pageDisplayer.DisplayPage(w, "login_form.html", content)
return
} else {
b.pageDisplayer.DisplayPage(w, "library.html", content)
return
}
}
b.pageDisplayer.DisplayPage(w, "library.html", content)
}
// Display login form for the Translation Portal
func loginFormHandler(w http.ResponseWriter, r *http.Request) {
b.pageDisplayer.DisplayPage(w, "login_form.html", nil)
}
// Process a login request
func loginHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
if b.authenticator == nil {
var err error
b.authenticator, err = initAuth(ctx)
if err != nil {
log.Print("loginHandler authenticator could not be initialized")
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
}
sessionInfo := identity.InvalidSession()
err := r.ParseForm()
if err != nil {
log.Printf("loginHandler: error parsing form: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
username := r.PostFormValue("UserName")
log.Printf("loginHandler: username = %s", username)
password := r.PostFormValue("Password")
users, err := b.authenticator.CheckLogin(ctx, username, password)
if err != nil {
log.Printf("main.loginHandler checking login, %v", err)
http.Error(w, "Error checking login", http.StatusInternalServerError)
return
}
if len(users) != 1 {
log.Printf("loginHandler: user %s not found or password does not match", username)
} else {
cookie, err := r.Cookie("session")
if err == nil {
log.Printf("loginHandler: updating session: %s", cookie.Value)
sessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)
}
if (err != nil) || !sessionInfo.Valid {
sessionid := identity.NewSessionId()
domain := config.GetSiteDomain()
log.Printf("loginHandler: setting new session %s for domain %s",
sessionid, domain)
cookie := &http.Cookie{
Name: "session",
Value: sessionid,
Domain: domain,
Path: "/",
MaxAge: 86400 * 30, // One month
}
http.SetCookie(w, cookie)
sessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)
}
}
if strings.Contains(r.Header.Get("Accept"), "application/json") {
sendJSON(w, sessionInfo)
} else {
if sessionInfo.Authenticated == 1 {
title := b.webConfig.GetVarWithDefault("Title", defTitle)
content := htmlContent{
Title: title,
}
b.pageDisplayer.DisplayPage(w, "index.html", content)
} else {
loginFormHandler(w, r)