Exemplo n.º 1
0
func fetchTranslations(lang string) ([]byte, error) {
	resp, err := http.Get(util.BaseURI() + "translations/" + lang + ".all.json")
	if err != nil {
		return []byte{}, err
	}
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, err
	}
	return content, nil
}
Exemplo n.º 2
0
// Body returns the card's body and iframe ID
func (c *Card) Body() (string, string, error) {
	note, err := c.Note()
	if err != nil {
		return "", "", errors.Wrap(err, "Unable to retrieve Note")
	}
	model, err := note.Model()
	if err != nil {
		return "", "", errors.Wrap(err, "Unable to retrieve Model")
	}
	tmpl, err := model.GenerateTemplate()
	if err != nil {
		return "", "", errors.Wrap(err, "Error generating template")
	}
	ctx := cardContext{
		IframeID: RandString(8),
		Card:     c,
		Note:     note,
		Model:    model,
		BaseURI:  util.BaseURI(),
		Fields:   make(map[string]template.HTML),
	}

	for i, f := range model.Fields {
		switch note.FieldValues[i].Type() {
		case fb.AnkiField, fb.TextField:
			text, e := note.FieldValues[i].Text()
			if e != nil {
				return "", "", errors.Wrap(e, "Unable to fetch text for field value")
			}
			ctx.Fields[f.Name] = template.HTML(text)
		}
	}

	htmlDoc := new(bytes.Buffer)
	if e := tmpl.Execute(htmlDoc, ctx); e != nil {
		return "", "", errors.Wrap(e, "Unable to execute template")
	}
	doc, err := html.Parse(htmlDoc)
	if err != nil {
		return "", "", errors.Wrap(err, "Unable to parse generated HTML")
	}
	body := findBody(doc)
	if body == nil {
		return "", "", errors.New("No <body> in the template output")
	}
	log.Debugf("%s", htmlDoc)

	container := findContainer(body.FirstChild, strconv.Itoa(int(c.TemplateID())), "question")
	if container == nil {
		return "", "", errors.Errorf("No div matching '%d' found in template output", c.TemplateID())
	}
	log.Debug("Found container: %s", container)

	// Delete unused divs
	for c := body.FirstChild; c != nil; c = body.FirstChild {
		body.RemoveChild(c)
	}
	inner := container.FirstChild
	inner.Parent = body
	body.FirstChild = inner

	if err := c.inlineSrc(body); err != nil {
		return "", "", errors.Wrap(err, "Error inlining images")
	}

	newBody := new(bytes.Buffer)
	if err := html.Render(newBody, doc); err != nil {
		return "", "", errors.Wrap(err, "Error rendering new HTML")
	}

	nbString := newBody.String()
	log.Debugf("original size = %d\n", len(htmlDoc.String()))
	log.Debugf("new body size = %d\n", len(nbString))
	return nbString, ctx.IframeID, nil
}