github.com/coincircle/mattermost-server@v4.8.1-0.20180321182714-9d701c704416+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  
    21  func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) {
    22  	if !*c.App.Config().ServiceSettings.EnableLinkPreviews {
    23  		c.Err = model.NewAppError("getOpenGraphMetadata", "api.post.link_preview_disabled.app_error", nil, "", http.StatusNotImplemented)
    24  		return
    25  	}
    26  
    27  	props := model.StringInterfaceFromJson(r.Body)
    28  
    29  	url := ""
    30  	ok := false
    31  	if url, ok = props["url"].(string); len(url) == 0 || !ok {
    32  		c.SetInvalidParam("url")
    33  		return
    34  	}
    35  
    36  	ogJSONGeneric, ok := openGraphDataCache.Get(url)
    37  	if ok {
    38  		w.Write(ogJSONGeneric.([]byte))
    39  		return
    40  	}
    41  
    42  	og := c.App.GetOpenGraphMetadata(url)
    43  
    44  	ogJSON, err := og.ToJSON()
    45  	openGraphDataCache.AddWithExpiresInSecs(props["url"], ogJSON, 3600) // Cache would expire after 1 hour
    46  	if err != nil {
    47  		w.Write([]byte(`{"url": ""}`))
    48  		return
    49  	}
    50  
    51  	w.Write(ogJSON)
    52  }