Files
t5de-importer/internal/importer/importer.go
T
dhkatz 145ebf25c1
CI / build (push) Successful in 16s
Release / release (push) Successful in 3s
CI / image (push) Successful in 12s
feat: sign in to IMVU for Access Pass products (#4)
Co-authored-by: dhkatz <[email protected]>
2026-11-08 16:15:05 +00:00

300 lines
9.0 KiB
Go

// Package importer runs a catalog's imports: it says hello to the hub, follows the config the catalog's team sets on
// the console (paused, rate, jobs at a time, IMVU accounts), claims jobs, imports each product's newest IMVU revision
// from IMVU's CDN, and uploads it to the catalog (t5de-hub's docs/imports.md).
package importer
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"time"
"git.t5de.dev/t5de/t5de-api/cfl"
"git.t5de.dev/t5de/t5de-importer/internal/accounts"
"git.t5de.dev/t5de/t5de-importer/internal/catalog"
"git.t5de.dev/t5de/t5de-importer/internal/convert"
"git.t5de.dev/t5de/t5de-importer/internal/hub"
"git.t5de.dev/t5de/t5de-importer/internal/imvu"
"git.t5de.dev/t5de/t5de-importer/internal/keys"
)
// Importer is one catalog's importer.
type Importer struct {
Hub *hub.Client
CDN *imvu.CDN
Key *keys.Key
Accounts *accounts.Store
Version string
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)
ClaimEvery time.Duration // how long to wait after a claim found nothing (default 15 s)
RetryEvery time.Duration // how long to wait after the hub failed (default 30 s)
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.
func (im *Importer) Run(ctx context.Context) error {
if im.ConfigEvery == 0 {
im.ConfigEvery = time.Minute
}
if im.ClaimEvery == 0 {
im.ClaimEvery = 15 * time.Second
}
if im.RetryEvery == 0 {
im.RetryEvery = 30 * time.Second
}
cfg, err := im.hello(ctx)
if err != nil {
return err
}
im.apply(ctx, cfg)
done := make(chan struct{})
running := 0
configAt := time.NewTicker(im.ConfigEvery)
defer configAt.Stop()
claimAt := time.NewTimer(0)
defer claimAt.Stop()
for {
select {
case <-ctx.Done():
for ; running > 0; running-- {
<-done
}
return nil
case <-configAt.C:
cfg, err := im.Hub.Config(ctx)
if err != nil {
im.Logger.Printf("config: %v", err)
continue
}
im.apply(ctx, cfg)
resetTimer(claimAt, 0)
case <-done:
running--
resetTimer(claimAt, 0)
case <-claimAt.C:
if im.paused || running >= im.concurrency {
continue
}
jobs, err := im.Hub.Claim(ctx, im.concurrency-running)
if err != nil {
if ctx.Err() == nil {
im.Logger.Printf("claiming jobs: %v", err)
}
resetTimer(claimAt, im.RetryEvery)
continue
}
for _, j := range jobs {
running++
go func() {
im.job(ctx, j)
done <- struct{}{}
}()
}
if len(jobs) == 0 {
resetTimer(claimAt, im.ClaimEvery)
} else {
resetTimer(claimAt, 0)
}
}
}
}
func resetTimer(t *time.Timer, d time.Duration) {
t.Stop()
select {
case <-t.C:
default:
}
t.Reset(d)
}
// hello says hello until the hub answers: a wrong key or a catalog without imports keeps being retried, so the
// importer starts working once the team fixes it on the console.
func (im *Importer) hello(ctx context.Context) (*hub.Config, error) {
for {
cfg, err := im.Hub.Hello(ctx, im.Version, im.Key.PublicKey)
if err == nil {
im.Logger.Printf("hello: the hub has this importer's key (fingerprint %s)", im.Key.Fingerprint[:16])
return cfg, nil
}
var refused *hub.Error
if errors.As(err, &refused) && refused.Status == http.StatusUnauthorized {
im.Logger.Printf("hello: the hub refused (%v): check CATALOG_ID and IMPORTER_KEY, and that imports are on for the catalog", err)
} else {
im.Logger.Printf("hello: %v", err)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(im.RetryEvery):
}
}
}
// apply takes a config: paused or not, the settings, and the accounts.
func (im *Importer) apply(ctx context.Context, cfg *hub.Config) {
if cfg.Paused != im.paused {
if cfg.Paused {
im.Logger.Printf("paused on the console")
} else {
im.Logger.Printf("running")
}
}
im.paused = cfg.Paused
im.concurrency = min(max(cfg.Settings.Concurrency, 1), 8)
rate := cfg.Settings.Rate
if rate <= 0 {
rate = 1
}
im.CDN.Limiter.SetRate(min(rate, 10))
if cfg.Fingerprint != "" && cfg.Fingerprint != im.Key.Fingerprint {
// Another importer said hello for this catalog since: passwords are sealed for its key, not this one's.
im.Logger.Printf("config: the hub has another importer's key (fingerprint %.16s): is a second importer running for this catalog?", cfg.Fingerprint)
}
im.syncAccounts(ctx, cfg.Accounts)
}
// syncAccounts keeps the accounts the hub lists: new passwords (sealed for this importer's key) are checked and
// kept, then reported received, so the hub drops its copy; accounts no longer listed are forgotten.
func (im *Importer) syncAccounts(ctx context.Context, list []hub.Account) {
ids := map[string]bool{}
for _, a := range list {
ids[a.ID] = true
if a.Sealed == nil {
continue
}
if _, err := im.Key.Open(*a.Sealed, a.IMVUID); err != nil {
im.Logger.Printf("account %s (%s): %v", a.ID, a.Username, err)
if err := im.Hub.ReportAccount(ctx, a.ID, hub.AccountReport{State: "needs_password", Message: upperFirst(err.Error()) + "."}); err != nil {
im.Logger.Printf("account %s: reporting: %v", a.ID, err)
}
continue
}
if err := im.Accounts.Put(accounts.Account{ID: a.ID, IMVUID: a.IMVUID, Username: a.Username, Sealed: *a.Sealed}); err != nil {
im.Logger.Printf("account %s: keeping its password: %v", a.ID, err)
continue
}
if err := im.Hub.ReportAccount(ctx, a.ID, hub.AccountReport{Received: true}); err != nil {
im.Logger.Printf("account %s: reporting it received: %v", a.ID, err)
continue
}
im.Logger.Printf("account %s (%s): password received", a.ID, a.Username)
}
if n, err := im.Accounts.Keep(ids); err != nil {
im.Logger.Printf("accounts: %v", err)
} 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 {
if s == "" || s[0] < 'a' || s[0] > 'z' {
return s
}
return string(s[0]-'a'+'A') + s[1:]
}
// job does one job and reports it; nothing is reported if the importer is stopping.
func (im *Importer) job(ctx context.Context, j hub.Job) {
start := time.Now()
out, err := im.run(ctx, j, start)
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 (%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 (%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)
}
}
// 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 == "" {
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 {
return nil, err
}
if latest == 0 {
if j.LastRevision > 0 {
return &hub.Outcome{Status: "unchanged", IMVURevision: j.LastRevision}, nil
}
return nil, fmt.Errorf("IMVU's CDN has no revision of it (%d probes)", probes)
}
data, err := im.CDN.CFL(ctx, j.IMVUProduct, latest)
if err != nil {
return nil, err
}
entries, err := cfl.Read(data)
if err != nil {
return nil, fmt.Errorf("revision %d: %w", latest, err)
}
files, err := convert.Files(ctx, entries, j.Rating, func(ctx context.Context, url string) ([]byte, error) {
return im.CDN.File(ctx, j.IMVUProduct, latest, url)
})
if err != nil {
return nil, fmt.Errorf("revision %d: %w", latest, err)
}
chkn, err := convert.Chkn(files)
if err != nil {
return nil, err
}
rating := j.Rating
for _, f := range files {
if f.Name == "index.xml" {
rating = convert.Rating(f.Data)
}
}
if err := convert.Check(chkn, j.IMVUProduct, rating, im.Tmp); err != nil {
return nil, fmt.Errorf("revision %d breaks the product rules: %w", latest, err)
}
token, url, err := im.Hub.Token(ctx, j.ID, latest)
if err != nil {
return nil, err
}
reg, err := catalog.Upload(ctx, im.HTTP, im.UserAgent, url, token, chkn)
if err != nil {
return nil, err
}
im.Logger.Printf("job %s: IMVU product %d revision %d imported as %s revision %d (%d files, %d probes, %s)",
j.ID, j.IMVUProduct, latest, reg.Product, reg.Revision, len(files), probes, time.Since(start).Round(time.Millisecond))
return nil, nil
}