-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
215 lines (184 loc) · 5.46 KB
/
main.go
File metadata and controls
215 lines (184 loc) · 5.46 KB
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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/danesparza/plex2slack-lambda/data"
)
// Set up our flags
var (
webhookURL = ""
)
func parseEnvironment() {
// Check for allowed origins
if envWebhook := os.Getenv("PLEX2SLACK_WEBHOOK_URL"); envWebhook != "" {
webhookURL = envWebhook
}
}
func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// Parse our options from the environment
parseEnvironment()
// Verify the webhook url has been set
log.Printf("PLEX2SLACK_WEBHOOK_URL from environment: %+v\n", webhookURL)
// Step zero: Decode the body:
s, err := base64.StdEncoding.DecodeString(request.Body)
if err != nil {
log.Printf("There was an error base64 decoding the body: %v\n", err)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusBadRequest,
Headers: map[string]string{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
Body: fmt.Sprintf("Error getting content type: %v", err),
}, nil
}
// Print out what we have
// log.Printf("%+v\n", string(s))
// log.Printf("Headers: %+v\n", request.Headers)
// First, get the content type. Throw an error if we can't
mediaType, params, err := mime.ParseMediaType(request.Headers["Content-Type"])
if err != nil {
log.Printf("There was an error getting the content type: %v\n", err)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusUnsupportedMediaType,
Headers: map[string]string{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
Body: fmt.Sprintf("Error getting content type: %v", err),
}, nil
}
// If the content type is multipart...
if strings.HasPrefix(mediaType, "multipart/") {
// Break apart the content into its parts
readForm := multipart.NewReader(strings.NewReader(string(s)), params["boundary"])
// log.Printf("DEBUG:: boundary: %v\n", params["boundary"])
for {
part, errPart := readForm.NextPart()
if errPart == io.EOF {
break
}
if part.FormName() == "thumb" {
/*
No op
*/
} else if part.FormName() == "payload" {
partBytes, _ := ioutil.ReadAll(part)
msg := data.PlexMessage{}
if err := json.Unmarshal(partBytes, &msg); err != nil {
panic(err)
}
// First, see what kind of message it is:
if msg.Event == "library.new" {
// Format our notification:
slackMsg := data.SlackRequestBody{}
// Movie
if msg.Metadata.Type == "movie" {
slackMsg = data.SlackRequestBody{
Text: fmt.Sprintf("%v added to Movies", msg.Metadata.Title),
Blocks: []data.SlackBlock{
data.SlackBlock{
Type: "section",
Text: &data.SlackText{
Text: fmt.Sprintf("*%v*", msg.Metadata.Title),
Type: "mrkdwn",
},
},
data.SlackBlock{
Type: "context",
Elements: []data.SlackElement{
data.SlackElement{
Type: "mrkdwn",
Text: "added to Movies",
},
},
},
data.SlackBlock{
Type: "divider",
},
},
}
}
// TV show
if msg.Metadata.Type == "episode" {
slackMsg = data.SlackRequestBody{
Text: fmt.Sprintf("%v %v: %v added to TV shows", msg.Metadata.GrandparentTitle, msg.Metadata.ParentTitle, msg.Metadata.Title),
Blocks: []data.SlackBlock{
data.SlackBlock{
Type: "section",
Text: &data.SlackText{
Text: fmt.Sprintf("New episode of *%v %v*: _%v_", msg.Metadata.GrandparentTitle, msg.Metadata.ParentTitle, msg.Metadata.Title),
Type: "mrkdwn",
},
},
data.SlackBlock{
Type: "context",
Elements: []data.SlackElement{
data.SlackElement{
Type: "mrkdwn",
Text: "added to TV shows",
},
},
},
data.SlackBlock{
Type: "divider",
},
},
}
}
// Send the message to slack
SendSlackNotification(webhookURL, slackMsg)
}
// Used for debugging:
log.Printf("Event: %v / Type: %v / Grandparent title: %v / Parent title: %v / Title: %v \n", msg.Event, msg.Metadata.Type, msg.Metadata.GrandparentTitle, msg.Metadata.ParentTitle, msg.Metadata.Title)
}
}
}
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Headers: map[string]string{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
Body: "Success",
}, nil
}
func main() {
lambda.Start(handler)
}
// SendSlackNotification will post to an 'Incoming Webook' url setup in Slack Apps. It accepts
// some text and the slack channel is saved within Slack.
func SendSlackNotification(webhookURL string, msg data.SlackRequestBody) error {
slackBody, _ := json.Marshal(msg)
log.Printf("Sending message to Slack:\n %v\n", string(slackBody))
req, err := http.NewRequest(http.MethodPost, webhookURL, bytes.NewBuffer(slackBody))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return err
}
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
if buf.String() != "ok" {
return errors.New("Non-ok response returned from Slack")
}
return nil
}