Skip to content

Commit

Permalink
Merge pull request #21 from flimzy/body
Browse files Browse the repository at this point in the history
Card bodies
  • Loading branch information
flimzy committed Sep 11, 2016
2 parents 8770028 + 236f13e commit 470a14f
Show file tree
Hide file tree
Showing 15 changed files with 320 additions and 343 deletions.
12 changes: 7 additions & 5 deletions fserve/fserve.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import (
"sync"

"github.com/flimzy/go-pouchdb"
"github.com/flimzy/log"
"github.com/gopherjs/gopherjs/js"
"github.com/gopherjs/jsbuiltin"
"github.com/pkg/errors"

"github.com/FlashbackSRS/flashback-model"
"github.com/FlashbackSRS/flashback/repository"
Expand All @@ -23,17 +25,17 @@ func Init(wg *sync.WaitGroup) {
data := e.Get("data").String()
var msg Message
if err := json.Unmarshal([]byte(data), &msg); err != nil {
fmt.Printf("Error decoding message from iframe: %s\n", err)
log.Printf("Error decoding message from iframe: %s", err)
return
}
go func() {
data, err := fetchFile(&msg)
if err != nil {
fmt.Printf("Error fetching file: %s\n", err)
log.Printf("Error fetching file: %s\n", err)
return
}
if err := sendResponse(&msg, data); err != nil {
fmt.Printf("Error sending response to iframe: %s\n", err)
log.Printf("Error sending response to iframe: %s\n", err)
return
}
}()
Expand All @@ -45,7 +47,7 @@ func fetchFile(req *Message) (*string, error) {
for _, id := range []string{req.NoteId, req.ModelId} {
file, err := fetchAttachment(id, req.Path)
if file != nil || err != nil {
return file, err
return file, errors.Wrap(err, "Error fetching attachment")
}
}
switch req.Path {
Expand All @@ -54,7 +56,7 @@ func fetchFile(req *Message) (*string, error) {
case "style.css":
return encodeFile("text/css", []byte("/* CSS placeholder */")), nil
}
return nil, fmt.Errorf("File not found: %s", req.Path)
return nil, errors.Errorf("Attachment not found: %s", req.Path)
}

func sendResponse(req *Message, data *string) error {
Expand Down
128 changes: 89 additions & 39 deletions repository/card.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@ package repo

import (
"bytes"
"encoding/base64"
"encoding/hex"
"fmt"
"html/template"
"math/rand"
"strconv"
"time"

"github.com/PuerkitoBio/goquery"
"github.com/flimzy/log"

"github.com/pkg/errors"
"golang.org/x/net/html"

"github.com/flimzy/go-pouchdb"
"github.com/pkg/errors"

"github.com/FlashbackSRS/flashback-model"
"github.com/FlashbackSRS/flashback/util"
Expand Down Expand Up @@ -55,22 +57,25 @@ func (c *Card) fetchNote() error {
return nil
}

/*
func (c *Card) modelID() (string, int, error) {
parts := strings.Split(c.Identity(), ".")
if len(parts) != 3 {
return "", 0, errors.New("Invalid card ID: " + c.Identity())
}
modelID, err := strconv.Atoi(parts[2])
// GetCard fetches the requested card
func (u *User) GetCard(id string) (*Card, error) {
db, err := u.DB()
if err != nil {
return "", 0, errors.Wrap(err, "Unable to parse ModelID")
return nil, errors.Wrap(err, "Unable to connect to User DB")
}
return "theme-" + parts[1], modelID, nil

card := &fb.Card{}
if err := db.Get(id, card, pouchdb.Options{}); err != nil {
return nil, errors.Wrap(err, "Unable to fetch requested card")
}
return &Card{
Card: card,
db: db,
}, nil
}
*/

// GetCard isn't currently used (???) FIXME
func GetCard() (*Card, error) {
// GetRandomCard returns a random card
func GetRandomCard() (*Card, error) {
c := &Card{}
if err := c.fetchArbitraryCard(); err != nil {
return nil, err
Expand All @@ -81,12 +86,12 @@ func GetCard() (*Card, error) {
func (c *Card) fetchArbitraryCard() error {
u, err := CurrentUser()
if err != nil {
return err
return errors.Wrap(err, "No user logged in")
}
if c.db == nil {
db, err := u.DB()
if err != nil {
return err
return errors.Wrap(err, "Error connecting to User DB")
}
c.db = db
}
Expand Down Expand Up @@ -161,30 +166,35 @@ func (c *Card) Body() (string, string, error) {
if body == nil {
return "", "", errors.New("No <body> in the template output")
}
fmt.Printf("%s\n", htmlDoc)
/*
container := findContainer(body.FirstChild, c.ModelID(), "question")
if container == nil {
return "", "", errors.New("No matching div found in template output")
}
// Delete unused divs
for c := body.FirstChild; c != nil; c = body.FirstChild {
body.RemoveChild(c)
}
inner := container.FirstChild
inner.Parent = body
body.FirstChild = inner
log.Debugf("%s", htmlDoc)

newBody := new(bytes.Buffer)
if err := html.Render(newBody, doc); err != nil {
return "", "", errors.Wrap(err, "Error rendering new HTML")
}
nbString := newBody.String()
fmt.Printf("original size = %d\n", len(htmlDoc.String()))
fmt.Printf("new body size = %d\n", len(nbString))
return nbString, ctx.IframeID, nil
*/
return "", "", nil
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
}

const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Expand Down Expand Up @@ -251,3 +261,43 @@ func findContainer(n *html.Node, targetID, targetClass string) *html.Node {
}
return findContainer(n.NextSibling, targetID, targetClass)
}

func (c *Card) inlineSrc(n *html.Node) error {
doc := goquery.NewDocumentFromNode(n)
doc.Find("img").Each(func(i int, s *goquery.Selection) {
src, ok := s.Attr("src")
if !ok {
log.Print("Found an image with no source!!??")
return
}
log.Debugf("Found image with src of '%s'", src)
att, err := c.GetAttachment(src)
if err != nil {
log.Printf("Error inlining file '%s': %s", src, err)
return
}
s.SetAttr("src", fmt.Sprintf("data:%s;base64,%s", att.ContentType, base64.StdEncoding.EncodeToString(att.Content)))
// iframe.Set("src", "data:text/html;charset=utf-8;base64,"+base64.StdEncoding.EncodeToString([]byte(body)))
})
return nil
}

// GetAttachment fetches an attachment from the note, failling back to the model
func (c *Card) GetAttachment(filename string) (*Attachment, error) {
n, err := c.Note()
if err != nil {
return nil, errors.Wrap(err, "Error fetching Note for GetAttachment()")
}
if file, ok := n.Attachments.GetFile(filename); ok {
return &Attachment{file}, nil
}

m, err := n.Model()
if err != nil {
return nil, errors.Wrap(err, "Error fetching Model for GetAttachments()")
}
if file, ok := m.Files.GetFile(filename); ok {
return &Attachment{file}, nil
}
return nil, errors.Errorf("File '%s' not found", filename)
}
9 changes: 9 additions & 0 deletions repository/files.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package repo

import (
"github.com/FlashbackSRS/flashback-model"
)

type Attachment struct {
*fb.Attachment
}
16 changes: 9 additions & 7 deletions repository/note.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,19 @@ func (n *Note) fetchTheme() error {
// Nothing to do
return nil
}
ThemeID := "theme-" + n.ThemeID
log.Debugf("Fetching theme %s", ThemeID)
log.Debugf("Fetching theme %s", n.ThemeID)
t := &fb.Theme{}
if err := n.db.Get(ThemeID, t, pouchdb.Options{Attachments: true}); err != nil {
if err := n.db.Get(n.ThemeID, t, pouchdb.Options{Attachments: true}); err != nil {
fmt.Printf("Error: %s\n", err)
return errors.Wrapf(err, "fetchTheme() can't fetch theme-%s", ThemeID)
return errors.Wrapf(err, "fetchTheme() can't fetch %s", n.ThemeID)
}
m := t.Models[n.ModelID]
n.theme = &Theme{t}
n.model = &Model{t.Models[n.ModelID]}
n.model = &Model{m}
n.model.Theme = t
fmt.Printf("Fetched this model: %v\n", n.model)
fmt.Printf("Fetched this theme: %v\n", n.theme)
n.SetModel(m)

log.Debugf("Fetched this model: %v\n", n.model)
log.Debugf("Fetched this theme: %v\n", n.theme)
return nil
}
2 changes: 1 addition & 1 deletion repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func NewDB(name string) (*DB, error) {
db := newDB(name)
parts := strings.SplitN(name, "-", 2)
if initFunc, ok := initFuncs[parts[0]]; ok {
log.Debug("Initializing DB %s\n", name)
log.Debugf("Initializing DB %s", name)
return db, initFunc(db)
}
return db, nil
Expand Down
2 changes: 1 addition & 1 deletion repository/test/Art.fbb

Large diffs are not rendered by default.

Loading

0 comments on commit 470a14f

Please sign in to comment.