github.com/qichengzx/mattermost-server@v4.5.1-0.20180604164826-2c75247c97d0+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/dyatlov/go-opengraph/opengraph" 10 "github.com/mattermost/mattermost-server/model" 11 "github.com/mattermost/mattermost-server/utils" 12 ) 13 14 const OPEN_GRAPH_METADATA_CACHE_SIZE = 10000 15 16 var openGraphDataCache = utils.NewLru(OPEN_GRAPH_METADATA_CACHE_SIZE) 17 18 func (api *API) InitOpenGraph() { 19 api.BaseRoutes.OpenGraph.Handle("", api.ApiSessionRequired(getOpenGraphMetadata)).Methods("POST") 20 21 // Dump the image cache if the proxy settings have changed. (need switch URLs to the correct proxy) 22 api.App.AddConfigListener(func(before, after *model.Config) { 23 if (before.ServiceSettings.ImageProxyType != after.ServiceSettings.ImageProxyType) || 24 (before.ServiceSettings.ImageProxyURL != after.ServiceSettings.ImageProxyType) { 25 openGraphDataCache.Purge() 26 } 27 }) 28 } 29 30 func OpenGraphDataWithProxyAddedToImageURLs(ogdata *opengraph.OpenGraph, toProxyURL func(string) string) *opengraph.OpenGraph { 31 for _, image := range ogdata.Images { 32 var url string 33 if image.SecureURL != "" { 34 url = image.SecureURL 35 } else { 36 url = image.URL 37 } 38 39 image.URL = "" 40 image.SecureURL = toProxyURL(url) 41 } 42 43 return ogdata 44 } 45 46 func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) { 47 if !*c.App.Config().ServiceSettings.EnableLinkPreviews { 48 c.Err = model.NewAppError("getOpenGraphMetadata", "api.post.link_preview_disabled.app_error", nil, "", http.StatusNotImplemented) 49 return 50 } 51 52 props := model.StringInterfaceFromJson(r.Body) 53 54 url := "" 55 ok := false 56 if url, ok = props["url"].(string); len(url) == 0 || !ok { 57 c.SetInvalidParam("url") 58 return 59 } 60 61 ogJSONGeneric, ok := openGraphDataCache.Get(url) 62 if ok { 63 w.Write(ogJSONGeneric.([]byte)) 64 return 65 } 66 67 og := c.App.GetOpenGraphMetadata(url) 68 69 // If image proxy enabled modify open graph data to feed though proxy 70 if toProxyURL := c.App.ImageProxyAdder(); toProxyURL != nil { 71 og = OpenGraphDataWithProxyAddedToImageURLs(og, toProxyURL) 72 } 73 74 ogJSON, err := og.ToJSON() 75 openGraphDataCache.AddWithExpiresInSecs(props["url"], ogJSON, 3600) // Cache would expire after 1 hour 76 if err != nil { 77 w.Write([]byte(`{"url": ""}`)) 78 return 79 } 80 81 w.Write(ogJSON) 82 }