-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathhandlers_linkpreview.go
259 lines (218 loc) · 7.37 KB
/
handlers_linkpreview.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
package server
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"github.com/golang/protobuf/proto"
"go.uber.org/zap"
"github.com/status-im/status-go/images"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/protobuf"
)
func getUnfurledLinksFromDB(db *sql.DB, msgID string) ([]*protobuf.UnfurledLink, error) {
var result []byte
err := db.QueryRow(`SELECT unfurled_links FROM user_messages WHERE id = ?`, msgID).Scan(&result)
if err != nil {
return nil, fmt.Errorf("could not find message with message-id '%s': %w", msgID, err)
}
var links []*protobuf.UnfurledLink
err = json.Unmarshal(result, &links)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal protobuf.UrlPreview: %w", err)
}
return links, nil
}
func getThumbnailPayload(db *sql.DB, msgID string, thumbnailURL string) ([]byte, error) {
var payload []byte
var links, err = getUnfurledLinksFromDB(db, msgID)
if err != nil {
return nil, err
}
for _, p := range links {
if p.Url == thumbnailURL {
payload = p.ThumbnailPayload
break
}
}
return payload, nil
}
func getFaviconPayload(db *sql.DB, msgID string, faviconURL string) ([]byte, error) {
var payload []byte
var links, err = getUnfurledLinksFromDB(db, msgID)
if err != nil {
return nil, err
}
for _, p := range links {
if p.Url == faviconURL {
payload = p.FaviconPayload
break
}
}
return payload, nil
}
func validateAndReturnImageParams(r *http.Request, w http.ResponseWriter, logger *zap.Logger) ImageParams {
params := r.URL.Query()
parsed := ParseImageParams(logger, params)
if parsed.MessageID == "" {
http.Error(w, "missing query parameter 'message-id'", http.StatusBadRequest)
return ImageParams{}
}
if parsed.URL == "" {
http.Error(w, "missing query parameter 'url'", http.StatusBadRequest)
return ImageParams{}
}
return parsed
}
func getMimeTypeAndWriteImage(w http.ResponseWriter, logger *zap.Logger, imagePayload []byte) {
mimeType, err := images.GetMimeType(imagePayload)
if err != nil {
http.Error(w, "mime type not supported", http.StatusNotImplemented)
return
}
w.Header().Set("Content-Type", "image/"+mimeType)
w.Header().Set("Cache-Control", "no-store")
_, err = w.Write(imagePayload)
if err != nil {
logger.Error("failed to write response", zap.Error(err))
}
}
func checkForFetchImageError(err error, logger *zap.Logger, parsedImageParams ImageParams, w http.ResponseWriter, imageType string) {
if err != nil {
logger.Error("failed to get "+imageType, zap.String("msgID", parsedImageParams.MessageID))
http.Error(w, "failed to get "+imageType, http.StatusInternalServerError)
return
}
}
func handleLinkPreviewThumbnail(db *sql.DB, logger *zap.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
parsed := validateAndReturnImageParams(r, w, logger)
if parsed.URL != "" {
thumbnail, err := getThumbnailPayload(db, parsed.MessageID, parsed.URL)
checkForFetchImageError(err, logger, parsed, w, "thumbnail")
getMimeTypeAndWriteImage(w, logger, thumbnail)
}
}
}
func handleLinkPreviewFavicon(db *sql.DB, logger *zap.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
parsed := validateAndReturnImageParams(r, w, logger)
if parsed.URL != "" {
favicon, err := getFaviconPayload(db, parsed.MessageID, parsed.URL)
checkForFetchImageError(err, logger, parsed, w, "favicon")
getMimeTypeAndWriteImage(w, logger, favicon)
}
}
}
func getStatusLinkPreviewImage(p *protobuf.UnfurledStatusLink, imageID common.MediaServerImageID) ([]byte, error) {
switch imageID {
case common.MediaServerContactIcon:
contact := p.GetContact()
if contact == nil {
return nil, fmt.Errorf("this is not a contact link")
}
if contact.Icon == nil {
return nil, fmt.Errorf("contact icon is empty")
}
return contact.Icon.Payload, nil
case common.MediaServerCommunityIcon:
community := p.GetCommunity()
if community == nil {
return nil, fmt.Errorf("this is not a community link")
}
if community.Icon == nil {
return nil, fmt.Errorf("community icon is empty")
}
return community.Icon.Payload, nil
case common.MediaServerCommunityBanner:
community := p.GetCommunity()
if community == nil {
return nil, fmt.Errorf("this is not a community link")
}
if community.Banner == nil {
return nil, fmt.Errorf("community banner is empty")
}
return community.Banner.Payload, nil
case common.MediaServerChannelCommunityIcon:
channel := p.GetChannel()
if channel == nil {
return nil, fmt.Errorf("this is not a community channel link")
}
if channel.Community == nil {
return nil, fmt.Errorf("channel community is empty")
}
if channel.Community.Icon == nil {
return nil, fmt.Errorf("channel community icon is empty")
}
return channel.Community.Icon.Payload, nil
case common.MediaServerChannelCommunityBanner:
channel := p.GetChannel()
if channel == nil {
return nil, fmt.Errorf("this is not a community channel link")
}
if channel.Community == nil {
return nil, fmt.Errorf("channel community is empty")
}
if channel.Community.Banner == nil {
return nil, fmt.Errorf("channel community banner is empty")
}
return channel.Community.Banner.Payload, nil
}
return nil, fmt.Errorf("value not supported")
}
func getStatusLinkPreviewThumbnail(db *sql.DB, messageID string, URL string, imageID common.MediaServerImageID) ([]byte, int, error) {
var messageLinks []byte
err := db.QueryRow(`SELECT unfurled_status_links FROM user_messages WHERE id = ?`, messageID).Scan(&messageLinks)
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("could not find message with message-id '%s': %w", messageID, err)
}
var links protobuf.UnfurledStatusLinks
err = proto.Unmarshal(messageLinks, &links)
if err != nil {
return nil, http.StatusInternalServerError, fmt.Errorf("failed to unmarshal protobuf.UrlPreview: %w", err)
}
for _, p := range links.UnfurledStatusLinks {
if p.Url == URL {
thumbnailPayload, err := getStatusLinkPreviewImage(p, imageID)
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("invalid query parameter 'image-id' value: %w", err)
}
return thumbnailPayload, http.StatusOK, nil
}
}
return nil, http.StatusBadRequest, fmt.Errorf("no link preview found for given url")
}
func handleStatusLinkPreviewThumbnail(db *sql.DB, logger *zap.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
parsed := ParseImageParams(logger, params)
if parsed.MessageID == "" {
http.Error(w, "missing query parameter 'message-id'", http.StatusBadRequest)
return
}
if parsed.URL == "" {
http.Error(w, "missing query parameter 'url'", http.StatusBadRequest)
return
}
if parsed.ImageID == "" {
http.Error(w, "missing query parameter 'image-id'", http.StatusBadRequest)
return
}
thumbnail, httpsStatusCode, err := getStatusLinkPreviewThumbnail(db, parsed.MessageID, parsed.URL, common.MediaServerImageID(parsed.ImageID))
if err != nil {
http.Error(w, err.Error(), httpsStatusCode)
return
}
mimeType, err := images.GetMimeType(thumbnail)
if err != nil {
http.Error(w, "mime type not supported", http.StatusNotImplemented)
return
}
w.Header().Set("Content-Type", "image/"+mimeType)
w.Header().Set("Cache-Control", "no-store")
_, err = w.Write(thumbnail)
if err != nil {
logger.Error("failed to write response", zap.Error(err))
}
}
}