package webcontroller import ( "io" "io/ioutil" "net/http" "strings" "fornaxian.tech/pixeldrain_server/util" "github.com/Fornaxian/log" "github.com/julienschmidt/httprouter" "github.com/microcosm-cc/bluemonday" blackfriday "github.com/russross/blackfriday/v2" ) // ServeFilePreview controller for GET /u/:id/preview func (wc *WebController) serveFilePreview(w http.ResponseWriter, r *http.Request, p httprouter.Params) { if p.ByName("id") == "demo" || p.ByName("id") == "adsplus" || p.ByName("id") == "pixfuture" { serveFilePreviewDemo(w) // Required for a-ads.com quality check return } apiKey, _ := wc.getAPIKey(r) api := wc.api.Login(apiKey).RealIP(util.RemoteAddress(r)).RealAgent(r.UserAgent()) file, err := api.GetFileInfo(p.ByName("id")) // TODO: Error handling if err != nil { wc.serveNotFound(w, r) return } if strings.HasPrefix(file.MimeType, "text") && (strings.HasSuffix(file.Name, ".md") || strings.HasSuffix(file.Name, ".markdown")) { if file.Size > 1e6 { // Prevent out of memory errors w.Write([]byte("File is too large to view online.\nPlease download and view it locally.")) return } body, err := api.GetFile(file.ID) if err != nil { log.Error("Can't download text file for preview: %s", err) w.Write([]byte("An error occurred while downloading this file.")) return } defer body.Close() bodyBytes, err := ioutil.ReadAll(body) if err != nil { log.Error("Can't read text file for preview: %s", err) w.Write([]byte("An error occurred while reading this file.")) return } w.Write(bluemonday.UGCPolicy().SanitizeBytes(blackfriday.Run(bodyBytes))) } } // ServeFilePreviewDemo serves the content of the demo file. It contains a nice // message to the human reviewers of the a-ads ad network so they can properly // categorize the website. func serveFilePreviewDemo(w http.ResponseWriter) { io.WriteString(w, `
`) }