Exemple #1
0
func renderTemplate(filepath string, data map[string]interface{}) []byte {

	var out string
	var err error
	var template pongo2.Template

	// Read the template from the disk every time
	if ServerConfig.Debug {
		newTemplate, err := pongo2.FromFile(filepath)
		if err != nil {
			panic(err)
		}
		template = *newTemplate

	} else {
		// Read the template and cache it
		cached, ok := templateCache[filepath]
		if ok == false {
			newTemplate, err := pongo2.FromFile(filepath)
			if err != nil {
				panic(err)
			}
			templateCache[filepath] = *newTemplate
			cached = *newTemplate
		}
		template = cached
	}

	out, err = template.Execute(data)
	if err != nil {
		panic(err)
	}
	return []byte(out)
}
Exemple #2
0
func (d *Data) renderLowLevel(dst string, src string, prefix string, r io.Reader) error {
	var err error

	// Determine the filename and whether we're dealing with a template
	var tpl *pongo2.Template = nil
	filename := src
	if strings.HasSuffix(filename, ".tpl") {
		var buf bytes.Buffer
		if _, err := io.Copy(&buf, r); err != nil {
			return err
		}

		base := filepath.Dir(filename)
		if prefix != "" {
			base = filepath.Join(prefix, base)
		}

		// Create the template set so we can control loading
		tplSet := pongo2.NewSet("otto", &tplLoader{
			Data: d,
			Base: base,
		})

		// Parse the template
		dst = strings.TrimSuffix(dst, ".tpl")
		tpl, err = tplSet.FromString(buf.String())
		if err != nil {
			return err
		}
	}

	// Make the directory containing the final path.
	dir := filepath.Dir(dst)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	// Create the file itself
	f, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer f.Close()

	// If it isn't a template, do a direct byte copy
	if tpl == nil {
		_, err = io.Copy(f, r)
		return err
	}

	return tpl.ExecuteWriter(d.Context, f)
}
Exemple #3
0
func renderTemplate(tpl *pongo2.Template, context pongo2.Context, r *http.Request, writer io.Writer) error {
	if Config.siteName == "" {
		parts := strings.Split(r.Host, ":")
		context["sitename"] = parts[0]
	} else {
		context["sitename"] = Config.siteName
	}

	context["sitepath"] = Config.sitePath
	context["using_auth"] = Config.authFile != ""

	return tpl.ExecuteWriter(context, writer)
}
func (p *pongoRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
	file := data[0].(string)
	ctx := data[1].(pongo2.Context)
	var t *pongo2.Template

	if tmpl, ok := p.cache[file]; ok {
		t = tmpl
	} else {
		tmpl, err := pongo2.FromFile(file)
		if err != nil {
			return err
		}
		p.cache[file] = tmpl
		t = tmpl
	}
	writeHeader(w, code, "text/html")
	return t.ExecuteWriter(ctx, w)
}
Exemple #5
0
func (p *Render) Render(w http.ResponseWriter, code int, data ...interface{}) error {
	file := "templates/" + data[0].(string)
	ctx := data[1].(pongo2.Context)
	var t *pongo2.Template

	if tmpl, ok := p.cache[file]; ok {
		t = tmpl
	} else {
		if options.Debug {
			tmpl, err := pongo2.FromFile(file)
			if err != nil {
				return err
			}
			t = tmpl
		} else {
			buff, err := server.Asset(file)
			if err == nil {
				tmpl, err := pongo2.FromString(string(buff))
				if err != nil {
					return err
				}
				t = tmpl
			} else {
				tmpl, err := pongo2.FromFile(file)
				if err != nil {
					return err
				}
				t = tmpl
			}

		}
		p.cache[file] = t
	}
	writeHeader(w, code, "text/html")
	return t.ExecuteWriter(ctx, w)
}
Exemple #6
0
func fileDisplayHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	fileName := c.URLParams["name"]
	filePath := path.Join(Config.filesDir, fileName)

	err := checkFile(fileName)
	if err == NotFoundErr {
		notFoundHandler(c, w, r)
		return
	}

	metadata, err := metadataRead(fileName)
	if err != nil {
		oopsHandler(c, w, r, RespAUTO, "Corrupt metadata.")
		return
	}
	var expiryHuman string
	if metadata.Expiry != neverExpire {
		expiryHuman = humanize.RelTime(time.Now(), metadata.Expiry, "", "")
	}
	sizeHuman := humanize.Bytes(uint64(metadata.Size))
	extra := make(map[string]string)

	file, _ := os.Open(filePath)
	defer file.Close()

	header := make([]byte, 512)
	file.Read(header)

	extension := strings.TrimPrefix(filepath.Ext(fileName), ".")

	if strings.EqualFold("application/json", r.Header.Get("Accept")) {
		js, _ := json.Marshal(map[string]string{
			"filename":  fileName,
			"expiry":    strconv.FormatInt(metadata.Expiry.Unix(), 10),
			"size":      strconv.FormatInt(metadata.Size, 10),
			"mimetype":  metadata.Mimetype,
			"sha256sum": metadata.Sha256sum,
		})
		w.Write(js)
		return
	}

	var tpl *pongo2.Template

	if strings.HasPrefix(metadata.Mimetype, "image/") {
		tpl = Templates["display/image.html"]

	} else if strings.HasPrefix(metadata.Mimetype, "video/") {
		tpl = Templates["display/video.html"]

	} else if strings.HasPrefix(metadata.Mimetype, "audio/") {
		tpl = Templates["display/audio.html"]

	} else if metadata.Mimetype == "application/pdf" {
		tpl = Templates["display/pdf.html"]

	} else if supportedBinExtension(extension) {
		if metadata.Size < maxDisplayFileSizeBytes {
			bytes, err := ioutil.ReadFile(filePath)
			if err == nil {
				extra["extension"] = extension
				extra["lang_hl"], extra["lang_ace"] = extensionToHlAndAceLangs(extension)
				extra["contents"] = string(bytes)
				tpl = Templates["display/bin.html"]
			}
		}
	} else if extension == "md" {
		if metadata.Size < maxDisplayFileSizeBytes {
			bytes, err := ioutil.ReadFile(filePath)
			if err == nil {
				unsafe := blackfriday.MarkdownCommon(bytes)
				html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)

				extra["contents"] = string(html)
				tpl = Templates["display/md.html"]
			}
		}
	}

	// Catch other files
	if tpl == nil {
		tpl = Templates["display/file.html"]
	}

	err = tpl.ExecuteWriter(pongo2.Context{
		"mime":     metadata.Mimetype,
		"filename": fileName,
		"size":     sizeHuman,
		"expiry":   expiryHuman,
		"extra":    extra,
		"files":    metadata.ArchiveFiles,
	}, w)

	if err != nil {
		oopsHandler(c, w, r, RespHTML, "")
	}
}
Exemple #7
0
func fileDisplayHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	fileName := c.URLParams["name"]
	filePath := path.Join(Config.filesDir, fileName)
	fileInfo, err := os.Stat(filePath)

	if !fileExistsAndNotExpired(fileName) {
		notFoundHandler(c, w, r)
		return
	}

	expiry, _ := metadataGetExpiry(fileName)
	var expiryHuman string
	if !expiry.IsZero() {
		expiryHuman = humanize.RelTime(time.Now(), expiry, "", "")
	}
	sizeHuman := humanize.Bytes(uint64(fileInfo.Size()))
	extra := make(map[string]string)

	file, _ := os.Open(filePath)
	header := make([]byte, 512)
	file.Read(header)
	file.Close()

	mimetype := mimemagic.Match("", header)
	extension := strings.TrimPrefix(filepath.Ext(fileName), ".")

	if strings.EqualFold("application/json", r.Header.Get("Accept")) {
		js, _ := json.Marshal(map[string]string{
			"filename": fileName,
			"mimetype": mimetype,
			"expiry":   strconv.FormatInt(expiry.Unix(), 10),
			"size":     strconv.FormatInt(fileInfo.Size(), 10),
		})
		w.Write(js)
		return
	}

	var tpl *pongo2.Template

	if strings.HasPrefix(mimetype, "image/") {
		tpl = Templates["display/image.html"]
	} else if strings.HasPrefix(mimetype, "video/") {
		tpl = Templates["display/video.html"]
	} else if strings.HasPrefix(mimetype, "audio/") {
		tpl = Templates["display/audio.html"]
	} else if mimetype == "application/pdf" {
		tpl = Templates["display/pdf.html"]
	} else if supportedBinExtension(extension) {
		if fileInfo.Size() < maxDisplayFileSizeBytes {
			bytes, err := ioutil.ReadFile(filePath)
			if err != nil {
				tpl = Templates["display/file.html"]
			} else {
				extra["extension"] = extension
				extra["lang_hl"], extra["lang_ace"] = extensionToHlAndAceLangs(extension)
				extra["contents"] = string(bytes)
				tpl = Templates["display/bin.html"]
			}
		} else {
			tpl = Templates["display/file.html"]
		}
	} else {
		tpl = Templates["display/file.html"]
	}

	err = tpl.ExecuteWriter(pongo2.Context{
		"mime":     mimetype,
		"filename": fileName,
		"size":     sizeHuman,
		"expiry":   expiryHuman,
		"extra":    extra,
	}, w)

	if err != nil {
		oopsHandler(c, w, r, RespHTML, "")
	}
}
Exemple #8
0
func RenderTemplate(t *pongo2.Template, w io.Writer, data interface{}) error {
	return t.ExecuteWriter(pongo2.Context{"v": data}.Update(baseContext), w)
}