github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/api4/openGraph.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package api4 5 6 import ( 7 "net/http" 8 "time" 9 10 "github.com/masterhung0112/hk_server/v5/model" 11 "github.com/masterhung0112/hk_server/v5/services/cache" 12 ) 13 14 const OpenGraphMetadataCacheSize = 10000 15 16 var openGraphDataCache = cache.NewLRU(cache.LRUOptions{ 17 Size: OpenGraphMetadataCacheSize, 18 }) 19 20 func (api *API) InitOpenGraph() { 21 api.BaseRoutes.OpenGraph.Handle("", api.ApiSessionRequired(getOpenGraphMetadata)).Methods("POST") 22 23 // Dump the image cache if the proxy settings have changed. (need switch URLs to the correct proxy) 24 api.app.AddConfigListener(func(before, after *model.Config) { 25 if (before.ImageProxySettings.Enable != after.ImageProxySettings.Enable) || 26 (before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) || 27 (before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) || 28 (before.ImageProxySettings.RemoteImageProxyOptions != after.ImageProxySettings.RemoteImageProxyOptions) { 29 openGraphDataCache.Purge() 30 } 31 }) 32 } 33 34 func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) { 35 if !*c.App.Config().ServiceSettings.EnableLinkPreviews { 36 c.Err = model.NewAppError("getOpenGraphMetadata", "api.post.link_preview_disabled.app_error", nil, "", http.StatusNotImplemented) 37 return 38 } 39 40 props := model.StringInterfaceFromJson(r.Body) 41 42 url := "" 43 ok := false 44 if url, ok = props["url"].(string); url == "" || !ok { 45 c.SetInvalidParam("url") 46 return 47 } 48 49 var ogJSONGeneric []byte 50 err := openGraphDataCache.Get(url, &ogJSONGeneric) 51 if err == nil { 52 w.Write(ogJSONGeneric) 53 return 54 } 55 56 og := c.App.GetOpenGraphMetadata(url) 57 ogJSON, err := og.ToJSON() 58 openGraphDataCache.SetWithExpiry(url, ogJSON, 1*time.Hour) 59 if err != nil { 60 w.Write([]byte(`{"url": ""}`)) 61 return 62 } 63 64 w.Write(ogJSON) 65 }