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