feat: sign in to IMVU for Access Pass products (#4)
CI / build (push) Successful in 16s
Release / release (push) Successful in 3s
CI / image (push) Successful in 12s

Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #4.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-08 16:15:05 +00:00
1 parent dd8205602c
commit 145ebf25c1
11 files changed
+1001 -24

No files matched your search

+17 -1
View File
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"sync"
"time"
)
// FileName is the store's file in the data folder.
@@ -19,6 +20,8 @@ type Account struct {
IMVUID int64 `json:"imvuId"`
Username string `json:"username"`
Sealed string `json:"sealed"`
// When IMVU last refused the sign-in with this password (zero: never): it isn't tried again for a while.
RefusedAt time.Time `json:"refusedAt,omitzero"`
}
// Store is the accounts file.
@@ -56,7 +59,7 @@ func (s *Store) Get(id string) (Account, bool) {
return a, ok
}
// Put keeps an account (replacing its password, if it had one).
// Put keeps an account (replacing its password, if it had one; a new password may be tried at once).
func (s *Store) Put(a Account) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -64,6 +67,19 @@ func (s *Store) Put(a Account) error {
return s.save()
}
// Refused records that IMVU refused the account's sign-in (with its current password).
func (s *Store) Refused(id string, at time.Time) error {
s.mu.Lock()
defer s.mu.Unlock()
a, ok := s.byID[id]
if !ok {
return nil
}
a.RefusedAt = at
s.byID[id] = a
return s.save()
}
// Keep forgets every account not in ids (the hub no longer lists them) and returns how many it forgot.
func (s *Store) Keep(ids map[string]bool) (int, error) {
s.mu.Lock()
+46 -2
View File
@@ -70,15 +70,59 @@ type Config struct {
Accounts []Account `json:"accounts"`
}
// Job is a claimed import job. Rating is IMVU's ("general", "adult"), or "" when the hub couldn't see it.
// Job is a claimed job. Rating is IMVU's ("general", "adult"), or "" when IMVU hides the product from the hub.
type Job struct {
ID string `json:"id"`
Kind string `json:"kind"` // "import" or "recheck"
Kind string `json:"kind"` // "import", "recheck", or "list" (a whole shop, signed in)
IMVUProduct int64 `json:"imvuProduct"`
IMVUCreator int64 `json:"imvuCreator"` // a "list" job's shop
LastRevision int `json:"lastRevision"` // the newest IMVU revision imported already, or 0
Rating string `json:"rating"`
}
// Seen is a product as the importer's IMVU account sees it.
type Seen struct {
ID int64 `json:"id"`
Name string `json:"name"`
Rating string `json:"rating"`
CreatorID int64 `json:"creatorId"`
CreatorName string `json:"creatorName"`
Purchasable bool `json:"purchasable"`
}
// Listing reports a "list" job's shop, as the importer's account lists it; the hub keeps and queues its products.
func (c *Client) Listing(ctx context.Context, job string, products []Seen) (listed, queued int, err error) {
if products == nil {
products = []Seen{}
}
var r struct {
Listed int `json:"listed"`
Queued int `json:"queued"`
}
err = c.do(ctx, http.MethodPost, "/api/v1/importer/jobs/"+url.PathEscape(job)+"/listing", map[string]any{"products": products}, &r)
return r.Listed, r.Queued, err
}
// Info reports a job's product as the importer's account sees it (nil: not at all). The hub answers its rating
// (now known, "" if not) and whether the job's grant covers it.
func (c *Client) Info(ctx context.Context, job string, p *Seen) (rating string, covered bool, err error) {
body := map[string]any{"found": false}
if p != nil {
body = map[string]any{"found": true, "name": p.Name, "rating": p.Rating, "creatorId": p.CreatorID, "creatorName": p.CreatorName, "purchasable": p.Purchasable}
}
var r struct {
Rating *string `json:"rating"`
Covered bool `json:"covered"`
}
if err := c.do(ctx, http.MethodPost, "/api/v1/importer/jobs/"+url.PathEscape(job)+"/info", body, &r); err != nil {
return "", false, err
}
if r.Rating != nil {
rating = *r.Rating
}
return rating, r.Covered, nil
}
// Hello sends the importer's version and public key (base64 SPKI) and returns its config.
func (c *Client) Hello(ctx context.Context, version, publicKey string) (*Config, error) {
var cfg Config
+19 -3
View File
@@ -30,6 +30,8 @@ type Importer struct {
UserAgent string
HTTP *http.Client // for uploads to the catalog
Tmp string // a folder for working files
Sessions string // a folder for the IMVU accounts' sessions (their cookies)
APIURL string // IMVU's API (imvu.APIURL, or a test server's)
Logger *log.Logger
ConfigEvery time.Duration // how often the config is fetched (default a minute)
@@ -38,6 +40,7 @@ type Importer struct {
paused bool
concurrency int
signIn signedIn
}
// Run runs until ctx ends. Jobs it's working on then are left claimed; the hub queues them again after 30 minutes.
@@ -195,6 +198,8 @@ func (im *Importer) syncAccounts(ctx context.Context, list []hub.Account) {
} else if n > 0 {
im.Logger.Printf("accounts: forgot %d the hub no longer lists", n)
}
im.forgetSessions(ids)
im.ensureSignedIn(ctx, list)
}
func upperFirst(s string) string {
@@ -211,15 +216,19 @@ func (im *Importer) job(ctx context.Context, j hub.Job) {
if ctx.Err() != nil {
return
}
what := fmt.Sprintf("IMVU product %d", j.IMVUProduct)
if j.Kind == "list" {
what = fmt.Sprintf("IMVU shop %d", j.IMVUCreator)
}
if err != nil {
im.Logger.Printf("job %s (IMVU product %d): failed: %v", j.ID, j.IMVUProduct, err)
im.Logger.Printf("job %s (%s): failed: %v", j.ID, what, err)
out = &hub.Outcome{Status: "failed", Reason: upperFirst(err.Error()) + "."}
}
if out == nil {
return // the catalog's upload registered it: the job is done
}
if out.Status == "unchanged" {
im.Logger.Printf("job %s (IMVU product %d): no revision after %d", j.ID, j.IMVUProduct, out.IMVURevision)
im.Logger.Printf("job %s (%s): no revision after %d", j.ID, what, out.IMVURevision)
}
if err := im.Hub.Report(ctx, j.ID, *out); err != nil && ctx.Err() == nil {
im.Logger.Printf("job %s: reporting: %v", j.ID, err)
@@ -229,8 +238,15 @@ func (im *Importer) job(ctx context.Context, j hub.Job) {
// run imports a job's product: its newest revision after the last one imported. It returns the outcome to report,
// or nil when the upload registered it.
func (im *Importer) run(ctx context.Context, j hub.Job, start time.Time) (*hub.Outcome, error) {
if j.Kind == "list" {
return im.listShop(ctx, j)
}
if j.Rating == "" {
return nil, errors.New("the hub doesn't know this product's rating: IMVU hides it from the signed out (an Access Pass product?), and the importer can't sign in to IMVU yet")
rating, err := im.lookUp(ctx, j)
if err != nil {
return nil, err
}
j.Rating = rating
}
latest, probes, err := im.CDN.Latest(ctx, j.IMVUProduct, j.LastRevision+1)
if err != nil {
+150 -15
View File
@@ -15,6 +15,8 @@ import (
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
@@ -29,20 +31,24 @@ import (
// fakeHub is the hub's importer API, as t5de-hub's docs/products.md has it, and a catalog's upload.
type fakeHub struct {
t *testing.T
mu sync.Mutex
cfg hub.Config
queue []hub.Job
claims int
hello map[string]string
reports map[string]hub.Outcome
done map[string]map[string][]byte // job → the uploaded product's files
account map[string]hub.AccountReport
catalog *httptest.Server
t *testing.T
mu sync.Mutex
cfg hub.Config
queue []hub.Job
claims int
hello map[string]string
reports map[string]hub.Outcome
done map[string]map[string][]byte // job → the uploaded product's files
account map[string]hub.AccountReport
reportsOf map[string][]hub.AccountReport // every report, by account
listings map[string][]hub.Seen // "list" jobs' products
infos map[string]*hub.Seen // what the importer saw of jobs' products
catalog *httptest.Server
}
func newFakeHub(t *testing.T) (*fakeHub, *httptest.Server) {
h := &fakeHub{t: t, reports: map[string]hub.Outcome{}, done: map[string]map[string][]byte{}, account: map[string]hub.AccountReport{}}
h := &fakeHub{t: t, reports: map[string]hub.Outcome{}, done: map[string]map[string][]byte{}, account: map[string]hub.AccountReport{},
reportsOf: map[string][]hub.AccountReport{}, listings: map[string][]hub.Seen{}, infos: map[string]*hub.Seen{}}
h.catalog = httptest.NewServer(http.HandlerFunc(h.upload))
t.Cleanup(h.catalog.Close)
s := httptest.NewServer(http.HandlerFunc(h.serve))
@@ -82,6 +88,26 @@ func (h *fakeHub) serve(w http.ResponseWriter, r *http.Request) {
"token": fmt.Sprintf("import:%s:%v", job, body["imvuRevision"]),
"url": h.catalog.URL + "/api/v1/uploads",
})
case strings.HasSuffix(path, "/listing"):
var l struct{ Products []hub.Seen }
b, _ := json.Marshal(body)
json.Unmarshal(b, &l)
job := strings.TrimSuffix(strings.TrimPrefix(path, "/jobs/"), "/listing")
h.listings[job] = l.Products
json.NewEncoder(w).Encode(map[string]int{"listed": len(l.Products), "queued": len(l.Products)})
case strings.HasSuffix(path, "/info"):
job := strings.TrimSuffix(strings.TrimPrefix(path, "/jobs/"), "/info")
answer := map[string]any{"rating": nil, "covered": false}
if body["found"] == true {
var p hub.Seen
b, _ := json.Marshal(body)
json.Unmarshal(b, &p)
h.infos[job] = &p
answer = map[string]any{"rating": p.Rating, "covered": p.CreatorID == 903}
} else {
h.infos[job] = nil
}
json.NewEncoder(w).Encode(answer)
case strings.HasPrefix(path, "/jobs/"):
var o hub.Outcome
b, _ := json.Marshal(body)
@@ -93,6 +119,14 @@ func (h *fakeHub) serve(w http.ResponseWriter, r *http.Request) {
b, _ := json.Marshal(body)
json.Unmarshal(b, &a)
h.account[strings.TrimPrefix(path, "/accounts/")] = a
h.reportsOf[strings.TrimPrefix(path, "/accounts/")] = append(h.reportsOf[strings.TrimPrefix(path, "/accounts/")], a)
if a.Received { // the hub drops its sealed copy
for i := range h.cfg.Accounts {
if h.cfg.Accounts[i].ID == strings.TrimPrefix(path, "/accounts/") {
h.cfg.Accounts[i].Sealed = nil
}
}
}
w.Write([]byte(`{}`))
default:
http.NotFound(w, r)
@@ -130,7 +164,7 @@ func (h *fakeHub) upload(w http.ResponseWriter, r *http.Request) {
func (h *fakeHub) settled(n int) bool {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.reports)+len(h.done) >= n
return len(h.reports)+len(h.done)+len(h.listings) >= n
}
func sealFor(t *testing.T, k *keys.Key, imvuID int64, password string) *string {
@@ -159,6 +193,10 @@ func newImporterIn(t *testing.T, h *httptest.Server, cdn *imvutest.CDN, dir stri
if err != nil {
t.Fatal(err)
}
sessions := filepath.Join(dir, "sessions")
if err := os.MkdirAll(sessions, 0o700); err != nil {
t.Fatal(err)
}
var logs bytes.Buffer
t.Cleanup(func() {
if t.Failed() {
@@ -173,6 +211,7 @@ func newImporterIn(t *testing.T, h *httptest.Server, cdn *imvutest.CDN, dir stri
Version: "1.2.3",
UserAgent: "test",
Tmp: t.TempDir(),
Sessions: sessions,
Logger: log.New(&logs, "", 0),
ConfigEvery: 50 * time.Millisecond,
ClaimEvery: 10 * time.Millisecond,
@@ -247,7 +286,7 @@ func TestImports(t *testing.T) {
if o := h.reports["b"]; o.Status != "unchanged" || o.IMVURevision != 3 {
t.Errorf("job b: %+v", o)
}
if o := h.reports["c"]; o.Status != "failed" || !strings.Contains(o.Reason, "rating") {
if o := h.reports["c"]; o.Status != "failed" || !strings.Contains(o.Reason, "no IMVU account is signed in") {
t.Errorf("job c: %+v", o)
}
if o := h.reports["d"]; o.Status != "failed" || !strings.Contains(o.Reason, "no revision") {
@@ -266,11 +305,12 @@ func TestAccountsAndPause(t *testing.T) {
if err := im.Accounts.Put(accounts.Account{ID: "gone", IMVUID: 1, Sealed: "x"}); err != nil {
t.Fatal(err)
}
okSealed := sealFor(t, im.Key, 100, "pw")
h.cfg = hub.Config{
Paused: true,
Settings: hub.Settings{Rate: 1, Concurrency: 1},
Accounts: []hub.Account{
{ID: "ok", IMVUID: 100, Username: "Importer1", Sealed: sealFor(t, im.Key, 100, "pw")},
{ID: "ok", IMVUID: 100, Username: "Importer1", Sealed: okSealed},
{ID: "moved", IMVUID: 200, Username: "Importer2", Sealed: sealFor(t, im.Key, 999, "pw")},
{ID: "waiting", IMVUID: 300, Username: "Importer3"},
},
@@ -284,7 +324,7 @@ func TestAccountsAndPause(t *testing.T) {
if !h.account["ok"].Received || h.account["moved"].State != "needs_password" {
t.Errorf("account reports %+v", h.account)
}
if a, ok := im.Accounts.Get("ok"); !ok || a.IMVUID != 100 || a.Sealed != *h.cfg.Accounts[0].Sealed {
if a, ok := im.Accounts.Get("ok"); !ok || a.IMVUID != 100 || a.Sealed != *okSealed {
t.Errorf("kept %+v, %v", a, ok)
}
if _, ok := im.Accounts.Get("gone"); ok {
@@ -317,3 +357,98 @@ func TestHelloRefused(t *testing.T) {
t.Error("ran with a refused key")
}
}
func TestSignedIn(t *testing.T) {
api := imvutest.NewAPI(t)
api.Users = []imvutest.User{
{ID: 777, Username: "ImporterAP", Password: "right", AccessPass: true},
{ID: 778, Username: "NoLuck", Password: "right"},
{ID: 903, Username: "apkeeperAv"},
}
api.Products = []imvutest.Product{
{ID: 9501, Name: "Coat", CreatorID: 903},
{ID: 9502, Name: "Robe", CreatorID: 903, AccessPass: true},
}
cdn := imvutest.New(t)
cdn.Add(9502, 1, imvutest.File{Name: "index.xml", Data: imvutest.Index(5000)})
h, srv := newFakeHub(t)
dir := t.TempDir()
im := newImporterIn(t, srv, cdn, dir)
im.APIURL = api.URL
h.cfg = hub.Config{
Settings: hub.Settings{Rate: 10, Concurrency: 1},
Accounts: []hub.Account{
{ID: "wrong", IMVUID: 778, Username: "NoLuck", Sealed: sealFor(t, im.Key, 778, "not the password")},
{ID: "ap", IMVUID: 777, Username: "ImporterAP", Sealed: sealFor(t, im.Key, 777, "right")},
},
}
h.queue = []hub.Job{
{ID: "list", Kind: "list", IMVUCreator: 903},
{ID: "robe", Kind: "import", IMVUProduct: 9502}, // hidden from the hub: no rating
{ID: "gone", Kind: "import", IMVUProduct: 9599},
}
runUntil(t, im, func() bool { return h.settled(3) })
// The first account is refused; the second signs in, with Access Pass (which IMVU shows it alone).
if r := h.account["wrong"]; r.State != "sign_in_failed" || !strings.Contains(r.Message, "Invalid username or password") {
t.Errorf("refused account: %+v", r)
}
if r := h.account["ap"]; r.State != "ok" || r.AccessPass == nil || !*r.AccessPass {
t.Errorf("signed-in account: %+v", r)
}
// The shop as the account lists it: the Access Pass product too.
if got := h.listings["list"]; len(got) != 2 || got[1] != (hub.Seen{ID: 9502, Name: "Robe", Rating: "adult", CreatorID: 903, CreatorName: "creator903", Purchasable: true}) {
t.Errorf("listing %+v", got)
}
// The hidden product: looked up, reported, imported as adult.
if p := h.infos["robe"]; p == nil || p.Rating != "adult" || p.CreatorID != 903 {
t.Errorf("robe info %+v", p)
}
if robe := h.done["robe"]; robe == nil || !bytes.Contains(robe["index.xml"], []byte("<ProductRating>AP</ProductRating>")) {
t.Errorf("robe: %q (reports %v)", robe, h.reports)
}
if p, ok := h.infos["gone"]; !ok || p != nil {
t.Errorf("gone info %+v, %v", p, ok)
}
if o := h.reports["gone"]; o.Status != "failed" || !strings.Contains(o.Reason, "deleted?") {
t.Errorf("gone: %+v", o)
}
// A restart resumes the saved session: no new sign-in.
signIns := api.SignIns
h.mu.Lock()
h.queue = []hub.Job{{ID: "list2", Kind: "list", IMVUCreator: 903}}
h.mu.Unlock()
again := newImporterIn(t, srv, cdn, dir)
again.Key = im.Key
again.APIURL = api.URL
runUntil(t, again, func() bool { return h.settled(4) })
if api.SignIns != signIns {
t.Errorf("signed in again: %d sign-ins, was %d", api.SignIns, signIns)
}
// The refused account isn't tried again within the hour (same password), even after a restart.
refusals := 0
for _, r := range h.reportsOf["wrong"] {
if r.State == "sign_in_failed" {
refusals++
}
}
if refusals != 1 {
t.Errorf("the refused account was refused %d times", refusals)
}
// IMVU ends the session: the importer signs in again.
api.EndSessions()
h.mu.Lock()
h.queue = []hub.Job{{ID: "list3", Kind: "list", IMVUCreator: 903}, {ID: "list4", Kind: "list", IMVUCreator: 903}}
h.mu.Unlock()
runUntil(t, again, func() bool {
h.mu.Lock()
defer h.mu.Unlock()
return (h.listings["list3"] != nil || h.reports["list3"].Status != "") && (h.listings["list4"] != nil || h.reports["list4"].Status != "")
})
if api.SignIns != signIns+1 || len(h.listings["list3"]) != 2 || len(h.listings["list4"]) != 2 {
t.Errorf("after the session ended: %d sign-ins (want %d); listings %d and %d, reports %v", api.SignIns, signIns+1, len(h.listings["list3"]), len(h.listings["list4"]), h.reports)
}
}
+236
View File
@@ -0,0 +1,236 @@
package importer
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"git.t5de.dev/t5de/t5de-importer/internal/hub"
"git.t5de.dev/t5de/t5de-importer/internal/imvu"
)
// SignInRetry is how long an account IMVU refused is left before trying it again (unless its password changes):
// IMVU limits sign-ins.
const SignInRetry = time.Hour
// signedIn is the IMVU account the importer uses: the first of the console's accounts, in order, that signs in.
type signedIn struct {
mu sync.Mutex
session *imvu.Session
account string // the hub's ID of its account
list []hub.Account // the console's accounts, as last fetched
}
// errNoSession is no account signed in.
var errNoSession = errors.New("no IMVU account is signed in")
// withSession runs f with the signed-in session, signing in first if none is; if IMVU ended the session, it signs
// in again and runs f once more.
func (im *Importer) withSession(ctx context.Context, f func(*imvu.Session) error) error {
for attempt := 0; attempt < 2; attempt++ {
s := im.current()
if s == nil {
im.ensureSignedIn(ctx, nil)
if s = im.current(); s == nil {
return errNoSession
}
}
err := f(s)
if !errors.Is(err, imvu.ErrSignedOut) {
return err
}
im.signedOut(s)
}
return imvu.ErrSignedOut
}
// current is the signed-in session, or nil.
func (im *Importer) current() *imvu.Session {
im.signIn.mu.Lock()
defer im.signIn.mu.Unlock()
return im.signIn.session
}
// signedOut drops a session IMVU no longer takes; the next config poll signs in again.
func (im *Importer) signedOut(s *imvu.Session) {
im.signIn.mu.Lock()
defer im.signIn.mu.Unlock()
if im.signIn.session == s {
im.signIn.session = nil
im.Logger.Printf("IMVU: the session ended; signing in again")
}
}
// ensureSignedIn signs in with the first account (in the console's order) that IMVU takes, unless one is signed in
// already and still listed. Each sign-in is reported: state ok and whether the account has Access Pass, or the
// refusal. A nil list means the last one.
func (im *Importer) ensureSignedIn(ctx context.Context, list []hub.Account) {
im.signIn.mu.Lock()
defer im.signIn.mu.Unlock()
if list == nil {
list = im.signIn.list
} else {
im.signIn.list = list
}
listed := map[string]bool{}
for _, a := range list {
listed[a.ID] = true
}
if im.signIn.session != nil {
if listed[im.signIn.account] {
return
}
im.Logger.Printf("IMVU: account %s was removed on the console; signing out", im.signIn.account)
im.signIn.session.Forget()
im.signIn.session = nil
}
for _, a := range list {
kept, ok := im.Accounts.Get(a.ID)
if !ok {
continue // no password yet (or it needs entering again)
}
if time.Since(kept.RefusedAt) < SignInRetry {
continue // refused with this password lately (a new one clears it)
}
s := &imvu.Session{URL: im.APIURL, UserAgent: imvu.BrowserUserAgent, Limiter: im.CDN.Limiter, File: filepath.Join(im.Sessions, a.ID+".json")}
resumed, err := s.Resume(ctx)
if err != nil {
im.Logger.Printf("IMVU: resuming %s's session: %v", a.Username, err)
return // IMVU unreachable: next time
}
if !resumed {
password, err := im.Key.Open(kept.Sealed, a.IMVUID)
if err == nil {
err = s.SignIn(ctx, a.Username, password)
}
var refused *imvu.ErrSignIn
if errors.As(err, &refused) {
im.Logger.Printf("IMVU: %s: %v", a.Username, err)
im.refused(a.ID)
s.Forget()
im.reportAccount(ctx, a.ID, hub.AccountReport{State: "sign_in_failed", Message: upperFirst(refused.Message)})
continue
}
if err != nil {
im.Logger.Printf("IMVU: signing in as %s: %v", a.Username, err)
return
}
}
if s.UserID != a.IMVUID {
im.Logger.Printf("IMVU: %s signed in as IMVU account %d, not %d", a.Username, s.UserID, a.IMVUID)
im.refused(a.ID)
s.Forget()
im.reportAccount(ctx, a.ID, hub.AccountReport{State: "sign_in_failed", Message: fmt.Sprintf("Signed in as another IMVU account (%d).", s.UserID)})
continue
}
im.signIn.session, im.signIn.account = s, a.ID
ap := s.AccessPass
how := "signed in"
if resumed {
how = "resumed the session"
}
im.Logger.Printf("IMVU: %s as %s (Access Pass: %v)", how, a.Username, ap)
im.reportAccount(ctx, a.ID, hub.AccountReport{State: "ok", AccessPass: &ap})
return
}
}
func (im *Importer) refused(id string) {
if err := im.Accounts.Refused(id, time.Now()); err != nil {
im.Logger.Printf("account %s: %v", id, err)
}
}
func (im *Importer) reportAccount(ctx context.Context, id string, r hub.AccountReport) {
if err := im.Hub.ReportAccount(ctx, id, r); err != nil {
im.Logger.Printf("account %s: reporting: %v", id, err)
}
}
// forgetSessions removes saved sessions of accounts the hub no longer lists.
func (im *Importer) forgetSessions(listed map[string]bool) {
entries, err := os.ReadDir(im.Sessions)
if err != nil {
return
}
for _, e := range entries {
id, ok := cutSuffix(e.Name(), ".json")
if ok && !listed[id] {
os.Remove(filepath.Join(im.Sessions, e.Name()))
}
}
}
func cutSuffix(s, suffix string) (string, bool) {
if len(s) < len(suffix) || s[len(s)-len(suffix):] != suffix {
return s, false
}
return s[:len(s)-len(suffix)], true
}
// listShop does a "list" job: the shop as the signed-in account lists it, reported to the hub, which queues its
// products.
func (im *Importer) listShop(ctx context.Context, j hub.Job) (*hub.Outcome, error) {
var products []imvu.Seen
err := im.withSession(ctx, func(s *imvu.Session) (err error) {
products, err = s.Shop(ctx, j.IMVUCreator)
return err
})
if errors.Is(err, errNoSession) {
return nil, errors.New("no IMVU account is signed in to list the shop with")
}
if err != nil {
return nil, err
}
seen := make([]hub.Seen, len(products))
for i, p := range products {
seen[i] = hub.Seen(p)
}
listed, queued, err := im.Hub.Listing(ctx, j.ID, seen)
if err != nil {
return nil, err
}
im.Logger.Printf("job %s: IMVU shop %d lists %d products signed in; %d queued", j.ID, j.IMVUCreator, listed, queued)
return nil, nil
}
// lookUp asks the signed-in account about a product IMVU hides from the hub, tells the hub, and returns its rating.
func (im *Importer) lookUp(ctx context.Context, j hub.Job) (string, error) {
var p *imvu.Seen
accessPass := false
err := im.withSession(ctx, func(s *imvu.Session) (err error) {
p, err = s.Product(ctx, j.IMVUProduct)
accessPass = s.AccessPass
return err
})
if errors.Is(err, errNoSession) {
return "", errors.New("IMVU hides this product from the hub (an Access Pass product?), and no IMVU account is signed in to look it up")
}
if err != nil {
return "", err
}
var seen *hub.Seen
if p != nil {
h := hub.Seen(*p)
seen = &h
}
rating, covered, err := im.Hub.Info(ctx, j.ID, seen)
if err != nil {
return "", err
}
switch {
case rating == "" && !accessPass:
return "", errors.New("IMVU doesn't show this product to the importer's account, which has no Access Pass")
case rating == "":
return "", errors.New("IMVU doesn't show this product to the importer's account either (deleted?)")
case !covered && p != nil:
return "", fmt.Errorf("the grant doesn't cover this product: IMVU says it's another creator's (%d)", p.CreatorID)
case !covered:
return "", errors.New("the grant doesn't cover this product")
}
return rating, nil
}
+362
View File
@@ -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}
}
+150
View File
@@ -0,0 +1,150 @@
package imvutest
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
)
// User is a fake IMVU account.
type User struct {
ID int64
Username string
Password string
AccessPass bool
}
// Product is a fake IMVU product. Access Pass ones are hidden from the signed out and from accounts without it.
type Product struct {
ID int64
Name string
CreatorID int64
AccessPass bool
}
// API is a fake of IMVU's REST API: signing in (a session cookie), the signed-in account, users, products and shop
// listings, each as the viewer may see them.
type API struct {
*httptest.Server
mu sync.Mutex
Users []User
Products []Product
SignIns int // sign-ins tried
sessions map[string]int64 // session cookie → account
}
// NewAPI starts a fake API.
func NewAPI(t testing.TB) *API {
a := &API{sessions: map[string]int64{}}
a.Server = httptest.NewServer(http.HandlerFunc(a.serve))
t.Cleanup(a.Close)
return a
}
// EndSessions ends every session, as IMVU does after a while.
func (a *API) EndSessions() {
a.mu.Lock()
defer a.mu.Unlock()
a.sessions = map[string]int64{}
}
func (a *API) user(f func(User) bool) *User {
for i := range a.Users {
if f(a.Users[i]) {
return &a.Users[i]
}
}
return nil
}
func (a *API) serve(w http.ResponseWriter, r *http.Request) {
a.mu.Lock()
defer a.mu.Unlock()
var viewer *User
if c, err := r.Cookie("osCsid"); err == nil {
if id, ok := a.sessions[c.Value]; ok {
viewer = a.user(func(u User) bool { return u.ID == id })
}
}
self := a.URL + r.URL.Path
one := func(data map[string]any) {
json.NewEncoder(w).Encode(map[string]any{"status": "success", "id": self, "denormalized": map[string]any{self: map[string]any{"data": data}}})
}
fail := func(status int, code, message string) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]any{"status": "failure", "error": code, "message": message})
}
visible := func(p Product) bool { return !p.AccessPass || (viewer != nil && viewer.AccessPass) }
productData := func(p Product) map[string]any {
rating := "GA"
if p.AccessPass {
rating = "AP"
}
return map[string]any{"product_id": p.ID, "product_name": p.Name, "creator_cid": p.CreatorID, "creator_name": "creator" + strconv.FormatInt(p.CreatorID, 10), "rating": rating, "is_purchasable": true}
}
switch {
case r.URL.Path == "/login" && r.Method == http.MethodPost:
a.SignIns++
var body struct{ Username, Password string }
json.NewDecoder(r.Body).Decode(&body)
u := a.user(func(u User) bool { return strings.EqualFold(u.Username, body.Username) && u.Password == body.Password })
if u == nil {
fail(http.StatusUnauthorized, "LOGIN-002", "Invalid username or password")
return
}
b := make([]byte, 16)
rand.Read(b)
token := hex.EncodeToString(b)
a.sessions[token] = u.ID
http.SetCookie(w, &http.Cookie{Name: "osCsid", Value: token, Path: "/"})
w.WriteHeader(http.StatusCreated)
one(map[string]any{"user": map[string]any{"id": a.URL + "/user/user-" + strconv.FormatInt(u.ID, 10)}})
case r.URL.Path == "/login/me":
if viewer == nil {
fail(http.StatusUnauthorized, "AUTHENTICATION-005", "Not signed in")
return
}
one(map[string]any{"user": map[string]any{"id": a.URL + "/user/user-" + strconv.FormatInt(viewer.ID, 10)}, "session_id": "x"})
case strings.HasPrefix(r.URL.Path, "/user/user-"):
id, _ := strconv.ParseInt(strings.TrimPrefix(r.URL.Path, "/user/user-"), 10, 64)
u := a.user(func(u User) bool { return u.ID == id })
if u == nil {
fail(http.StatusNotFound, "NOT-FOUND", "No such user")
return
}
// IMVU shows Access Pass to the account itself only.
one(map[string]any{"legacy_cid": u.ID, "username": u.Username, "is_ap": viewer != nil && viewer.ID == u.ID && u.AccessPass})
case strings.HasPrefix(r.URL.Path, "/product/product-"):
id, _ := strconv.ParseInt(strings.TrimPrefix(r.URL.Path, "/product/product-"), 10, 64)
for _, p := range a.Products {
if p.ID == id && visible(p) {
one(productData(p))
return
}
}
fail(http.StatusUnauthorized, "AUTHENTICATION-005", "Not allowed") // as IMVU answers hidden and missing alike
case r.URL.Path == "/product":
creator := a.user(func(u User) bool { return strings.EqualFold(u.Username, r.URL.Query().Get("creator")) })
self = a.URL + r.URL.RequestURI()
den := map[string]any{}
items := []string{}
for _, p := range a.Products {
if creator != nil && p.CreatorID == creator.ID && visible(p) {
ref := a.URL + "/product/product-" + strconv.FormatInt(p.ID, 10)
items = append(items, ref)
den[ref] = map[string]any{"data": productData(p)}
}
}
den[self] = map[string]any{"data": map[string]any{"items": items, "total_count": len(items)}, "relations": []any{}}
json.NewEncoder(w).Encode(map[string]any{"status": "success", "id": self, "denormalized": den})
default:
fail(http.StatusNotFound, "NOT-FOUND", "No such thing")
}
}