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,101 @@
|
||||
// Package accounts keeps the IMVU accounts' passwords the importer was given: each still sealed for its key, so
|
||||
// the file alone (without the key) reveals nothing. The hub drops its copy once the importer says it has one.
|
||||
package accounts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// FileName is the store's file in the data folder.
|
||||
const FileName = "accounts.json"
|
||||
|
||||
// Account is a kept account.
|
||||
type Account struct {
|
||||
ID string `json:"id"` // the hub's
|
||||
IMVUID int64 `json:"imvuId"`
|
||||
Username string `json:"username"`
|
||||
Sealed string `json:"sealed"`
|
||||
}
|
||||
|
||||
// Store is the accounts file.
|
||||
type Store struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
byID map[string]Account
|
||||
}
|
||||
|
||||
// Open reads the store in dir (empty if there's none yet).
|
||||
func Open(dir string) (*Store, error) {
|
||||
s := &Store{path: filepath.Join(dir, FileName), byID: map[string]Account{}}
|
||||
data, err := os.ReadFile(s.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var list []Account
|
||||
if err := json.Unmarshal(data, &list); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range list {
|
||||
s.byID[a.ID] = a
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Get returns the account with the hub's ID id.
|
||||
func (s *Store) Get(id string) (Account, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
a, ok := s.byID[id]
|
||||
return a, ok
|
||||
}
|
||||
|
||||
// Put keeps an account (replacing its password, if it had one).
|
||||
func (s *Store) Put(a Account) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.byID[a.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()
|
||||
defer s.mu.Unlock()
|
||||
n := 0
|
||||
for id := range s.byID {
|
||||
if !ids[id] {
|
||||
delete(s.byID, id)
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return n, s.save()
|
||||
}
|
||||
|
||||
func (s *Store) save() error {
|
||||
list := make([]Account, 0, len(s.byID))
|
||||
for _, a := range s.byID {
|
||||
list = append(list, a)
|
||||
}
|
||||
data, err := json.MarshalIndent(list, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := s.path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, s.path)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Package buildinfo holds what release builds set with -ldflags "-X ...".
|
||||
package buildinfo
|
||||
|
||||
// Version is the release's version, "X.Y.Z", or what CI sets for other builds.
|
||||
var Version = "dev"
|
||||
@@ -0,0 +1,85 @@
|
||||
// Package catalog uploads imported products to the catalog (t5de-hub's docs/products.md, `POST /api/v1/uploads`
|
||||
// with a t5de-import token). The catalog checks the files, stores them and registers the revision with the hub,
|
||||
// which marks the job done.
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Error is the catalog's refusal: its status and `{error, message}`.
|
||||
type Error struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Message != "" {
|
||||
return fmt.Sprintf("the catalog refused the upload (%d %s): %s", e.Status, e.Code, e.Message)
|
||||
}
|
||||
return fmt.Sprintf("the catalog refused the upload (%d %s)", e.Status, e.Code)
|
||||
}
|
||||
|
||||
// Registered is the hub's product and revision for an upload.
|
||||
type Registered struct {
|
||||
Product string `json:"product"`
|
||||
Revision int `json:"revision"`
|
||||
}
|
||||
|
||||
// Upload posts a .chkn to the catalog's upload URL with an import token.
|
||||
func Upload(ctx context.Context, client *http.Client, userAgent, url, token string, chkn []byte) (*Registered, error) {
|
||||
var body bytes.Buffer
|
||||
form := multipart.NewWriter(&body)
|
||||
w, err := form.CreateFormFile("file", "product.chkn")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := w.Write(chkn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := form.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", form.FormDataContentType())
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
e := &Error{Status: resp.StatusCode}
|
||||
var r struct {
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if json.Unmarshal(data, &r) == nil {
|
||||
e.Code, e.Message = r.Error, r.Message
|
||||
}
|
||||
return nil, e
|
||||
}
|
||||
var reg Registered
|
||||
if err := json.Unmarshal(data, ®); err != nil {
|
||||
return nil, fmt.Errorf("the catalog's answer: %w", err)
|
||||
}
|
||||
return ®, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUploadRefused(t *testing.T) {
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer tok" {
|
||||
t.Errorf("authorization %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"error":"bad_files","message":"These product files can't be used: index.xml: no ProductRating"}`))
|
||||
}))
|
||||
defer s.Close()
|
||||
_, err := Upload(context.Background(), nil, "test", s.URL, "tok", []byte("zip"))
|
||||
var e *Error
|
||||
if !errors.As(err, &e) || e.Status != 400 || e.Code != "bad_files" {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
if e.Error() != "the catalog refused the upload (400 bad_files): These product files can't be used: index.xml: no ProductRating" {
|
||||
t.Errorf("message %q", e.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Package convert turns an IMVU product revision, as IMVU's CDN serves it, into a T5 product's files (t5de-hub's
|
||||
// docs/imports.md, "What's imported"): the CFL's entries, with the small placeholder textures replaced by the
|
||||
// originals its _contents.json names (and files kept only on the CDN fetched), without _contents.json (packs don't
|
||||
// use it), and with index.xml's ProductRating set. The parent stays as index.xml names it (__DATAIMPORT).
|
||||
package convert
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"git.t5de.dev/t5de/t5de-api/cfl"
|
||||
"git.t5de.dev/t5de/t5de-api/pack"
|
||||
)
|
||||
|
||||
// ContentsName is the file listing a revision's files on the CDN.
|
||||
const ContentsName = "_contents.json"
|
||||
|
||||
// File is one of a product's files.
|
||||
type File struct {
|
||||
Name string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// content is one _contents.json entry. Originals (tag "original") and files kept only on the CDN have a url.
|
||||
type content struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Tags []string `json:"tags"`
|
||||
}
|
||||
|
||||
// Fetch downloads a file of the revision by its _contents.json url.
|
||||
type Fetch func(ctx context.Context, url string) ([]byte, error)
|
||||
|
||||
// Files converts a revision's CFL entries. rating is IMVU's ("general" or "adult"); the files say AP if either
|
||||
// IMVU or the files themselves do.
|
||||
func Files(ctx context.Context, entries []cfl.Entry, rating string, fetch Fetch) ([]File, error) {
|
||||
if rating != "general" && rating != "adult" {
|
||||
return nil, fmt.Errorf("unknown rating %q", rating)
|
||||
}
|
||||
files := make([]File, 0, len(entries))
|
||||
at := map[string]int{}
|
||||
var contents []content
|
||||
for _, e := range entries {
|
||||
if e.Name == ContentsName {
|
||||
if err := json.Unmarshal(e.Data, &contents); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", ContentsName, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, dup := at[e.Name]; dup {
|
||||
return nil, fmt.Errorf("the CFL has %q twice", e.Name)
|
||||
}
|
||||
at[e.Name] = len(files)
|
||||
files = append(files, File{Name: e.Name, Data: e.Data})
|
||||
}
|
||||
for _, c := range contents {
|
||||
if c.URL == "" || c.Name == ContentsName {
|
||||
continue
|
||||
}
|
||||
i, inCFL := at[c.Name]
|
||||
if inCFL && !slices.Contains(c.Tags, "original") {
|
||||
continue
|
||||
}
|
||||
data, err := fetch(ctx, c.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", c.Name, err)
|
||||
}
|
||||
if inCFL {
|
||||
files[i].Data = data
|
||||
} else {
|
||||
at[c.Name] = len(files)
|
||||
files = append(files, File{Name: c.Name, Data: data})
|
||||
}
|
||||
}
|
||||
i, ok := at[pack.IndexName]
|
||||
if !ok {
|
||||
return nil, errors.New("the product has no index.xml")
|
||||
}
|
||||
index, err := SetRating(files[i].Data, rating)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files[i].Data = index
|
||||
return files, nil
|
||||
}
|
||||
|
||||
var (
|
||||
ratingElement = regexp.MustCompile(`<ProductRating>\s*([A-Za-z]*)\s*</ProductRating>`)
|
||||
templateOpen = regexp.MustCompile(`<Template(\s[^>]*)?>`)
|
||||
)
|
||||
|
||||
// SetRating sets index.xml's ProductRating: AP if rating is "adult" or it says AP already, else GA. IMVU's files
|
||||
// usually have none, and the hub rates an imported revision the higher of IMVU's rating and the files'.
|
||||
func SetRating(index []byte, rating string) ([]byte, error) {
|
||||
want := "GA"
|
||||
if m := ratingElement.FindSubmatch(index); rating == "adult" || (m != nil && string(m[1]) == "AP") {
|
||||
want = "AP"
|
||||
}
|
||||
element := []byte("<ProductRating>" + want + "</ProductRating>")
|
||||
if loc := ratingElement.FindIndex(index); loc != nil {
|
||||
return slices.Concat(index[:loc[0]], element, index[loc[1]:]), nil
|
||||
}
|
||||
loc := templateOpen.FindIndex(index)
|
||||
if loc == nil {
|
||||
return nil, errors.New("index.xml has no <Template>")
|
||||
}
|
||||
return slices.Concat(index[:loc[1]], []byte("\n"), element, index[loc[1]:]), nil
|
||||
}
|
||||
|
||||
// Chkn zips the files at the root, as Create Mode's .chkn: what the catalog's upload takes.
|
||||
func Chkn(files []File) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
z := zip.NewWriter(&b)
|
||||
for _, f := range files {
|
||||
w, err := z.CreateHeader(&zip.FileHeader{Name: f.Name, Method: zip.Deflate})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := w.Write(f.Data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := z.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// Check checks a .chkn by t5de-api's pack rules, as the catalog will (names, limits, index.xml and its rating), so
|
||||
// a product that breaks them fails here with the reason. tmp is a folder for the check's files.
|
||||
func Check(chkn []byte, imvuProduct int64, rating string, tmp string) error {
|
||||
dir, err := os.MkdirTemp(tmp, "check-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
m := pack.Manifest{Format: 1, ID: "imvu-" + strconv.FormatInt(imvuProduct, 10), Revision: 1, Name: "IMVU product", Rating: rating}
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, pack.ManifestName), b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, pack.ChknName), chkn, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = pack.Load(dir)
|
||||
return err
|
||||
}
|
||||
|
||||
// Rating is the pack rating ("general", "adult") that index.xml's ProductRating means.
|
||||
func Rating(index []byte) string {
|
||||
if m := ratingElement.FindSubmatch(index); m != nil && string(m[1]) == "AP" {
|
||||
return "adult"
|
||||
}
|
||||
return "general"
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.t5de.dev/t5de/t5de-api/cfl"
|
||||
)
|
||||
|
||||
func TestSetRating(t *testing.T) {
|
||||
for _, c := range []struct{ in, rating, want string }{
|
||||
{"<Template>\n<X/></Template>", "general", "<Template>\n<ProductRating>GA</ProductRating>\n<X/></Template>"},
|
||||
{"<Template>\n<X/></Template>", "adult", "<Template>\n<ProductRating>AP</ProductRating>\n<X/></Template>"},
|
||||
{`<?xml version="1.0"?><Template a="b"></Template>`, "general", `<?xml version="1.0"?><Template a="b">` + "\n<ProductRating>GA</ProductRating></Template>"},
|
||||
{"<Template><ProductRating>AP</ProductRating></Template>", "general", "<Template><ProductRating>AP</ProductRating></Template>"},
|
||||
{"<Template><ProductRating> GA </ProductRating></Template>", "adult", "<Template><ProductRating>AP</ProductRating></Template>"},
|
||||
{"<Template><ProductRating>GA</ProductRating></Template>", "general", "<Template><ProductRating>GA</ProductRating></Template>"},
|
||||
} {
|
||||
got, err := SetRating([]byte(c.in), c.rating)
|
||||
if err != nil || string(got) != c.want {
|
||||
t.Errorf("%q, %s: got %q, %v; want %q", c.in, c.rating, got, err, c.want)
|
||||
}
|
||||
}
|
||||
if _, err := SetRating([]byte("<NotATemplate/>"), "general"); err == nil {
|
||||
t.Error("no <Template>: no error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFiles(t *testing.T) {
|
||||
contents := `[{"name":"tex.png","url":"abc.png","tags":["original","thumbnail"]},` +
|
||||
`{"name":"mat.xrf","url":"def.xrf"},{"name":"cdn-only.xrf","url":"ghi.xrf"},{"name":"small.png","tags":["original"]},{"name":"index.xml"}]`
|
||||
entries := []cfl.Entry{
|
||||
{Name: "index.xml", Data: []byte("<Template>\n</Template>")},
|
||||
{Name: "tex.png", Data: []byte("placeholder")},
|
||||
{Name: "mat.xrf", Data: []byte("material")},
|
||||
{Name: "small.png", Data: []byte("small original")},
|
||||
{Name: "_contents.json", Data: []byte(contents)},
|
||||
}
|
||||
cdn := map[string]string{"abc.png": "full-size original", "ghi.xrf": "only on the CDN"}
|
||||
var asked []string
|
||||
fetch := func(_ context.Context, url string) ([]byte, error) {
|
||||
asked = append(asked, url)
|
||||
if s, ok := cdn[url]; ok {
|
||||
return []byte(s), nil
|
||||
}
|
||||
return nil, errors.New("missing")
|
||||
}
|
||||
files, err := Files(context.Background(), entries, "adult", fetch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]string{}
|
||||
var names []string
|
||||
for _, f := range files {
|
||||
got[f.Name] = string(f.Data)
|
||||
names = append(names, f.Name)
|
||||
}
|
||||
want := map[string]string{
|
||||
"index.xml": "<Template>\n<ProductRating>AP</ProductRating>\n</Template>",
|
||||
"tex.png": "full-size original",
|
||||
"mat.xrf": "material", // in the CFL already, not an original
|
||||
"small.png": "small original",
|
||||
"cdn-only.xrf": "only on the CDN",
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Errorf("files %v", names)
|
||||
}
|
||||
for n, w := range want {
|
||||
if got[n] != w {
|
||||
t.Errorf("%s: got %q, want %q", n, got[n], w)
|
||||
}
|
||||
}
|
||||
if strings.Join(asked, ",") != "abc.png,ghi.xrf" {
|
||||
t.Errorf("fetched %v", asked)
|
||||
}
|
||||
|
||||
if _, err := Files(context.Background(), entries[1:], "general", fetch); err == nil {
|
||||
t.Error("no index.xml: no error")
|
||||
}
|
||||
cdn = nil
|
||||
if _, err := Files(context.Background(), entries, "general", fetch); err == nil {
|
||||
t.Error("an original missing: no error")
|
||||
}
|
||||
if _, err := Files(context.Background(), entries, "", fetch); err == nil {
|
||||
t.Error("no rating: no error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChknAndCheck(t *testing.T) {
|
||||
index, _ := SetRating([]byte("<Template>\n</Template>"), "general")
|
||||
files := []File{{Name: "index.xml", Data: index}, {Name: "Skin%20%5B03%5D.xrf", Data: []byte{1, 2, 3}}}
|
||||
chkn, err := Chkn(files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
z, err := zip.NewReader(bytes.NewReader(chkn), int64(len(chkn)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, f := range z.File {
|
||||
r, _ := f.Open()
|
||||
data, _ := io.ReadAll(r)
|
||||
if f.Name != files[i].Name || !bytes.Equal(data, files[i].Data) {
|
||||
t.Errorf("zip entry %d: %q", i, f.Name)
|
||||
}
|
||||
}
|
||||
if err := Check(chkn, 42, "general", t.TempDir()); err != nil {
|
||||
t.Errorf("check: %v", err)
|
||||
}
|
||||
if err := Check(chkn, 42, "adult", t.TempDir()); err == nil {
|
||||
t.Error("rating disagreeing with index.xml: no error")
|
||||
}
|
||||
bad, _ := Chkn(append(files, File{Name: "_contents.json", Data: []byte("[]")}))
|
||||
if err := Check(bad, 42, "general", t.TempDir()); err == nil {
|
||||
t.Error("_contents.json: no error")
|
||||
}
|
||||
if Rating(index) != "general" {
|
||||
t.Error("Rating of GA")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Package hub talks to T5DE's hub as a catalog's importer: t5de-hub's docs/products.md ("For importers") and
|
||||
// docs/imports.md. Every request carries `Authorization: Importer <catalog ID>:<key>`.
|
||||
package hub
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Client is one catalog's importer at a hub.
|
||||
type Client struct {
|
||||
url string
|
||||
auth string
|
||||
userAgent string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New makes a client for the hub at hubURL (its base, without /api/v1).
|
||||
func New(hubURL, catalog, key, userAgent string, client *http.Client) *Client {
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
return &Client{
|
||||
url: strings.TrimRight(hubURL, "/"),
|
||||
auth: "Importer " + catalog + ":" + key,
|
||||
userAgent: userAgent,
|
||||
http: client,
|
||||
}
|
||||
}
|
||||
|
||||
// Error is the hub's refusal: its status and `{error, message}`.
|
||||
type Error struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Message != "" {
|
||||
return fmt.Sprintf("hub: %d %s: %s", e.Status, e.Code, e.Message)
|
||||
}
|
||||
return fmt.Sprintf("hub: %d %s", e.Status, e.Code)
|
||||
}
|
||||
|
||||
// Settings are the importer's settings from the console.
|
||||
type Settings struct {
|
||||
Rate float64 `json:"rate"` // requests a second to IMVU, 0.2-10
|
||||
Concurrency int `json:"concurrency"` // jobs at once, 1-8
|
||||
}
|
||||
|
||||
// Account is an IMVU account the catalog's team added. Sealed is set until the importer says it has it.
|
||||
type Account struct {
|
||||
ID string `json:"id"`
|
||||
IMVUID int64 `json:"imvuId"`
|
||||
Username string `json:"username"`
|
||||
Sealed *string `json:"sealed"`
|
||||
}
|
||||
|
||||
// Config is what the importer runs with.
|
||||
type Config struct {
|
||||
Paused bool `json:"paused"`
|
||||
Settings Settings `json:"settings"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Accounts []Account `json:"accounts"`
|
||||
}
|
||||
|
||||
// Job is a claimed import job. Rating is IMVU's ("general", "adult"), or "" when the hub couldn't see it.
|
||||
type Job struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"` // "import" or "recheck"
|
||||
IMVUProduct int64 `json:"imvuProduct"`
|
||||
LastRevision int `json:"lastRevision"` // the newest IMVU revision imported already, or 0
|
||||
Rating string `json:"rating"`
|
||||
}
|
||||
|
||||
// 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
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/importer/hello", map[string]string{"version": version, "publicKey": publicKey}, &cfg)
|
||||
return &cfg, err
|
||||
}
|
||||
|
||||
// Config fetches the importer's config.
|
||||
func (c *Client) Config(ctx context.Context) (*Config, error) {
|
||||
var cfg Config
|
||||
err := c.do(ctx, http.MethodGet, "/api/v1/importer/config", nil, &cfg)
|
||||
return &cfg, err
|
||||
}
|
||||
|
||||
// Claim claims up to limit (1-20) queued jobs.
|
||||
func (c *Client) Claim(ctx context.Context, limit int) ([]Job, error) {
|
||||
var r struct {
|
||||
Jobs []Job `json:"jobs"`
|
||||
}
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/importer/jobs/claim", map[string]int{"limit": limit}, &r)
|
||||
return r.Jobs, err
|
||||
}
|
||||
|
||||
// Token gets a t5de-import token for a claimed job's IMVU revision, and the catalog's upload URL.
|
||||
func (c *Client) Token(ctx context.Context, job string, imvuRevision int) (token, uploadURL string, err error) {
|
||||
var r struct {
|
||||
Token string `json:"token"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
err = c.do(ctx, http.MethodPost, "/api/v1/importer/jobs/"+url.PathEscape(job)+"/token", map[string]int{"imvuRevision": imvuRevision}, &r)
|
||||
return r.Token, r.URL, err
|
||||
}
|
||||
|
||||
// Outcome is a job's outcome, for Report.
|
||||
type Outcome struct {
|
||||
Status string `json:"status"` // "done", "unchanged" or "failed"
|
||||
IMVURevision int `json:"imvuRevision,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// Report reports a job's outcome. (An upload the catalog registered marks its job done already.)
|
||||
func (c *Client) Report(ctx context.Context, job string, o Outcome) error {
|
||||
if len(o.Reason) > 2000 {
|
||||
o.Reason = o.Reason[:2000]
|
||||
}
|
||||
return c.do(ctx, http.MethodPost, "/api/v1/importer/jobs/"+url.PathEscape(job), o, nil)
|
||||
}
|
||||
|
||||
// AccountReport is what the importer says about an account.
|
||||
type AccountReport struct {
|
||||
Received bool `json:"received,omitempty"`
|
||||
State string `json:"state,omitempty"` // "ok", "sign_in_failed" or "needs_password"
|
||||
AccessPass *bool `json:"accessPass,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// ReportAccount reports on an account: that the importer has its password, then how signing in went.
|
||||
func (c *Client) ReportAccount(ctx context.Context, id string, r AccountReport) error {
|
||||
return c.do(ctx, http.MethodPost, "/api/v1/importer/accounts/"+url.PathEscape(id), r, nil)
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
|
||||
var body io.Reader
|
||||
if in != nil {
|
||||
b, err := json.Marshal(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.url+path, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", c.auth)
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
if in != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
e := &Error{Status: resp.StatusCode}
|
||||
var r struct {
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if json.Unmarshal(data, &r) == nil {
|
||||
e.Code, e.Message = r.Error, r.Message
|
||||
}
|
||||
return e
|
||||
}
|
||||
if out == nil {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(data, out); err != nil {
|
||||
return fmt.Errorf("hub: %s %s: %w", method, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Package imvu fetches products' files from IMVU's CDN, which serves them to anyone: a revision's CFL at
|
||||
// productdata/<product>/<revision>, and the files its _contents.json names at productdata/<product>/<revision>/<url>
|
||||
// (t5de-hub's docs/imports.md, "Spike"). Every request waits its turn at a shared rate.
|
||||
package imvu
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CDNURL is IMVU's product files.
|
||||
const CDNURL = "https://userimages-akm.imvu.com/productdata"
|
||||
|
||||
// Size limits on downloads: a CFL (compressed) and one file. Products are far smaller (the spike's largest was
|
||||
// 0.29 MiB); the pack limits are 64 MiB a file, 256 MiB in all.
|
||||
const (
|
||||
MaxCFL = 256 << 20
|
||||
MaxFile = 64 << 20
|
||||
)
|
||||
|
||||
// Misses is how many missing revisions in a row end a probe: revisions are numbered from 1, without gaps so far.
|
||||
const Misses = 3
|
||||
|
||||
// CDN is IMVU's CDN.
|
||||
type CDN struct {
|
||||
URL string // CDNURL, or a test server's
|
||||
UserAgent string
|
||||
HTTP *http.Client
|
||||
Limiter *Limiter
|
||||
}
|
||||
|
||||
// ErrMissing is a file the CDN doesn't have.
|
||||
var ErrMissing = errors.New("not on IMVU's CDN")
|
||||
|
||||
// Exists says whether a product revision is on the CDN.
|
||||
func (c *CDN) Exists(ctx context.Context, product int64, revision int) (bool, error) {
|
||||
resp, err := c.request(ctx, http.MethodHead, c.revisionURL(product, revision))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
resp.Body.Close()
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusOK:
|
||||
return true, nil
|
||||
case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden:
|
||||
return false, nil
|
||||
default:
|
||||
return false, fmt.Errorf("IMVU's CDN answered %d for product %d revision %d", resp.StatusCode, product, revision)
|
||||
}
|
||||
}
|
||||
|
||||
// Latest probes revisions from `from` up until Misses in a row are missing, and returns the newest found (0: none).
|
||||
// Probes returns how many requests that took.
|
||||
func (c *CDN) Latest(ctx context.Context, product int64, from int) (latest, probes int, err error) {
|
||||
if from < 1 {
|
||||
from = 1
|
||||
}
|
||||
for n, miss := from, 0; miss < Misses; n++ {
|
||||
probes++
|
||||
ok, err := c.Exists(ctx, product, n)
|
||||
if err != nil {
|
||||
return 0, probes, err
|
||||
}
|
||||
if ok {
|
||||
latest, miss = n, 0
|
||||
} else {
|
||||
miss++
|
||||
}
|
||||
}
|
||||
return latest, probes, nil
|
||||
}
|
||||
|
||||
// CFL downloads a product revision's CFL.
|
||||
func (c *CDN) CFL(ctx context.Context, product int64, revision int) ([]byte, error) {
|
||||
return c.get(ctx, c.revisionURL(product, revision), MaxCFL)
|
||||
}
|
||||
|
||||
// File downloads a file of a product revision by the url its _contents.json gives (a name relative to the
|
||||
// revision's folder).
|
||||
func (c *CDN) File(ctx context.Context, product int64, revision int, name string) ([]byte, error) {
|
||||
if name == "" || strings.ContainsAny(name, "/\\?#") || name == "." || name == ".." {
|
||||
return nil, fmt.Errorf("_contents.json names a file %q outside the revision", name)
|
||||
}
|
||||
return c.get(ctx, c.revisionURL(product, revision)+"/"+url.PathEscape(name), MaxFile)
|
||||
}
|
||||
|
||||
func (c *CDN) revisionURL(product int64, revision int) string {
|
||||
return strings.TrimRight(c.URL, "/") + "/" + strconv.FormatInt(product, 10) + "/" + strconv.Itoa(revision)
|
||||
}
|
||||
|
||||
func (c *CDN) get(ctx context.Context, u string, limit int64) ([]byte, error) {
|
||||
resp, err := c.request(ctx, http.MethodGet, u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden {
|
||||
return nil, fmt.Errorf("%s: %w", u, ErrMissing)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("IMVU's CDN answered %d for %s", resp.StatusCode, u)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", u, err)
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("%s is over %d bytes", u, limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (c *CDN) request(ctx context.Context, method, u string) (*http.Response, error) {
|
||||
if err := c.Limiter.Wait(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", c.UserAgent)
|
||||
client := c.HTTP
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
// Limiter spaces requests out to a rate (a second), shared by every job; the rate can change while it runs.
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
gap time.Duration
|
||||
next time.Time
|
||||
}
|
||||
|
||||
// NewLimiter makes a limiter for rate requests a second.
|
||||
func NewLimiter(rate float64) *Limiter {
|
||||
l := &Limiter{}
|
||||
l.SetRate(rate)
|
||||
return l
|
||||
}
|
||||
|
||||
// SetRate changes the rate, in requests a second (at least one a minute).
|
||||
func (l *Limiter) SetRate(rate float64) {
|
||||
if rate < 1.0/60 {
|
||||
rate = 1.0 / 60
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.gap = time.Duration(float64(time.Second) / rate)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// Wait waits for the next request's turn.
|
||||
func (l *Limiter) Wait(ctx context.Context) error {
|
||||
l.mu.Lock()
|
||||
now := time.Now()
|
||||
at := l.next
|
||||
if at.Before(now) {
|
||||
at = now
|
||||
}
|
||||
l.next = at.Add(l.gap)
|
||||
l.mu.Unlock()
|
||||
if d := time.Until(at); d > 0 {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package imvu_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/imvu"
|
||||
"git.t5de.dev/t5de/t5de-importer/internal/imvutest"
|
||||
)
|
||||
|
||||
func TestLatest(t *testing.T) {
|
||||
cdn := imvutest.New(t)
|
||||
for _, rev := range []int{1, 2, 3, 5} { // 4 missing: a gap shorter than Misses is crossed
|
||||
cdn.Add(7, rev, imvutest.File{Name: "index.xml", Data: imvutest.Index(1)})
|
||||
}
|
||||
c := &imvu.CDN{URL: cdn.URL, Limiter: imvu.NewLimiter(1000)}
|
||||
ctx := context.Background()
|
||||
for _, tc := range []struct{ from, latest, probes int }{{0, 5, 8}, {1, 5, 8}, {4, 5, 5}, {6, 0, 3}} {
|
||||
latest, probes, err := c.Latest(ctx, 7, tc.from)
|
||||
if err != nil || latest != tc.latest || probes != tc.probes {
|
||||
t.Errorf("from %d: latest %d, %d probes, %v; want %d, %d", tc.from, latest, probes, err, tc.latest, tc.probes)
|
||||
}
|
||||
}
|
||||
if _, err := c.CFL(ctx, 7, 4); !errors.Is(err, imvu.ErrMissing) {
|
||||
t.Errorf("missing revision: %v", err)
|
||||
}
|
||||
if _, err := c.File(ctx, 7, 1, "../../8/1"); err == nil {
|
||||
t.Error("a file outside the revision: no error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiter(t *testing.T) {
|
||||
l := imvu.NewLimiter(50) // 20 ms apart
|
||||
start := time.Now()
|
||||
for range 6 {
|
||||
if err := l.Wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if d := time.Since(start); d < 90*time.Millisecond {
|
||||
t.Errorf("6 requests at 50 a second took %s", d)
|
||||
}
|
||||
l.SetRate(0.001) // a minute apart
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
l.Wait(ctx) // the next turn is ~20 ms away
|
||||
if err := l.Wait(ctx); err == nil {
|
||||
t.Error("waited a minute within 20 ms")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Package imvutest fakes IMVU's CDN for tests: products made in code (never IMVU's files), served as IMVU serves
|
||||
// them, in LZMA-compressed CFLs with a _contents.json.
|
||||
package imvutest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.t5de.dev/t5de/t5de-api/cfl"
|
||||
"github.com/ulikunitz/xz/lzma"
|
||||
)
|
||||
|
||||
// File is a file of a fake revision. Original, if set, is served on the CDN under URL as the full-size original
|
||||
// (Data is then the CFL's placeholder); with no Data and an URL, the file is on the CDN only.
|
||||
type File struct {
|
||||
Name string
|
||||
Data []byte
|
||||
URL string
|
||||
Original []byte
|
||||
}
|
||||
|
||||
// CDN is a fake CDN: Revisions[product][revision] is a revision's files.
|
||||
type CDN struct {
|
||||
*httptest.Server
|
||||
mu sync.Mutex
|
||||
Revisions map[int64]map[int][]File
|
||||
Requests map[string]int // by method
|
||||
}
|
||||
|
||||
// New starts a fake CDN.
|
||||
func New(t testing.TB) *CDN {
|
||||
c := &CDN{Revisions: map[int64]map[int][]File{}, Requests: map[string]int{}}
|
||||
c.Server = httptest.NewServer(http.HandlerFunc(c.serve))
|
||||
t.Cleanup(c.Close)
|
||||
return c
|
||||
}
|
||||
|
||||
// Add adds a product revision.
|
||||
func (c *CDN) Add(product int64, revision int, files ...File) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.Revisions[product] == nil {
|
||||
c.Revisions[product] = map[int][]File{}
|
||||
}
|
||||
c.Revisions[product][revision] = files
|
||||
}
|
||||
|
||||
func (c *CDN) serve(w http.ResponseWriter, r *http.Request) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.Requests[r.Method]++
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) < 2 || len(parts) > 3 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
product, _ := strconv.ParseInt(parts[0], 10, 64)
|
||||
revision, _ := strconv.Atoi(parts[1])
|
||||
files, ok := c.Revisions[product][revision]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if len(parts) == 3 {
|
||||
for _, f := range files {
|
||||
if f.URL == parts[2] {
|
||||
data := f.Original
|
||||
if data == nil {
|
||||
data = f.Data
|
||||
}
|
||||
w.Write(data)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Write(Compressed(files))
|
||||
}
|
||||
|
||||
// Compressed is a revision's CFL as IMVU's CDN serves it: its files that have Data, and _contents.json, every entry
|
||||
// and the directory LZMA-compressed (pylzma's format, with end markers).
|
||||
func Compressed(files []File) []byte {
|
||||
type content struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
}
|
||||
var entries []cfl.Entry
|
||||
var contents []content
|
||||
for _, f := range files {
|
||||
c := content{Name: f.Name, URL: f.URL}
|
||||
if f.Original != nil {
|
||||
c.Tags = []string{"original", "thumbnail"}
|
||||
}
|
||||
contents = append(contents, c)
|
||||
if f.Data != nil {
|
||||
entries = append(entries, cfl.Entry{Name: f.Name, Data: f.Data})
|
||||
}
|
||||
}
|
||||
list, _ := json.Marshal(contents)
|
||||
entries = append(entries, cfl.Entry{Name: "_contents.json", Data: list})
|
||||
|
||||
le := binary.LittleEndian
|
||||
b := make([]byte, 12)
|
||||
copy(b, "CFL3")
|
||||
var dir []byte
|
||||
for _, e := range entries {
|
||||
offset := len(b)
|
||||
stored := pylzma(e.Data)
|
||||
b = le.AppendUint32(b, uint32(len(stored)))
|
||||
b = append(b, stored...)
|
||||
name, _ := cfl.Latin1(e.Name)
|
||||
dir = le.AppendUint32(dir, uint32(len(e.Data)))
|
||||
dir = le.AppendUint32(dir, uint32(offset))
|
||||
dir = le.AppendUint32(dir, cfl.LZMA)
|
||||
dir = le.AppendUint16(dir, uint16(len(name)))
|
||||
dir = append(dir, name...)
|
||||
}
|
||||
le.PutUint32(b[4:], uint32(len(b)))
|
||||
le.PutUint32(b[8:], uint32(len(dir)))
|
||||
stored := pylzma(dir)
|
||||
b = le.AppendUint32(b, cfl.LZMA)
|
||||
b = le.AppendUint32(b, uint32(len(stored)))
|
||||
return append(b, stored...)
|
||||
}
|
||||
|
||||
// pylzma compresses as pylzma does: 5 property bytes, then the raw stream with an end marker.
|
||||
func pylzma(data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
w, err := lzma.WriterConfig{EOSMarker: true}.NewWriter(&b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
w.Write(data)
|
||||
if err := w.Close(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
out := b.Bytes()
|
||||
return append(bytes.Clone(out[:5]), out[lzma.HeaderLen:]...)
|
||||
}
|
||||
|
||||
// Index is a minimal index.xml as IMVU's files have it: a parent, and no ProductRating.
|
||||
func Index(parent int64) []byte {
|
||||
return []byte(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Template>
|
||||
<__DATAIMPORT>product://` + strconv.FormatInt(parent, 10) + `/index.xml</__DATAIMPORT><ParticleSystems>
|
||||
</ParticleSystems>
|
||||
</Template>
|
||||
`)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// Package keys holds the importer's RSA key pair, which the catalog's team seals IMVU account passwords for
|
||||
// (RSA-OAEP with SHA-256, in their browser): t5de-hub's docs/imports.md, "IMVU accounts".
|
||||
package keys
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Bits is the size of keys Load makes.
|
||||
const Bits = 3072
|
||||
|
||||
// FileName is the private key's file in the data folder.
|
||||
const FileName = "importer-key.pem"
|
||||
|
||||
// Key is the importer's key pair.
|
||||
type Key struct {
|
||||
private *rsa.PrivateKey
|
||||
// PublicKey is the public key as base64 SPKI (DER), as the hub takes it.
|
||||
PublicKey string
|
||||
// Fingerprint is sha256 of the SPKI, hex, as the console shows it.
|
||||
Fingerprint string
|
||||
}
|
||||
|
||||
// Load reads the key pair from dir, or makes one (and says so) if there's none.
|
||||
func Load(dir string) (k *Key, made bool, err error) {
|
||||
path := filepath.Join(dir, FileName)
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, Bits)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
der, err := x509.MarshalPKCS8PrivateKey(priv)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0o600); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
k, err := fromPrivate(priv)
|
||||
return k, true, err
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
block, _ := pem.Decode(data)
|
||||
if block == nil || block.Type != "PRIVATE KEY" {
|
||||
return nil, false, fmt.Errorf("%s isn't a PEM private key", path)
|
||||
}
|
||||
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
priv, ok := parsed.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, false, fmt.Errorf("%s isn't an RSA key", path)
|
||||
}
|
||||
k, err = fromPrivate(priv)
|
||||
return k, false, err
|
||||
}
|
||||
|
||||
func fromPrivate(priv *rsa.PrivateKey) (*Key, error) {
|
||||
spki, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(spki)
|
||||
return &Key{private: priv, PublicKey: base64.StdEncoding.EncodeToString(spki), Fingerprint: hex.EncodeToString(sum[:])}, nil
|
||||
}
|
||||
|
||||
// Open opens a sealed password: base64 of RSA-OAEP (SHA-256) over `{"imvuId": …, "password": …}`. It must be for
|
||||
// imvuID, so a sealed password can't be moved to another account.
|
||||
func (k *Key) Open(sealed string, imvuID int64) (string, error) {
|
||||
ct, err := base64.StdEncoding.DecodeString(sealed)
|
||||
if err != nil {
|
||||
return "", errors.New("the sealed password isn't base64")
|
||||
}
|
||||
plain, err := rsa.DecryptOAEP(sha256.New(), nil, k.private, ct, nil)
|
||||
if err != nil {
|
||||
return "", errors.New("the sealed password can't be opened with this importer's key")
|
||||
}
|
||||
var v struct {
|
||||
IMVUID int64 `json:"imvuId"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.Unmarshal(plain, &v); err != nil {
|
||||
return "", errors.New("the sealed password isn't what the console seals")
|
||||
}
|
||||
if v.IMVUID != imvuID {
|
||||
return "", errors.New("the sealed password is for another IMVU account")
|
||||
}
|
||||
if v.Password == "" {
|
||||
return "", errors.New("the sealed password is empty")
|
||||
}
|
||||
return v.Password, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package keys
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// seal seals as the console does in the browser: RSA-OAEP with SHA-256 over {"imvuId", "password"}.
|
||||
func seal(t *testing.T, k *Key, plain string) string {
|
||||
t.Helper()
|
||||
der, _ := base64.StdEncoding.DecodeString(k.PublicKey)
|
||||
pub, err := x509.ParsePKIXPublicKey(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub.(*rsa.PublicKey), []byte(plain), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(ct)
|
||||
}
|
||||
|
||||
func TestLoadAndOpen(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
k, made, err := Load(dir)
|
||||
if err != nil || !made {
|
||||
t.Fatalf("made %v, %v", made, err)
|
||||
}
|
||||
if k.private.N.BitLen() != Bits || len(k.Fingerprint) != 64 {
|
||||
t.Errorf("bits %d, fingerprint %q", k.private.N.BitLen(), k.Fingerprint)
|
||||
}
|
||||
again, made, err := Load(dir)
|
||||
if err != nil || made || again.Fingerprint != k.Fingerprint || again.PublicKey != k.PublicKey {
|
||||
t.Fatalf("reloaded: made %v, %v", made, err)
|
||||
}
|
||||
if fi, err := os.Stat(filepath.Join(dir, FileName)); err != nil || (fi.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/') {
|
||||
t.Errorf("key file: %v, %v", fi, err)
|
||||
}
|
||||
|
||||
sealed := seal(t, k, `{"imvuId":4242,"password":"hunter2"}`)
|
||||
if pw, err := again.Open(sealed, 4242); err != nil || pw != "hunter2" {
|
||||
t.Errorf("open: %q, %v", pw, err)
|
||||
}
|
||||
if _, err := k.Open(sealed, 4243); err == nil {
|
||||
t.Error("another account's password: no error")
|
||||
}
|
||||
if _, err := k.Open(seal(t, k, `{"imvuId":4242,"password":""}`), 4242); err == nil {
|
||||
t.Error("empty password: no error")
|
||||
}
|
||||
if _, err := k.Open("not base64!", 4242); err == nil {
|
||||
t.Error("not base64: no error")
|
||||
}
|
||||
other, _, _ := Load(t.TempDir())
|
||||
if _, err := other.Open(sealed, 4242); err == nil {
|
||||
t.Error("another importer's key: no error")
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filepath.Join(dir, FileName), []byte("junk"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := Load(dir); err == nil {
|
||||
t.Error("junk key file: no error")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user