Skip to content
This repository was archived by the owner on Nov 25, 2024. It is now read-only.

Commit ff87ec3

Browse files
committed
made handler sy-test compatible
1 parent 677fbb2 commit ff87ec3

File tree

4 files changed

+74
-60
lines changed

4 files changed

+74
-60
lines changed

mediaapi/routing/url_preview.go

+66-52
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"context"
66
"crypto/sha256"
7+
"crypto/tls"
78
"encoding/base64"
89
"encoding/json"
910
"fmt"
@@ -94,6 +95,11 @@ func makeUrlPreviewHandler(
9495
}
9596
}
9697

98+
urlParsed, err := url.Parse(pUrl)
99+
if err != nil {
100+
return util.ErrorResponse(ErrorMissingUrl)
101+
}
102+
97103
hash := getHashFromString(pUrl)
98104

99105
// Get for url preview from in-memory cache
@@ -136,6 +142,7 @@ func makeUrlPreviewHandler(
136142
// we defer caching the url preview response as well as signalling the waiting goroutines
137143
// about the completion of the request
138144
defer func() {
145+
139146
urlPreviewCacheItem := &types.UrlPreviewCacheRecord{
140147
Created: time.Now().Unix(),
141148
}
@@ -164,38 +171,25 @@ func makeUrlPreviewHandler(
164171
if err != nil {
165172
activeUrlPreviewRequest.Error = err
166173
} else {
167-
defer func() {
168-
err := resp.Body.Close()
169-
if err != nil {
170-
logger.WithError(err).Error("unable to close response body")
171-
}
172-
}()
174+
defer resp.Body.Close() // nolint: errcheck
173175

174176
var result *types.UrlPreview
175-
var err, err2 error
176-
var imgUrl *url.URL
177+
var err error
177178
var imgReader *http.Response
178179
var mediaData *types.MediaMetadata
179180
var width, height int
180181

181182
if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/html") {
182183
// The url is a webpage - get data from the meta tags
183-
result = getPreviewFromHTML(resp, pUrl)
184+
result = getPreviewFromHTML(resp, urlParsed)
184185
if result.ImageUrl != "" {
185-
// The page has an og:image link
186-
if imgUrl, err2 = url.Parse(result.ImageUrl); err2 == nil {
187-
imgReader, err2 = downloadUrl(result.ImageUrl, time.Duration(cfg.UrlPreviewTimeout)*time.Second)
188-
if err2 == nil {
189-
// Download image and store it as a thumbnail
190-
mediaData, width, height, err2 = downloadAndStoreImage(imgUrl.Path, req.Context(), imgReader, cfg, device, db, activeThumbnailGeneration, logger)
191-
}
192-
}
193-
// In case of any error in image download
194-
// we don't show the original URL as it is insecure for the room users
195-
if err2 != nil {
196-
result.ImageUrl = ""
186+
// In case of an image in the preview we download it
187+
if imgReader, err = downloadUrl(result.ImageUrl, time.Duration(cfg.UrlPreviewTimeout)*time.Second); err == nil {
188+
mediaData, width, height, _ = downloadAndStoreImage("url_preview", req.Context(), imgReader, cfg, device, db, activeThumbnailGeneration, logger)
197189
}
198-
190+
// We don't show the original image in the preview
191+
// as it is insecure for room members
192+
result.ImageUrl = ""
199193
}
200194
} else if strings.HasPrefix(resp.Header.Get("Content-Type"), "image/") {
201195
// The url is an image link
@@ -275,7 +269,10 @@ func checkActivePreviewResponse(activeUrlPreviewRequests *types.ActiveUrlPreview
275269
}
276270

277271
func downloadUrl(url string, t time.Duration) (*http.Response, error) {
278-
client := http.Client{Timeout: t}
272+
tr := &http.Transport{
273+
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
274+
}
275+
client := http.Client{Timeout: t, Transport: tr}
279276
resp, err := client.Get(url)
280277
if err != nil {
281278
return nil, err
@@ -287,15 +284,18 @@ func downloadUrl(url string, t time.Duration) (*http.Response, error) {
287284
return resp, nil
288285
}
289286

290-
func getPreviewFromHTML(resp *http.Response, url string) *types.UrlPreview {
287+
func getPreviewFromHTML(resp *http.Response, urlParsed *url.URL) *types.UrlPreview {
288+
291289
fields := getMetaFieldsFromHTML(resp)
292290
preview := &types.UrlPreview{
293291
Title: fields["og:title"],
294292
Description: fields["og:description"],
293+
Type: fields["og:type"],
294+
Url: fields["og:url"],
295295
}
296296

297297
if fields["og:title"] == "" {
298-
preview.Title = url
298+
preview.Title = urlParsed.String()
299299
}
300300
if fields["og:image"] != "" {
301301
preview.ImageUrl = fields["og:image"]
@@ -305,14 +305,19 @@ func getPreviewFromHTML(resp *http.Response, url string) *types.UrlPreview {
305305
preview.ImageUrl = fields["og:image:secure_url"]
306306
}
307307

308-
if fields["og:image:width"] != "" {
309-
if width, err := strconv.Atoi(fields["og:image:width"]); err == nil {
310-
preview.ImageWidth = width
311-
}
312-
}
313-
if fields["og:image:height"] != "" {
314-
if height, err := strconv.Atoi(fields["og:image:height"]); err == nil {
315-
preview.ImageHeight = height
308+
if preview.ImageUrl != "" {
309+
if imgUrl, err := url.Parse(preview.ImageUrl); err == nil {
310+
// Use the same scheme and host as the original URL if empty
311+
if imgUrl.Scheme == "" {
312+
imgUrl.Scheme = urlParsed.Scheme
313+
}
314+
// Use the same host as the original URL if empty
315+
if imgUrl.Host == "" {
316+
imgUrl.Host = urlParsed.Host
317+
}
318+
preview.ImageUrl = imgUrl.String()
319+
} else {
320+
preview.ImageUrl = ""
316321
}
317322
}
318323

@@ -371,11 +376,11 @@ func downloadAndStoreImage(
371376
if err != nil {
372377
return nil, width, height, err
373378
}
374-
img, err := thumbnailer.ReadFile(string(filePath))
379+
width, height, err := thumbnailer.GetImageSize(string(filePath))
375380
if err != nil {
376381
return nil, width, height, err
377382
}
378-
return existingMetadata, img.Bounds().Dx(), img.Bounds().Dy(), nil
383+
return existingMetadata, width, height, nil
379384
}
380385

381386
tmpFileName := filepath.Join(string(tmpDir), "content")
@@ -386,22 +391,34 @@ func downloadAndStoreImage(
386391
}
387392
logger.WithField("contentType", fileType).Debug("uploaded file is an image")
388393

389-
// Create a thumbnail from the image
390-
thumbnailPath := tmpFileName + ".thumbnail"
394+
var thumbnailPath string
391395

392-
width, height, err = createThumbnail(types.Path(tmpFileName), types.Path(thumbnailPath), types.ThumbnailSize(cfg.UrlPreviewThumbnailSize),
393-
hash, activeThumbnailGeneration, cfg.MaxThumbnailGenerators, logger)
394-
if err != nil {
395-
if errors.Is(err, thumbnailer.ErrThumbnailTooLarge) {
396-
// In case the image is smaller than the thumbnail size
397-
// we don't create a thumbnail
398-
thumbnailPath = tmpFileName
399-
} else {
396+
if cfg.UrlPreviewThumbnailSize.Width != 0 {
397+
// Create a thumbnail from the image
398+
thumbnailPath = tmpFileName + ".thumbnail"
399+
400+
width, height, err = createThumbnail(types.Path(tmpFileName), types.Path(thumbnailPath), types.ThumbnailSize(cfg.UrlPreviewThumbnailSize),
401+
hash, activeThumbnailGeneration, cfg.MaxThumbnailGenerators, logger)
402+
if err != nil {
403+
if errors.Is(err, thumbnailer.ErrThumbnailTooLarge) {
404+
// In case the image is smaller than the thumbnail size
405+
// we don't create a thumbnail
406+
thumbnailPath = tmpFileName
407+
} else {
408+
return nil, width, height, err
409+
}
410+
}
411+
} else {
412+
// No thumbnail size specified, use the original image
413+
thumbnailPath = tmpFileName
414+
width, height, err = thumbnailer.GetImageSize(thumbnailPath)
415+
if err != nil {
400416
return nil, width, height, err
401417
}
418+
402419
}
403420

404-
thumbnailFileInfo, err := os.Stat(string(thumbnailPath))
421+
thumbnailFileInfo, err := os.Stat(thumbnailPath)
405422
if err != nil {
406423
logger.WithError(err).Error("unable to get thumbnail file info")
407424
return nil, width, height, err
@@ -564,12 +581,7 @@ func detectFileType(filePath string, logger *log.Entry) (string, error) {
564581
logger.WithError(err).Error("unable to open image file")
565582
return "", err
566583
}
567-
defer func() {
568-
err := file.Close()
569-
if err != nil {
570-
logger.WithError(err).Error("unable to close image file")
571-
}
572-
}()
584+
defer file.Close() // nolint: errcheck
573585

574586
buf := make([]byte, 512)
575587

@@ -605,6 +617,8 @@ func getMetaFieldsFromHTML(resp *http.Response) map[string]string {
605617
"og:image:width",
606618
"og:image:height",
607619
"og:image:type",
620+
"og:type",
621+
"og:url",
608622
}
609623
fieldsMap := make(map[string]bool, len(fieldsToGet))
610624
for _, field := range fieldsToGet {

mediaapi/thumbnailer/thumbnailer_nfnt.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,10 @@ func CreateThumbnailFromFile(
311311
return width, height, nil
312312
}
313313

314-
func ReadFile(src string) (image.Image, error) {
315-
return readFile(src)
314+
func GetImageSize(src string) (width int, height int, err error) {
315+
img, err := readFile(src)
316+
if err != nil {
317+
return 0, 0, err
318+
}
319+
return img.Bounds().Dx(), img.Bounds().Dy(), nil
316320
}

mediaapi/types/types.go

+2
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ type UrlPreview struct {
119119
ImageHeight int `json:"og:image:height"`
120120
ImageWidth int `json:"og:image:width"`
121121
Title string `json:"og:title"`
122+
Type string `json:"og:type"`
123+
Url string `json:"og:url"`
122124
}
123125

124126
type UrlPreviewResult struct {

setup/config/config_mediaapi.go

-6
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,6 @@ func (c *MediaAPI) Defaults(opts DefaultOpts) {
7575
}
7676
c.BasePath = "./media_store"
7777
}
78-
79-
c.UrlPreviewThumbnailSize = ThumbnailSize{
80-
Width: 200,
81-
Height: 200,
82-
ResizeMethod: "scale",
83-
}
8478
}
8579

8680
func (c *MediaAPI) Verify(configErrs *ConfigErrors) {

0 commit comments

Comments
 (0)