-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
62 lines (56 loc) · 2 KB
/
function.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
package function
import (
"context"
"github.com/dachv/cloud-ocr-function/cloudocr"
"github.com/dachv/cloud-ocr-function/cloudsql"
"github.com/dachv/cloud-ocr-function/cloudstorage"
_ "github.com/lib/pq"
"log"
"os"
"path"
"strconv"
)
const (
formTypeFieldId string = "FormType"
validFormType string = "0W-8BEN-E"
processedDir string = "processed"
unprocessedDir string = "unprocessed"
)
var destinationBucket string
func init() {
destinationBucket = os.Getenv("CLOUD_OCR_DESTINATION_BUCKET")
}
//zip -r cloud-ocr-function.zip ./ -x \*.git\* -x \*.idea\* -x \*/.DS_Store\*
//gsutil rm "gs://cloud-ocr-source/**"
//gsutil -h "x-goog-meta-company-name:TestCompany1" -h "x-goog-meta-app-id:1" cp ~/Desktop/ADF-W8-BEN-E\ 2016-Signed.pdf gs://cloud-ocr-source/
func HandleCloudStorageUpload(ctx context.Context, event cloudstorage.StorageEvent) error {
log.Printf("StorageEvent: %v\n", event)
companyName := event.Metadata["company-name"]
appId := event.Metadata["app-id"]
objectData := cloudstorage.ReadObjectData(event.Bucket, event.Name)
ocrResult := cloudocr.PerformOcr(objectData)
ocrData := ocrResult.GetTextData()
validDoc := isDocumentValid(ocrData)
if validDoc {
_, version := cloudsql.ExistsWith(companyName, validFormType)
version = version + 1
objectName := path.Join(companyName, processedDir, appId, strconv.Itoa(version), event.Name)
cloudstorage.CreateNewObject(destinationBucket, objectName, objectData, ocrData)
insertId := cloudsql.InsertDocument(objectName, companyName, version, ocrData)
log.Printf("Document metadata insert id: %v", insertId)
} else {
objectName := path.Join(companyName, unprocessedDir, appId, event.Name)
cloudstorage.CreateNewObject(destinationBucket, objectName, objectData, ocrData)
}
return nil
}
func isDocumentValid(ocrData map[string]string) bool {
for id, value := range ocrData {
if id == formTypeFieldId && value == validFormType {
log.Printf("Document is valid: %v", value)
return true
}
}
log.Printf("Document is invalid")
return false
}