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,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