odds-crawler-backend/pkg/v1/cdp/cdp-service.go
2019-05-12 19:58:43 +09:00

87 lines
2.0 KiB
Go

package cdp
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
_cdp "git.loafle.net/chrome_devtools_protocol/cdp-go/pkg/cdp"
"git.loafle.net/chrome_devtools_protocol/protocol-go/pkg/cdp"
"git.loafle.net/chrome_devtools_protocol/protocol-go/pkg/page"
api_cdp "git.loafle.net/odds_crawler/odds-crawler-proto/pkg/api/v1/cdp"
)
const (
// apiVersion is version of API is provided by server
apiVersion = "v1"
)
// cdpServiceServer is implementation of v1.CDPServiceServer proto interface
type cdpServiceServer struct {
ctx context.Context
cancel context.CancelFunc
}
// NewCDPServiceServer creates ToDo service
func NewCDPServiceServer() api_cdp.CDPServiceServer {
ctx, cancel := _cdp.NewContext(
context.Background(),
)
return &cdpServiceServer{
ctx: ctx,
cancel: cancel,
}
}
func (s *cdpServiceServer) checkAPI(api string) error {
// API version is "" means use current version of the service
if len(api) > 0 {
if apiVersion != api {
return status.Errorf(codes.Unimplemented,
"unsupported API version: service implements API version '%s', but asked for '%s'", apiVersion, api)
}
}
return nil
}
func (s *cdpServiceServer) Navigate(ctx context.Context, req *api_cdp.NavigateRequest) (*api_cdp.NavigateReply, error) {
if err := s.checkAPI(req.Api); err != nil {
return nil, err
}
var res *api_cdp.NavigateReply
err :=
_cdp.Run(s.ctx,
_cdp.Tasks{
_cdp.ActionFunc(func(ctx context.Context) error {
params := page.Navigate(req.Url)
params.WithReferrer(req.Referrer)
params.WithTransitionType(page.TransitionType(req.TransitionType))
params.WithFrameID(cdp.FrameID(req.FrameID))
frameID, loaderID, errorText, err := params.Do(s.ctx)
if nil != err {
return err
}
res = &api_cdp.NavigateReply{
FrameID: frameID.String(),
LoaderID: loaderID.String(),
ErrorText: errorText,
}
return nil
}),
},
)
if nil != err {
return nil, err
}
return res, nil
}