user.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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) error
  12. WithLoginEvent(f func(ctx context.Context, bytes []byte) error) UserBrowserAgent
  13. WithLoginCallback(f func(ctx context.Context, user *UserContext) error) UserBrowserAgent
  14. GetName() string
  15. }
  16. type UserContext struct {
  17. Cookies map[string][]*proto.NetworkCookieParam `json:"cookies"`
  18. LocalStorage map[string]map[string]string `json:"local_storage"`
  19. sync.Mutex
  20. }
  21. func NewUserContext() *UserContext {
  22. return &UserContext{
  23. Cookies: make(map[string][]*proto.NetworkCookieParam),
  24. LocalStorage: make(map[string]map[string]string),
  25. }
  26. }
  27. func (uc *UserContext) WithCookies(name string, cookies []*proto.NetworkCookieParam) *UserContext {
  28. uc.Cookies[name] = cookies
  29. return uc
  30. }
  31. func (uc *UserContext) WithLocalStorage(name string, l map[string]string) *UserContext {
  32. uc.LocalStorage[name] = l
  33. return uc
  34. }
  35. // ToString 将用户上下文转换为字符串
  36. func (uc *UserContext) ToString() (string, error) {
  37. byt, err := json.Marshal(uc)
  38. return string(byt), err
  39. }
  40. // ParseContextFromJson 解析json字符串,设置Cookie
  41. func (uc *UserContext) ParseContextFromJson(jsonStr string) error {
  42. uc1 := &UserContext{}
  43. err := json.Unmarshal([]byte(jsonStr), uc1)
  44. if err != nil {
  45. return err
  46. }
  47. uc.Cookies = uc1.Cookies
  48. uc.LocalStorage = uc1.LocalStorage
  49. return nil
  50. }