feat: sign in to IMVU for Access Pass products (#4)
Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #4.
This commit is contained in:
1 parent
dd8205602c
commit
145ebf25c1
11 files changed
+1001
-24
No files matched your search
@@ -0,0 +1,362 @@
|
||||
package imvu
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// APIURL is IMVU's REST API.
|
||||
const APIURL = "https://api.imvu.com"
|
||||
|
||||
// BrowserUserAgent is the User-Agent a signed-in session sends to IMVU's API. IMVU's sign-in works only for a
|
||||
// User-Agent it takes for a desktop browser (verified 2026-11-08): with anything else, even this one with the
|
||||
// importer's name added or a "compatible" one, it answers 500 OUTBOUND VALIDATION-004 (`sauce` is null). The CDN
|
||||
// and the hub get the importer's own User-Agent.
|
||||
const BrowserUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
|
||||
|
||||
// Shop listing: pages of 1000 (IMVU's smaller pages overlap and miss products; t5de-hub's docs/imports.md "Whole
|
||||
// shops"), at most 10 of them.
|
||||
const (
|
||||
shopPage = 1000
|
||||
shopPages = 10
|
||||
)
|
||||
|
||||
// Seen is a product as an account sees it.
|
||||
type Seen struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Rating string `json:"rating"` // "general" or "adult"
|
||||
CreatorID int64 `json:"creatorId"`
|
||||
CreatorName string `json:"creatorName"`
|
||||
Purchasable bool `json:"purchasable"`
|
||||
}
|
||||
|
||||
// ErrSignIn is IMVU refusing a sign-in: a wrong password, a locked account, two-factor sign-in, ...
|
||||
type ErrSignIn struct{ Message string }
|
||||
|
||||
func (e *ErrSignIn) Error() string { return "IMVU refused the sign-in: " + e.Message }
|
||||
|
||||
// ErrSignedOut is a session IMVU no longer takes.
|
||||
var ErrSignedOut = errors.New("IMVU's session ended")
|
||||
|
||||
// Session is an IMVU account signed in to IMVU's API. Its cookies are kept in a file, so a restart doesn't sign in
|
||||
// again (IMVU limits sign-ins).
|
||||
type Session struct {
|
||||
URL string // APIURL, or a test server's
|
||||
UserAgent string // BrowserUserAgent
|
||||
Limiter *Limiter
|
||||
File string // where its cookies are kept (0600)
|
||||
|
||||
jar *cookiejar.Jar
|
||||
client *http.Client
|
||||
UserID int64
|
||||
AccessPass bool
|
||||
}
|
||||
|
||||
type savedCookie struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Expires time.Time `json:"expires"`
|
||||
}
|
||||
|
||||
func (s *Session) init() {
|
||||
if s.client != nil {
|
||||
return
|
||||
}
|
||||
s.jar, _ = cookiejar.New(nil)
|
||||
s.client = &http.Client{Jar: s.jar, Timeout: time.Minute}
|
||||
}
|
||||
|
||||
// Resume restores a saved session and checks it with IMVU: false if there's none, or IMVU no longer takes it.
|
||||
func (s *Session) Resume(ctx context.Context) (bool, error) {
|
||||
s.init()
|
||||
data, err := os.ReadFile(s.File)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var saved []savedCookie
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
u, _ := url.Parse(s.URL)
|
||||
var cookies []*http.Cookie
|
||||
for _, c := range saved {
|
||||
cookies = append(cookies, &http.Cookie{Name: c.Name, Value: c.Value, Expires: c.Expires, Path: "/"})
|
||||
}
|
||||
s.jar.SetCookies(u, cookies)
|
||||
if err := s.me(ctx); err != nil {
|
||||
if errors.Is(err, ErrSignedOut) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// SignIn signs in with a password and keeps the session's cookies.
|
||||
func (s *Session) SignIn(ctx context.Context, username, password string) error {
|
||||
s.init()
|
||||
body := map[string]any{"gdpr_cookie_acceptance": true, "username": username, "password": password, "remember_device": true}
|
||||
status, answer, err := s.call(ctx, http.MethodPost, "/login", body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status/100 != 2 {
|
||||
msg := answerMessage(answer)
|
||||
if msg == "" {
|
||||
msg = fmt.Sprintf("status %d", status)
|
||||
}
|
||||
if status >= 500 {
|
||||
return fmt.Errorf("IMVU's sign-in failed (%s)", msg)
|
||||
}
|
||||
return &ErrSignIn{Message: msg}
|
||||
}
|
||||
if err := s.me(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.save()
|
||||
}
|
||||
|
||||
// Forget removes the saved session.
|
||||
func (s *Session) Forget() {
|
||||
os.Remove(s.File)
|
||||
}
|
||||
|
||||
// me reads who's signed in, and whether they have Access Pass (which IMVU shows the account itself).
|
||||
func (s *Session) me(ctx context.Context) error {
|
||||
status, answer, err := s.call(ctx, http.MethodGet, "/login/me", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status == http.StatusUnauthorized || status == http.StatusForbidden {
|
||||
return ErrSignedOut
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return fmt.Errorf("IMVU answered %d for the session", status)
|
||||
}
|
||||
d := document(answer)
|
||||
user, _ := d["user"].(map[string]any)
|
||||
id := parseID(fmt.Sprint(user["id"]))
|
||||
if id == 0 {
|
||||
id = parseID(fmt.Sprint(d["user"]))
|
||||
}
|
||||
if id == 0 {
|
||||
return errors.New("IMVU's session answer has no user")
|
||||
}
|
||||
s.UserID = id
|
||||
status, answer, err = s.call(ctx, http.MethodGet, "/user/user-"+strconv.FormatInt(id, 10), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return fmt.Errorf("IMVU answered %d for the account", status)
|
||||
}
|
||||
s.AccessPass = document(answer)["is_ap"] == true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) save() error {
|
||||
u, _ := url.Parse(s.URL)
|
||||
var saved []savedCookie
|
||||
for _, c := range s.jar.Cookies(u) {
|
||||
saved = append(saved, savedCookie{Name: c.Name, Value: c.Value, Expires: time.Now().Add(30 * 24 * time.Hour)})
|
||||
}
|
||||
data, err := json.Marshal(saved)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := s.File + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, s.File)
|
||||
}
|
||||
|
||||
// Product is a product as the account sees it; nil if IMVU shows it no product (deleted, or hidden from it).
|
||||
func (s *Session) Product(ctx context.Context, id int64) (*Seen, error) {
|
||||
status, answer, err := s.call(ctx, http.MethodGet, "/product/product-"+strconv.FormatInt(id, 10), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case status == http.StatusOK:
|
||||
case status == http.StatusNotFound || status == http.StatusUnauthorized || status == http.StatusForbidden:
|
||||
if status != http.StatusNotFound {
|
||||
// Hidden even signed in: the session may have ended.
|
||||
if err := s.me(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("IMVU answered %d for product %d", status, id)
|
||||
}
|
||||
p := parseSeen(document(answer), id)
|
||||
if p == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Shop lists a creator's shop as the account sees it (Access Pass products too, with Access Pass). It checks the
|
||||
// session first: signed out, IMVU would list the general-rated products only, without a word.
|
||||
func (s *Session) Shop(ctx context.Context, creator int64) ([]Seen, error) {
|
||||
if err := s.me(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status, answer, err := s.call(ctx, http.MethodGet, "/user/user-"+strconv.FormatInt(creator, 10), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
username, _ := document(answer)["username"].(string)
|
||||
if status != http.StatusOK || username == "" {
|
||||
return nil, fmt.Errorf("IMVU has no account %d (status %d)", creator, status)
|
||||
}
|
||||
seen := map[int64]Seen{}
|
||||
var order []int64
|
||||
path := "/product?creator=" + url.QueryEscape(username) + "&limit=" + strconv.Itoa(shopPage)
|
||||
for page := 0; path != "" && page < shopPages; page++ {
|
||||
status, answer, err := s.call(ctx, http.MethodGet, path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return nil, fmt.Errorf("IMVU answered %d for %s's shop", status, username)
|
||||
}
|
||||
id, _ := answer["id"].(string)
|
||||
den, _ := answer["denormalized"].(map[string]any)
|
||||
entry, _ := den[id].(map[string]any)
|
||||
data, _ := entry["data"].(map[string]any)
|
||||
items, _ := data["items"].([]any)
|
||||
for _, it := range items {
|
||||
ref, _ := it.(string)
|
||||
pid := parseID(ref)
|
||||
if pid == 0 {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[pid]; dup {
|
||||
continue
|
||||
}
|
||||
pe, _ := den[ref].(map[string]any)
|
||||
pd, _ := pe["data"].(map[string]any)
|
||||
if p := parseSeen(pd, pid); p != nil {
|
||||
seen[pid] = *p
|
||||
order = append(order, pid)
|
||||
}
|
||||
}
|
||||
path = ""
|
||||
if rel, ok := entry["relations"].(map[string]any); ok {
|
||||
if next, _ := rel["next"].(string); strings.HasPrefix(next, s.URL+"/") {
|
||||
path = strings.TrimPrefix(next, s.URL)
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]Seen, 0, len(order))
|
||||
for _, id := range order {
|
||||
out = append(out, seen[id])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Session) call(ctx context.Context, method, path string, body any) (int, map[string]any, error) {
|
||||
s.init()
|
||||
if err := s.Limiter.Wait(ctx); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
r = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, s.URL+path, r)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", s.UserAgent)
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
var answer map[string]any
|
||||
json.Unmarshal(data, &answer)
|
||||
return resp.StatusCode, answer, nil
|
||||
}
|
||||
|
||||
// document is an answer's own document's data.
|
||||
func document(answer map[string]any) map[string]any {
|
||||
id, _ := answer["id"].(string)
|
||||
den, _ := answer["denormalized"].(map[string]any)
|
||||
e, _ := den[id].(map[string]any)
|
||||
if e == nil {
|
||||
// Some answers carry one document under another key.
|
||||
for _, v := range den {
|
||||
e, _ = v.(map[string]any)
|
||||
break
|
||||
}
|
||||
}
|
||||
d, _ := e["data"].(map[string]any)
|
||||
return d
|
||||
}
|
||||
|
||||
func answerMessage(answer map[string]any) string {
|
||||
for _, k := range []string{"message", "error"} {
|
||||
if s, ok := answer[k].(string); ok && s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseID takes the number at the end of an IMVU ID or URL ("https://api.imvu.com/product/product-123" → 123).
|
||||
func parseID(s string) int64 {
|
||||
i := strings.LastIndexAny(s, "-/")
|
||||
n, err := strconv.ParseInt(s[i+1:], 10, 64)
|
||||
if err != nil || n <= 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func parseSeen(d map[string]any, id int64) *Seen {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
creator, _ := d["creator_cid"].(float64)
|
||||
name, _ := d["product_name"].(string)
|
||||
if creator <= 0 {
|
||||
return nil
|
||||
}
|
||||
rating := "general"
|
||||
if r, _ := d["rating"].(string); r == "AP" {
|
||||
rating = "adult"
|
||||
}
|
||||
creatorName, _ := d["creator_name"].(string)
|
||||
purchasable := d["is_purchasable"] != false
|
||||
return &Seen{ID: id, Name: strings.TrimSpace(name), Rating: rating, CreatorID: int64(creator), CreatorName: creatorName, Purchasable: purchasable}
|
||||
}
|
||||
Reference in new issue
Block a user