feat: import IMVU products into a catalog
The importer from t5de-hub's docs/imports.md: says hello to the hub with its key pair, follows the console's config (paused, rate, jobs at a time, IMVU accounts, whose sealed passwords it keeps), claims jobs, finds each product's newest revision on IMVU's CDN, converts it (originals for placeholders, no _contents.json, ProductRating from IMVU's rating), checks it by t5de-api's pack rules and uploads it to the catalog with an import token. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
2b0d27831e
commit
e8578e4a71
26 files changed
+2345
-1
No files matched your search
@@ -0,0 +1,283 @@
|
||||
// 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
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
im.Logger.Printf("job %s (IMVU product %d): failed: %v", j.ID, j.IMVUProduct, 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)
|
||||
}
|
||||
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.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")
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package importer
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/accounts"
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/hub"
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/imvu"
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/imvutest"
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/keys"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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.catalog = httptest.NewServer(http.HandlerFunc(h.upload))
|
||||
t.Cleanup(h.catalog.Close)
|
||||
s := httptest.NewServer(http.HandlerFunc(h.serve))
|
||||
t.Cleanup(s.Close)
|
||||
return h, s
|
||||
}
|
||||
|
||||
func (h *fakeHub) serve(w http.ResponseWriter, r *http.Request) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if r.Header.Get("Authorization") != "Importer cat1:secret" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "forbidden", "message": "Not an importer."})
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/importer")
|
||||
switch {
|
||||
case path == "/hello":
|
||||
h.hello = map[string]string{"version": body["version"].(string), "publicKey": body["publicKey"].(string)}
|
||||
json.NewEncoder(w).Encode(h.cfg)
|
||||
case path == "/config":
|
||||
json.NewEncoder(w).Encode(h.cfg)
|
||||
case path == "/jobs/claim":
|
||||
h.claims++
|
||||
n := min(int(body["limit"].(float64)), len(h.queue))
|
||||
if h.cfg.Paused {
|
||||
n = 0
|
||||
}
|
||||
jobs := h.queue[:n]
|
||||
h.queue = h.queue[n:]
|
||||
json.NewEncoder(w).Encode(map[string]any{"jobs": jobs})
|
||||
case strings.HasSuffix(path, "/token"):
|
||||
job := strings.TrimSuffix(strings.TrimPrefix(path, "/jobs/"), "/token")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"token": fmt.Sprintf("import:%s:%v", job, body["imvuRevision"]),
|
||||
"url": h.catalog.URL + "/api/v1/uploads",
|
||||
})
|
||||
case strings.HasPrefix(path, "/jobs/"):
|
||||
var o hub.Outcome
|
||||
b, _ := json.Marshal(body)
|
||||
json.Unmarshal(b, &o)
|
||||
h.reports[strings.TrimPrefix(path, "/jobs/")] = o
|
||||
w.Write([]byte(`{}`))
|
||||
case strings.HasPrefix(path, "/accounts/"):
|
||||
var a hub.AccountReport
|
||||
b, _ := json.Marshal(body)
|
||||
json.Unmarshal(b, &a)
|
||||
h.account[strings.TrimPrefix(path, "/accounts/")] = a
|
||||
w.Write([]byte(`{}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// upload is the catalog's upload: the importer's .chkn, registered at once (which marks its job done).
|
||||
func (h *fakeHub) upload(w http.ResponseWriter, r *http.Request) {
|
||||
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer import:")
|
||||
f, _, err := r.FormFile("file")
|
||||
if !ok || err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
data, _ := io.ReadAll(f)
|
||||
z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
files := map[string][]byte{}
|
||||
for _, zf := range z.File {
|
||||
rc, _ := zf.Open()
|
||||
files[zf.Name], _ = io.ReadAll(rc)
|
||||
}
|
||||
job, rev, _ := strings.Cut(tok, ":")
|
||||
files["(revision)"] = []byte(rev)
|
||||
h.mu.Lock()
|
||||
h.done[job] = files
|
||||
h.mu.Unlock()
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]any{"product": "p-" + job, "revision": 1})
|
||||
}
|
||||
|
||||
func (h *fakeHub) settled(n int) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return len(h.reports)+len(h.done) >= n
|
||||
}
|
||||
|
||||
func sealFor(t *testing.T, k *keys.Key, imvuID int64, password string) *string {
|
||||
t.Helper()
|
||||
der, _ := base64.StdEncoding.DecodeString(k.PublicKey)
|
||||
pub, _ := x509.ParsePKIXPublicKey(der)
|
||||
plain, _ := json.Marshal(map[string]any{"imvuId": imvuID, "password": password})
|
||||
ct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub.(*rsa.PublicKey), plain, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := base64.StdEncoding.EncodeToString(ct)
|
||||
return &s
|
||||
}
|
||||
|
||||
func newImporter(t *testing.T, h *httptest.Server, cdn *imvutest.CDN) *Importer {
|
||||
return newImporterIn(t, h, cdn, t.TempDir())
|
||||
}
|
||||
|
||||
func newImporterIn(t *testing.T, h *httptest.Server, cdn *imvutest.CDN, dir string) *Importer {
|
||||
k, _, err := keys.Load(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := accounts.Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
t.Cleanup(func() {
|
||||
if t.Failed() {
|
||||
t.Log(logs.String())
|
||||
}
|
||||
})
|
||||
return &Importer{
|
||||
Hub: hub.New(h.URL, "cat1", "secret", "test", nil),
|
||||
CDN: &imvu.CDN{URL: cdn.URL, UserAgent: "test", Limiter: imvu.NewLimiter(10)},
|
||||
Key: k,
|
||||
Accounts: store,
|
||||
Version: "1.2.3",
|
||||
UserAgent: "test",
|
||||
Tmp: t.TempDir(),
|
||||
Logger: log.New(&logs, "", 0),
|
||||
ConfigEvery: 50 * time.Millisecond,
|
||||
ClaimEvery: 10 * time.Millisecond,
|
||||
RetryEvery: 10 * time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
func runUntil(t *testing.T, im *Importer, until func() bool) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
stopped := make(chan error)
|
||||
go func() { stopped <- im.Run(ctx) }()
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for !until() {
|
||||
if time.Now().After(deadline) {
|
||||
cancel()
|
||||
<-stopped
|
||||
t.Fatal("timed out")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
if err := <-stopped; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImports(t *testing.T) {
|
||||
cdn := imvutest.New(t)
|
||||
index := imvutest.Index(5000)
|
||||
cdn.Add(9001, 1, imvutest.File{Name: "index.xml", Data: index})
|
||||
cdn.Add(9001, 2,
|
||||
imvutest.File{Name: "index.xml", Data: index},
|
||||
imvutest.File{Name: "dress.png", Data: []byte("16x16"), URL: "aaa.png", Original: []byte("the full-size texture")},
|
||||
imvutest.File{Name: "Skin%20%5B03%5D.xrf", URL: "bbb.xrf", Original: []byte("a material kept on the CDN only")},
|
||||
)
|
||||
for rev := 1; rev <= 3; rev++ {
|
||||
cdn.Add(9002, rev, imvutest.File{Name: "index.xml", Data: index})
|
||||
}
|
||||
cdn.Add(9005, 1, imvutest.File{Name: "index.xml", Data: index})
|
||||
|
||||
h, srv := newFakeHub(t)
|
||||
h.cfg.Settings = hub.Settings{Rate: 10, Concurrency: 2}
|
||||
h.queue = []hub.Job{
|
||||
{ID: "a", Kind: "import", IMVUProduct: 9001, Rating: "general"},
|
||||
{ID: "b", Kind: "recheck", IMVUProduct: 9002, LastRevision: 3, Rating: "general"},
|
||||
{ID: "c", Kind: "import", IMVUProduct: 9003}, // the hub doesn't know its rating
|
||||
{ID: "d", Kind: "import", IMVUProduct: 9004, Rating: "general"},
|
||||
{ID: "e", Kind: "import", IMVUProduct: 9005, Rating: "adult"},
|
||||
}
|
||||
im := newImporter(t, srv, cdn)
|
||||
runUntil(t, im, func() bool { return h.settled(5) })
|
||||
|
||||
if h.hello["version"] != "1.2.3" || h.hello["publicKey"] != im.Key.PublicKey {
|
||||
t.Errorf("hello %v", h.hello)
|
||||
}
|
||||
// The newest revision, converted: originals in, _contents.json out, ProductRating added.
|
||||
a := h.done["a"]
|
||||
if a == nil {
|
||||
t.Fatalf("job a wasn't uploaded; reports %v", h.reports)
|
||||
}
|
||||
if string(a["(revision)"]) != "2" || string(a["dress.png"]) != "the full-size texture" ||
|
||||
string(a["Skin%20%5B03%5D.xrf"]) != "a material kept on the CDN only" || a["_contents.json"] != nil {
|
||||
t.Errorf("job a uploaded %q", a)
|
||||
}
|
||||
if !bytes.Contains(a["index.xml"], []byte("<ProductRating>GA</ProductRating>")) || !bytes.Contains(a["index.xml"], []byte("product://5000/index.xml")) {
|
||||
t.Errorf("job a's index.xml: %s", a["index.xml"])
|
||||
}
|
||||
if e := h.done["e"]; e == nil || !bytes.Contains(e["index.xml"], []byte("<ProductRating>AP</ProductRating>")) {
|
||||
t.Errorf("job e (adult): %q", e)
|
||||
}
|
||||
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") {
|
||||
t.Errorf("job c: %+v", o)
|
||||
}
|
||||
if o := h.reports["d"]; o.Status != "failed" || !strings.Contains(o.Reason, "no revision") {
|
||||
t.Errorf("job d: %+v", o)
|
||||
}
|
||||
if len(h.reports) != 3 || len(h.done) != 2 {
|
||||
t.Errorf("reports %v, uploads %d", h.reports, len(h.done))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountsAndPause(t *testing.T) {
|
||||
cdn := imvutest.New(t)
|
||||
h, srv := newFakeHub(t)
|
||||
dir := t.TempDir()
|
||||
im := newImporterIn(t, srv, cdn, dir)
|
||||
if err := im.Accounts.Put(accounts.Account{ID: "gone", IMVUID: 1, Sealed: "x"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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: "moved", IMVUID: 200, Username: "Importer2", Sealed: sealFor(t, im.Key, 999, "pw")},
|
||||
{ID: "waiting", IMVUID: 300, Username: "Importer3"},
|
||||
},
|
||||
}
|
||||
h.queue = []hub.Job{{ID: "x", Kind: "import", IMVUProduct: 1, Rating: "general"}}
|
||||
runUntil(t, im, func() bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return len(h.account) == 2
|
||||
})
|
||||
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 {
|
||||
t.Errorf("kept %+v, %v", a, ok)
|
||||
}
|
||||
if _, ok := im.Accounts.Get("gone"); ok {
|
||||
t.Error("an account the hub no longer lists is still kept")
|
||||
}
|
||||
if _, ok := im.Accounts.Get("moved"); ok {
|
||||
t.Error("a password for another account was kept")
|
||||
}
|
||||
// Reopened from disk: the same.
|
||||
again, err := accounts.Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := again.Get("ok"); !ok {
|
||||
t.Error("not saved")
|
||||
}
|
||||
if len(h.queue) != 1 || len(h.reports) != 0 {
|
||||
t.Errorf("paused, yet jobs were taken: queue %v", h.queue)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelloRefused(t *testing.T) {
|
||||
cdn := imvutest.New(t)
|
||||
_, srv := newFakeHub(t)
|
||||
im := newImporter(t, srv, cdn)
|
||||
im.Hub = hub.New(srv.URL, "cat1", "wrong", "test", nil)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := im.Run(ctx); err == nil {
|
||||
t.Error("ran with a refused key")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user