/
main.go
executable file
·183 lines (168 loc) · 4.74 KB
/
main.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
package main
import (
"os"
"fmt"
"log"
"regexp"
"context"
"io/ioutil"
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
)
type MailInfoData struct {
To string `json:"to"`
Date string `json:"date"`
File string `json:"file"`
From string `json:"from"`
Subject string `json:"subject"`
}
type APIResponse struct {
Message string `json:"message"`
Data []MailInfoData `json:"data"`
}
type Response events.APIGatewayProxyResponse
var s3Client *s3.Client
var dynamodbClient *dynamodb.Client
func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (Response, error) {
var jsonBytes []byte
var err error
d := make(map[string]string)
json.Unmarshal([]byte(request.Body), &d)
if v, ok := d["action"]; ok {
switch v {
case "getbody" :
// check access token if you need
if name, ok := d["name"]; ok {
log.Println(name)
res, err_ := getMailBody(ctx, name)
if err_ != nil {
err = err_
} else {
jsonBytes, _ = json.Marshal(APIResponse{Message: res, Data: []MailInfoData{}})
}
}
case "getlist" :
// check access token if you need
res, err_ := getMailList(ctx)
if err_ != nil {
err = err_
} else {
jsonBytes, _ = json.Marshal(APIResponse{Message: "success", Data: res})
}
}
}
log.Print(request.RequestContext.Identity.SourceIP)
if err != nil {
log.Print(err)
jsonBytes, _ = json.Marshal(APIResponse{Message: fmt.Sprint(err), Data: []MailInfoData{}})
return Response{
StatusCode: 500,
Body: string(jsonBytes),
}, nil
}
return Response {
StatusCode: 200,
Body: string(jsonBytes),
}, nil
}
func scan(ctx context.Context, filt expression.ConditionBuilder, proj expression.ProjectionBuilder)(*dynamodb.ScanOutput, error) {
if dynamodbClient == nil {
dynamodbClient = dynamodb.NewFromConfig(getConfig(ctx))
}
expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build()
if err != nil {
return nil, err
}
input := &dynamodb.ScanInput{
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
FilterExpression: expr.Filter(),
ProjectionExpression: expr.Projection(),
TableName: aws.String(os.Getenv("TABLE_NAME")),
}
res, err := dynamodbClient.Scan(ctx, input)
return res, err
}
func getMailList(ctx context.Context)([]MailInfoData, error) {
var mailInfoList []MailInfoData
// Filter by Destination
filt := expression.NotEqual(expression.Name("to"), expression.Value(" "))
// filt := expression.Equal(expression.Name("to"), expression.Value("UserName"))
proj := expression.NamesList(expression.Name("to"), expression.Name("date"), expression.Name("file"), expression.Name("from"), expression.Name("subject"))
res, err := scan(ctx, filt, proj)
if err != nil {
return mailInfoList, err
}
for _, i := range res.Items {
item := MailInfoData{}
err = attributevalue.UnmarshalMap(i, &item)
if err != nil {
return nil, err
}
mailInfoList = append(mailInfoList, item)
}
return mailInfoList, nil
}
func getMailBody(ctx context.Context, objectKey string)(string, error) {
if len(objectKey) == 0 {
return "", fmt.Errorf("Error: %s", "No ObjectKey.")
}
if s3Client == nil {
s3Client = s3.NewFromConfig(getConfig(ctx))
}
input := &s3.GetObjectInput{
Bucket: aws.String(os.Getenv("BUCKET_NAME")),
Key: aws.String(objectKey),
}
res, err := s3Client.GetObject(ctx, input)
if err != nil {
return "", err
}
rc := res.Body
defer rc.Close()
tmpData, err := ioutil.ReadAll(rc)
if err != nil {
log.Println(err)
return "", err
}
if len(string(tmpData)) < 1 {
return "", fmt.Errorf("Error: %s", "Empty Mail Body.")
}
// check user name if you need
/*
destination := ""
for _, w := range regexp.MustCompile("[\n]").Split(string(tmpData), -1) {
if strings.HasPrefix(w, "To") {
destination = w[4:]
break
}
}
if destination != "UserName" {
return "", fmt.Errorf("Error: %s", "Invalid Access.")
}
*/
strNormalized := regexp.MustCompile("\r\n").ReplaceAllString(string(tmpData), "\n")
rawMailLines := regexp.MustCompile(`\n\s*\n`).Split(strNormalized, -1)
if len(rawMailLines) < 2 {
return "", fmt.Errorf("Error: %s", "Empty Mail Body.")
}
return rawMailLines[1], nil
}
func getConfig(ctx context.Context) aws.Config {
var err error
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(os.Getenv("REGION")))
if err != nil {
log.Print(err)
}
return cfg
}
func main() {
lambda.Start(HandleRequest)
}