2018-10-08 03:32:30 +02:00
|
|
|
package html
|
2018-09-18 22:42:38 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2018-09-23 10:33:20 +02:00
|
|
|
"fmt"
|
2018-10-08 03:32:30 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/html/dynamic"
|
|
|
|
"github.com/MontFerret/ferret/pkg/html/static"
|
2018-09-23 10:33:20 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
2018-10-08 03:23:36 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/env"
|
2018-09-18 22:42:38 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
|
|
)
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
type Name string
|
2018-09-27 04:03:06 +02:00
|
|
|
|
|
|
|
const (
|
2018-10-07 04:33:39 +02:00
|
|
|
Dynamic Name = "dynamic"
|
|
|
|
Static Name = "static"
|
2018-09-27 04:03:06 +02:00
|
|
|
)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
|
|
|
type Driver interface {
|
2018-10-07 04:33:39 +02:00
|
|
|
GetDocument(ctx context.Context, url values.String) (values.HTMLNode, error)
|
2018-09-18 22:42:38 +02:00
|
|
|
Close() error
|
|
|
|
}
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
func ToContext(ctx context.Context, name Name, drv Driver) context.Context {
|
2018-09-18 22:42:38 +02:00
|
|
|
return context.WithValue(ctx, name, drv)
|
|
|
|
}
|
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
func FromContext(ctx context.Context, name Name) (Driver, error) {
|
2018-09-18 22:42:38 +02:00
|
|
|
val := ctx.Value(name)
|
|
|
|
|
|
|
|
drv, ok := val.(Driver)
|
|
|
|
|
|
|
|
if ok {
|
2018-09-23 10:33:20 +02:00
|
|
|
return drv, nil
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-09-23 10:33:20 +02:00
|
|
|
return nil, core.Error(core.ErrNotFound, fmt.Sprintf("%s driver", name))
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-10-08 03:23:36 +02:00
|
|
|
func WithDynamicDriver(ctx context.Context) context.Context {
|
|
|
|
e := env.FromContext(ctx)
|
|
|
|
|
|
|
|
return context.WithValue(
|
|
|
|
ctx,
|
|
|
|
Dynamic,
|
|
|
|
dynamic.NewDriver(
|
|
|
|
e.CDPAddress,
|
|
|
|
dynamic.WithProxy(e.ProxyAddress),
|
|
|
|
),
|
|
|
|
)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2018-10-08 03:23:36 +02:00
|
|
|
func WithStaticDriver(ctx context.Context) context.Context {
|
|
|
|
e := env.FromContext(ctx)
|
|
|
|
|
|
|
|
return context.WithValue(
|
|
|
|
ctx,
|
|
|
|
Static,
|
|
|
|
static.NewDriver(
|
|
|
|
static.WithProxy(e.ProxyAddress),
|
|
|
|
),
|
|
|
|
)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|