adding op and standarderror in printer package

This commit is contained in:
Julien Neuhart
2019-07-08 11:16:47 +02:00
parent 70b185a37a
commit 186c09f29b
4 changed files with 47 additions and 26 deletions

View File

@@ -12,6 +12,7 @@ import (
"github.com/mafredri/cdp/protocol/page" "github.com/mafredri/cdp/protocol/page"
"github.com/mafredri/cdp/protocol/target" "github.com/mafredri/cdp/protocol/target"
"github.com/mafredri/cdp/rpcc" "github.com/mafredri/cdp/rpcc"
"github.com/thecodingmachine/gotenberg/internal/pkg/standarderror"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
) )
@@ -37,24 +38,26 @@ type ChromeOptions struct {
} }
func (p *chrome) Print(destination string) error { func (p *chrome) Print(destination string) error {
const op = "printer.chrome.Print"
// FIXME duration not working with float
duration := time.Duration(p.opts.WaitTimeout+p.opts.WaitDelay) * time.Second duration := time.Duration(p.opts.WaitTimeout+p.opts.WaitDelay) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), duration) ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel() defer cancel()
devt, err := devtool.New("http://localhost:9222").Version(ctx) devt, err := devtool.New("http://localhost:9222").Version(ctx)
if err != nil { if err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
// connect to WebSocket URL (page) that speaks the Chrome DevTools Protocol. // connect to WebSocket URL (page) that speaks the Chrome DevTools Protocol.
devtConn, err := rpcc.DialContext(ctx, devt.WebSocketDebuggerURL) devtConn, err := rpcc.DialContext(ctx, devt.WebSocketDebuggerURL)
if err != nil { if err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
defer devtConn.Close() // nolint: errcheck defer devtConn.Close() // nolint: errcheck
// create a new CDP Client that uses conn. // create a new CDP Client that uses conn.
devtClient := cdp.NewClient(devtConn) devtClient := cdp.NewClient(devtConn)
newContextTarget, err := devtClient.Target.CreateBrowserContext(ctx) newContextTarget, err := devtClient.Target.CreateBrowserContext(ctx)
if err != nil { if err != nil {
return fmt.Errorf("creating new browser context: %v", err) return &standarderror.Error{Op: op, Err: err}
} }
// create a new blank target with the new browser context. // create a new blank target with the new browser context.
createTargetArgs := target. createTargetArgs := target.
@@ -62,13 +65,13 @@ func (p *chrome) Print(destination string) error {
SetBrowserContextID(newContextTarget.BrowserContextID) SetBrowserContextID(newContextTarget.BrowserContextID)
newTarget, err := devtClient.Target.CreateTarget(ctx, createTargetArgs) newTarget, err := devtClient.Target.CreateTarget(ctx, createTargetArgs)
if err != nil { if err != nil {
return fmt.Errorf("creating new blank target: %v", err) return &standarderror.Error{Op: op, Err: err}
} }
// connect the client to the new target. // connect the client to the new target.
newTargetWsURL := fmt.Sprintf("ws://127.0.0.1:9222/devtools/page/%s", newTarget.TargetID) newTargetWsURL := fmt.Sprintf("ws://127.0.0.1:9222/devtools/page/%s", newTarget.TargetID)
newContextConn, err := rpcc.DialContext(ctx, newTargetWsURL) newContextConn, err := rpcc.DialContext(ctx, newTargetWsURL)
if err != nil { if err != nil {
return fmt.Errorf("connecting client to blank target: %v", err) return &standarderror.Error{Op: op, Err: err}
} }
defer newContextConn.Close() // nolint: errcheck defer newContextConn.Close() // nolint: errcheck
// create a new CDP Client that uses newContextConn. // create a new CDP Client that uses newContextConn.
@@ -83,10 +86,10 @@ func (p *chrome) Print(destination string) error {
func() error { return targetClient.Page.Enable(ctx) }, func() error { return targetClient.Page.Enable(ctx) },
func() error { return targetClient.Runtime.Enable(ctx) }, func() error { return targetClient.Runtime.Enable(ctx) },
); err != nil { ); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
if err := p.navigate(ctx, targetClient); err != nil { if err := p.navigate(ctx, targetClient); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
print, err := targetClient.Page.PrintToPDF( print, err := targetClient.Page.PrintToPDF(
ctx, ctx,
@@ -104,41 +107,42 @@ func (p *chrome) Print(destination string) error {
SetPrintBackground(true), SetPrintBackground(true),
) )
if err != nil { if err != nil {
return fmt.Errorf("printing page to PDF: %v", err) return &standarderror.Error{Op: op, Err: err}
} }
if err := ioutil.WriteFile(destination, print.Data, 0644); err != nil { if err := ioutil.WriteFile(destination, print.Data, 0644); err != nil {
return fmt.Errorf("%s: writing file: %v", destination, err) return &standarderror.Error{Op: op, Err: err}
} }
return nil return nil
} }
func (p *chrome) navigate(ctx context.Context, client *cdp.Client) error { func (p *chrome) navigate(ctx context.Context, client *cdp.Client) error {
const op = "printer.chrome.navigate"
// make sure Page events are enabled. // make sure Page events are enabled.
if err := client.Page.Enable(ctx); err != nil { if err := client.Page.Enable(ctx); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
// make sure Network events are enabled. // make sure Network events are enabled.
if err := client.Network.Enable(ctx, nil); err != nil { if err := client.Network.Enable(ctx, nil); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
// create all clients for events. // create all clients for events.
domContentEventFired, err := client.Page.DOMContentEventFired(ctx) domContentEventFired, err := client.Page.DOMContentEventFired(ctx)
if err != nil { if err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
defer domContentEventFired.Close() // nolint: errcheck defer domContentEventFired.Close() // nolint: errcheck
loadEventFired, err := client.Page.LoadEventFired(ctx) loadEventFired, err := client.Page.LoadEventFired(ctx)
if err != nil { if err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
defer loadEventFired.Close() // nolint: errcheck defer loadEventFired.Close() // nolint: errcheck
loadingFinished, err := client.Network.LoadingFinished(ctx) loadingFinished, err := client.Network.LoadingFinished(ctx)
if err != nil { if err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
defer loadingFinished.Close() // nolint: errcheck defer loadingFinished.Close() // nolint: errcheck
if _, err := client.Page.Navigate(ctx, page.NewNavigateArgs(p.url)); err != nil { if _, err := client.Page.Navigate(ctx, page.NewNavigateArgs(p.url)); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
if err := runBatch( if err := runBatch(
// wait for all events. // wait for all events.
@@ -146,9 +150,10 @@ func (p *chrome) navigate(ctx context.Context, client *cdp.Client) error {
func() error { _, err := loadEventFired.Recv(); return err }, func() error { _, err := loadEventFired.Recv(); return err },
func() error { _, err := loadingFinished.Recv(); return err }, func() error { _, err := loadingFinished.Recv(); return err },
); err != nil { ); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
// wait for a given amount of time (useful for javascript delay). // wait for a given amount of time (useful for javascript delay).
// FIXME duration not working with float
time.Sleep(time.Duration(p.opts.WaitDelay) * time.Second) time.Sleep(time.Duration(p.opts.WaitDelay) * time.Second)
return nil return nil
} }

View File

@@ -10,27 +10,29 @@ import (
"github.com/labstack/gommon/random" "github.com/labstack/gommon/random"
"github.com/microcosm-cc/bluemonday" "github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday/v2" "github.com/russross/blackfriday/v2"
"github.com/thecodingmachine/gotenberg/internal/pkg/standarderror"
) )
// NewMarkdown returns a Markdown printer. // NewMarkdown returns a Markdown printer.
func NewMarkdown(fpath string, opts *ChromeOptions) (Printer, error) { func NewMarkdown(fpath string, opts *ChromeOptions) (Printer, error) {
const op = "printer.NewMarkdown"
tmpl, err := template. tmpl, err := template.
New(filepath.Base(fpath)). New(filepath.Base(fpath)).
Funcs(template.FuncMap{"toHTML": markdownToHTML}). Funcs(template.FuncMap{"toHTML": markdownToHTML}).
ParseFiles(fpath) ParseFiles(fpath)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s: parsing template: %v", fpath, err) return nil, &standarderror.Error{Op: op, Err: err}
} }
dirPath := filepath.Dir(fpath) dirPath := filepath.Dir(fpath)
data := &templateData{DirPath: dirPath} data := &templateData{DirPath: dirPath}
var buffer bytes.Buffer var buffer bytes.Buffer
if err := tmpl.Execute(&buffer, data); err != nil { if err := tmpl.Execute(&buffer, data); err != nil {
return nil, fmt.Errorf("%s: executing template: %v", fpath, err) return nil, &standarderror.Error{Op: op, Err: err}
} }
baseFilename := random.String(32) baseFilename := random.String(32)
dst := fmt.Sprintf("%s/%s.html", dirPath, baseFilename) dst := fmt.Sprintf("%s/%s.html", dirPath, baseFilename)
if err := ioutil.WriteFile(dst, buffer.Bytes(), 0644); err != nil { if err := ioutil.WriteFile(dst, buffer.Bytes(), 0644); err != nil {
return nil, fmt.Errorf("%s: writing file: %v", dst, err) return nil, &standarderror.Error{Op: op, Err: err}
} }
URL := fmt.Sprintf("file://%s", dst) URL := fmt.Sprintf("file://%s", dst)
return &chrome{ return &chrome{
@@ -44,10 +46,11 @@ type templateData struct {
} }
func markdownToHTML(dirPath, filename string) (template.HTML, error) { func markdownToHTML(dirPath, filename string) (template.HTML, error) {
const op = "printer.markdownToHTML"
fpath := fmt.Sprintf("%s/%s", dirPath, filename) fpath := fmt.Sprintf("%s/%s", dirPath, filename)
b, err := ioutil.ReadFile(fpath) b, err := ioutil.ReadFile(fpath)
if err != nil { if err != nil {
return "", fmt.Errorf("%s: reading file: %v", fpath, err) return "", &standarderror.Error{Op: op, Err: err}
} }
unsafe := blackfriday.Run(b) unsafe := blackfriday.Run(b)
content := bluemonday.UGCPolicy().SanitizeBytes(unsafe) content := bluemonday.UGCPolicy().SanitizeBytes(unsafe)

View File

@@ -2,9 +2,10 @@ package printer
import ( import (
"context" "context"
"fmt"
"os/exec" "os/exec"
"time" "time"
"github.com/thecodingmachine/gotenberg/internal/pkg/standarderror"
) )
type merge struct { type merge struct {
@@ -28,7 +29,9 @@ func NewMerge(fpaths []string, opts *MergeOptions) Printer {
} }
func (p *merge) Print(destination string) error { func (p *merge) Print(destination string) error {
const op = "printer.merge.Print"
if p.ctx == nil { if p.ctx == nil {
// FIXME duration not working with float
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.opts.WaitTimeout)*time.Second) ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.opts.WaitTimeout)*time.Second)
defer cancel() defer cancel()
p.ctx = ctx p.ctx = ctx
@@ -39,7 +42,7 @@ func (p *merge) Print(destination string) error {
cmd := exec.CommandContext(p.ctx, "pdftk", cmdArgs...) cmd := exec.CommandContext(p.ctx, "pdftk", cmdArgs...)
_, err := cmd.Output() _, err := cmd.Output()
if err != nil { if err != nil {
return fmt.Errorf("pdtk: %v", err) return &standarderror.Error{Op: op, Err: err}
} }
return nil return nil
} }

View File

@@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/labstack/gommon/random" "github.com/labstack/gommon/random"
"github.com/thecodingmachine/gotenberg/internal/pkg/standarderror"
) )
type office struct { type office struct {
@@ -33,6 +34,8 @@ func NewOffice(fpaths []string, opts *OfficeOptions) Printer {
} }
func (p *office) Print(destination string) error { func (p *office) Print(destination string) error {
const op = "printer.office.Print"
// FIXME duration not working with float
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.opts.WaitTimeout)*time.Second) ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.opts.WaitTimeout)*time.Second)
defer cancel() defer cancel()
fpaths := make([]string, len(p.fpaths)) fpaths := make([]string, len(p.fpaths))
@@ -41,24 +44,31 @@ func (p *office) Print(destination string) error {
baseFilename := random.String(32) baseFilename := random.String(32)
tmpDest := fmt.Sprintf("%s/%d%s.pdf", dirPath, i, baseFilename) tmpDest := fmt.Sprintf("%s/%d%s.pdf", dirPath, i, baseFilename)
if err := unoconv(ctx, fpath, tmpDest, p.opts); err != nil { if err := unoconv(ctx, fpath, tmpDest, p.opts); err != nil {
return err return &standarderror.Error{Op: op, Err: err}
} }
fpaths[i] = tmpDest fpaths[i] = tmpDest
} }
if len(fpaths) == 1 { if len(fpaths) == 1 {
return os.Rename(fpaths[0], destination) if err := os.Rename(fpaths[0], destination); err != nil {
return &standarderror.Error{Op: op, Err: err}
}
return nil
} }
m := &merge{ m := &merge{
ctx: ctx, ctx: ctx,
fpaths: fpaths, fpaths: fpaths,
} }
return m.Print(destination) if err := m.Print(destination); err != nil {
return &standarderror.Error{Op: op, Err: err}
}
return nil
} }
// nolint: gochecknoglobals // nolint: gochecknoglobals
var mu sync.Mutex var mu sync.Mutex
func unoconv(ctx context.Context, fpath, destination string, opts *OfficeOptions) error { func unoconv(ctx context.Context, fpath, destination string, opts *OfficeOptions) error {
const op = "printer.unoconv"
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
cmdArgs := []string{ cmdArgs := []string{
@@ -76,7 +86,7 @@ func unoconv(ctx context.Context, fpath, destination string, opts *OfficeOptions
) )
_, err := cmd.Output() _, err := cmd.Output()
if err != nil { if err != nil {
return fmt.Errorf("unoconv: %v", err) return &standarderror.Error{Op: op, Err: err}
} }
return nil return nil
} }