user.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package llm
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/go-rod/rod"
  6. "github.com/go-rod/rod/lib/proto"
  7. "sync"
  8. )
  9. type UserBrowserAgent interface {
  10. IsLogin(ctx context.Context, page *rod.Page) (bool, error)
  11. Login(ctx context.Context, page *rod.Page) (*UserContext, error)
  12. WithLoginEvent(f func(ctx context.Context, bytes []byte) error) UserBrowserAgent
  13. WithLoginCallback(f func(ctx context.Context, user *UserContext) error) UserBrowserAgent
  14. }
  15. type UserContext struct {
  16. Cookies map[string][]*proto.NetworkCookieParam `json:"cookies"`
  17. LocalStorage map[string]map[string]string `json:"local_storage"`
  18. sync.Mutex
  19. }
  20. func NewUserContext() *UserContext {
  21. return &UserContext{
  22. Cookies: make(map[string][]*proto.NetworkCookieParam),
  23. LocalStorage: make(map[string]map[string]string),
  24. }
  25. }
  26. func (uc *UserContext) WithCookies(name string, cookies []*proto.NetworkCookieParam) *UserContext {
  27. uc.Cookies[name] = cookies
  28. return uc
  29. }
  30. func (uc *UserContext) WithLocalStorage(name string, l map[string]string) *UserContext {
  31. uc.LocalStorage[name] = l
  32. return uc
  33. }
  34. // ToString 将用户上下文转换为字符串
  35. func (uc *UserContext) ToString() (string, error) {
  36. byt, err := json.Marshal(uc)
  37. return string(byt), err
  38. }
  39. // ParseContextFromJson 解析json字符串,设置Cookie
  40. func (uc *UserContext) ParseContextFromJson(jsonStr string) error {
  41. uc1 := &UserContext{}
  42. err := json.Unmarshal([]byte(jsonStr), uc1)
  43. if err != nil {
  44. return err
  45. }
  46. uc.Cookies = uc1.Cookies
  47. uc.LocalStorage = uc1.LocalStorage
  48. return nil
  49. }