forked from Songmu/deglacer
-
Notifications
You must be signed in to change notification settings - Fork 6
/
deglacer.go
198 lines (178 loc) · 4.38 KB
/
deglacer.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
package deglacer
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"github.com/MH4GF/notion-deglacer/notion"
"github.com/kjk/notionapi"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"golang.org/x/sync/errgroup"
)
func Run(argv []string) error {
if err := initialize(); err != nil {
return err
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
var eg errgroup.Group
srv := &http.Server{Addr: ":" + port, Handler: http.HandlerFunc(index)}
eg.Go(func() error {
err := srv.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
return err
}
return nil
})
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
sig := <-c
log.Printf("received signal %s, shutting down\n", sig)
eg.Go(func() error {
return srv.Shutdown(context.Background())
})
return eg.Wait()
}
var (
notionClient *notion.Client
slackCli *slack.Client
slackSigningSecret string
)
func initialize() error {
notionToken := os.Getenv("NOTION_TOKEN")
if notionToken == "" {
return errors.New("env NOTION_TOKEN required")
}
notionClient = ¬ion.Client{
AuthToken: notionToken,
}
slackSigningSecret = os.Getenv("SLACK_SIGNING_SECRET")
if slackSigningSecret == "" {
return errors.New("env SLACK_SIGNING_SECRET required")
}
slackToken := os.Getenv("SLACK_TOKEN")
if slackToken == "" {
return errors.New("env SLACK_TOKEN is empty")
}
slackCli = slack.New(slackToken)
return nil
}
func index(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
fmt.Fprintf(w, "Hello")
case http.MethodPost:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
sv, err := slack.NewSecretsVerifier(r.Header, slackSigningSecret)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
sv.Write(body)
if err := sv.Ensure(); err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
ev, err := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionNoVerifyToken())
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
switch ev.Type {
case slackevents.URLVerification:
var res *slackevents.ChallengeResponse
if err := json.Unmarshal(body, &res); err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/plain")
if _, err := w.Write([]byte(res.Challenge)); err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
case slackevents.CallbackEvent:
if ev.InnerEvent.Type != slackevents.LinkShared {
fmt.Fprint(w, "ok")
return
}
inEv, ok := ev.InnerEvent.Data.(*slackevents.LinkSharedEvent)
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
go unfurl(inEv)
fmt.Fprint(w, "ok")
return
}
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
func unfurl(ev *slackevents.LinkSharedEvent) {
unfurls := make(map[string]slack.Attachment, len(ev.Links))
for _, link := range ev.Links {
if !strings.HasSuffix(link.Domain, ".notion.so") {
continue
}
u, err := url.Parse(link.URL)
if err != nil {
log.Println(err)
continue
}
// official notion api does not provide retrieving pageID
// because notionapi library is only used to extract pageID
// notionapi can't parse query parameter
u.RawQuery = ""
u.Fragment = ""
pageID := notionapi.ExtractNoDashIDFromNotionURL(u.String())
var title string
page, err := notionClient.RetrievePage(pageID)
if err == nil {
title = page.Properties.Title()
} else {
log.Printf("RetrievePage Error: %s", err)
database, err := notionClient.RetrieveDatabase(pageID)
if err == nil {
fmt.Println(database.DatabaseTitle())
title = database.DatabaseTitle()
} else {
log.Printf("RetrieveDatabase Error: %s", err)
continue
}
}
// TODO: add Text Attachment contain the beginning of content
unfurls[link.URL] = slack.Attachment{
Title: title,
TitleLink: link.URL,
Footer: "Notion",
}
}
if len(unfurls) == 0 {
return
}
_, _, err := slackCli.PostMessage(ev.Channel, slack.MsgOptionUnfurl(ev.MessageTimeStamp, unfurls))
if err != nil {
log.Println(err)
}
}