diff --git a/.gitea/default_merge_message/SQUASH_TEMPLATE.md b/.gitea/default_merge_message/SQUASH_TEMPLATE.md new file mode 100644 index 0000000..97c80b4 --- /dev/null +++ b/.gitea/default_merge_message/SQUASH_TEMPLATE.md @@ -0,0 +1,3 @@ +${PullRequestTitle} (#${PullRequestIndex}) + +${PullRequestDescription} diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..b8b0091 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,69 @@ +# Tests the importer and builds t5de-importer for Linux (static); then, for main and vX.Y.Z tags, builds its image and +# pushes it to git.t5de.dev. CI never deploys. +name: CI + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + env: + # T5DE's modules (t5de-api) come straight from its Gitea, not through Go's public module proxy. + GOPRIVATE: git.t5de.dev + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Test + run: | + unformatted=$(gofmt -l .) + if [ -n "$unformatted" ]; then echo "Not gofmt-formatted: $unformatted"; exit 1; fi + go vet ./... + go test ./... + + # Static and reproducible: no cgo, no paths, no build ID. + - name: Build t5de-importer + run: | + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -buildvcs=false \ + -ldflags "-s -w -buildid= -X git.t5de.dev/t5de/t5de-importer/internal/buildinfo.Version=${GITHUB_SHA::12}" \ + -o dist/t5de-importer ./cmd/t5de-importer + sha256sum dist/t5de-importer + + # main → :latest-main and :main-; vX.Y.Z → :X.Y.Z, :X.Y and :latest. Built by the runner's Docker; the build + # fetches T5DE's Go modules from git.t5de.dev at the address the runner gives this job. + image: + needs: build + if: github.event_name == 'push' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Build and push + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + IMAGE: git.t5de.dev/t5de/t5de-importer + run: | + case "$GITHUB_REF" in + refs/heads/main) version="main-${GITHUB_SHA::12}"; tags="latest-main $version" ;; + refs/tags/v*) + version="${GITHUB_REF#refs/tags/v}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Not a vX.Y.Z tag: no image"; exit 0; } + tags="$version ${version%.*} latest" ;; + *) echo "Not main or a tag: no image"; exit 0 ;; + esac + git_ip=$(getent ahostsv4 git.t5de.dev | awk '{print $1; exit}') + echo "$REGISTRY_TOKEN" | docker login git.t5de.dev -u deploy --password-stdin + docker build --add-host "git.t5de.dev:$git_ip" --build-arg VERSION="$version" \ + --label org.opencontainers.image.source="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" \ + --label org.opencontainers.image.revision="$GITHUB_SHA" --label org.opencontainers.image.version="$version" \ + $(for t in $tags; do echo "-t $IMAGE:$t"; done) . + for t in $tags; do docker push -q "$IMAGE:$t"; done + docker logout git.t5de.dev diff --git a/.gitea/workflows/pull-request.yml b/.gitea/workflows/pull-request.yml new file mode 100644 index 0000000..f4083fe --- /dev/null +++ b/.gitea/workflows/pull-request.yml @@ -0,0 +1,30 @@ +# A pull request's title becomes its commit on main (squash merges, .gitea/default_merge_message), so it must be a +# conventional commit: the release workflow versions releases and writes the changelog from them. Required to merge +# (branch protection, dhkatz/infra modules/app-repo). +name: Pull request + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + title: + runs-on: ubuntu-latest + steps: + - name: Conventional commit title + env: + TITLE: ${{ github.event.pull_request.title }} + BRANCH: ${{ github.head_ref }} + AUTHOR: ${{ github.event.pull_request.user.login }} + run: | + types="feat|fix|perf|refactor|docs|test|build|ci|chore|style|revert" + conventional="^($types)(\([a-z0-9][a-z0-9./_-]*\))?!?: [^ ]" + if ! [[ "$TITLE" =~ $conventional ]]; then + echo "::error::The title becomes the commit on main, so it must be a conventional commit: type(scope): summary, e.g. \"feat(api): room bans\" or \"fix: crash on an empty catalog\" (! before the colon for a breaking change). Types: ${types//|/, }." + exit 1 + fi + if [[ "$TITLE" =~ ^chore\(release\) ]] && [[ "$BRANCH" != release || "$AUTHOR" != release-bot ]]; then + echo "::error::chore(release) is release-bot's: merging its release pull request is what tags a release." + exit 1 + fi + echo "OK: $TITLE" diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..d3f7b5b --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,86 @@ +# Releases. release-bot keeps one pull request open from the `release` branch, "chore(release): vX.Y.Z": the next +# version and its CHANGELOG.md entry, which git-cliff (cliff.toml) works out from the conventional commits on main +# since the last tag. Merging it makes release-bot tag vX.Y.Z on main and publish the release notes; the tag builds the +# image (ci.yml), which runs beside a catalog (T5DE's own deployment is dhkatz/infra's). Only release-bot may create v* tags. It acts with its +# own token (the org secret RELEASE_TOKEN), not this workflow's: Gitea starts no workflows for what that one does, so +# the release pull request's checks and the tag's build would never run. +name: Release + +on: + push: + branches: [main] + +concurrency: + group: release + +jobs: + release: + runs-on: ubuntu-latest + env: + CLIFF_VERSION: 2.14.2 + CLIFF_SHA512: 95b0c55ab3e351ca7c0285fbbde8f1e8c42906466a173e6884f5c7ca814523bda44cbd4ab26b0aa28cace4c02c5ee6b553e9742bd9d7df47a73b9ef58ea429a9 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Install git-cliff + run: | + archive="git-cliff-$CLIFF_VERSION-x86_64-unknown-linux-musl.tar.gz" + curl -fsSLO "https://github.com/orhun/git-cliff/releases/download/v$CLIFF_VERSION/$archive" + echo "$CLIFF_SHA512 $archive" | sha512sum -c - + mkdir -p "$HOME/.local/bin" + tar -xzf "$archive" --strip-components=1 -C "$HOME/.local/bin" "git-cliff-$CLIFF_VERSION/git-cliff" + rm "$archive" + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + + - name: Tag a merged release, or update the release pull request + env: + TOKEN: ${{ secrets.RELEASE_TOKEN }} + run: | + set -euo pipefail + api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY" + host="${GITHUB_SERVER_URL#https://}" + git config user.name release-bot + git config user.email "release-bot@${host#git.}" + basic=$(printf 'release-bot:%s' "$TOKEN" | base64 -w0) + push() { git -c http.extraHeader="Authorization: Basic $basic" push "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$@"; } + gitea() { curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" "$@"; } + + # The release pull request was merged: tag its commit and publish the release. + if [[ "$(git log -1 --format=%s)" =~ ^chore\(release\):\ (v[0-9]+\.[0-9]+\.[0-9]+) ]]; then + tag="${BASH_REMATCH[1]}" + if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then echo "$tag exists already"; exit 0; fi + git tag "$tag" + push "refs/tags/$tag" + jq -n --arg tag "$tag" --arg body "$(git cliff --latest --strip all)" '{tag_name: $tag, name: $tag, body: $body}' | + gitea -o /dev/null -X POST "$api/releases" -d @- + echo "Released $tag" + exit 0 + fi + + # Otherwise: anything to release since the last tag? (Nothing printed when no commit counts.) + last=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true) + next=$(git cliff --bumped-version 2>/dev/null || true) + next="v${next#v}" + if [ "$next" = v ] || [ "$next" = "$last" ]; then echo "Nothing to release since ${last:-the start}"; exit 0; fi + + notes=$(git cliff --unreleased --bump --strip all) + git switch -C release + git cliff --bump --output CHANGELOG.md + git add CHANGELOG.md + git commit -q -m "chore(release): $next" + push --force HEAD:refs/heads/release + + title="chore(release): $next" + body=$(printf 'Merging this releases **%s**: release-bot tags it on main, CI builds its image, and Komodo deploys it to prod. It updates itself as pull requests are merged.\n\n%s\n' "$next" "$notes") + payload=$(jq -n --arg title "$title" --arg body "$body" '{title: $title, body: $body}') + open=$(gitea "$api/pulls?state=open&limit=50" | jq -r '[.[] | select(.head.ref == "release")][0].number // empty') + if [ -n "$open" ]; then + gitea -o /dev/null -X PATCH "$api/pulls/$open" -d "$payload" + echo "Updated the release pull request #$open: $title" + else + jq '. + {head: "release", base: "main"}' <<<"$payload" | gitea -o /dev/null -X POST "$api/pulls" -d @- + echo "Opened the release pull request: $title" + fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6559156 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/dist/ +/data/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..fb1bd01 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,34 @@ +# t5de-importer + +T5DE's importer (see README.md): it imports IMVU products, with their creators' grants, into a T5DE catalog. Part of +T5DE; the design is t5de-hub's `docs/imports.md` and the hub's importer API is `docs/products.md` ("For importers") +(git.t5de.dev/t5de/t5de-hub, usually checked out beside this one); CFLs and product file rules are t5de-api's `cfl` +and `pack` packages; it uploads to a t5de-catalog. + +## Rules + +- Never commit IMVU's files or code: tests make their products in code (`internal/imvutest`: a minimal `index.xml`, + fake textures), never with files downloaded from IMVU. +- Never commit secrets (importer keys, key pairs, IMVU passwords, tokens). IMVU account passwords never reach the hub + readable: the console seals them for the importer's key, and the importer keeps them sealed on disk. +- Test with a throwaway IMVU account, never a real one. +- Every setting is set on the hub's console (the user wants everything configurable from a UI); environment + variables only for what's needed to reach the hub. +- Commits: author "dhkatz "; never the user's real name or email. +- Changes reach main only through pull requests, squash-merged: the PR's title becomes the commit on main, so it must + be a conventional commit (`feat: …`, `fix(convert): …`, `docs: …`; `!` before the colon for a breaking change), + checked by `.gitea/workflows/pull-request.yml`. Commits on the branch can be anything. Push a branch and open the + pull request on git.t5de.dev (web UI or API); the user merges. +- Releases: release-bot keeps a `chore(release): vX.Y.Z` pull request open (`release.yml`, git-cliff from those + titles); merging it tags vX.Y.Z, which builds the image. Never tag by hand (v* tags are release-bot's). +- Follow t5de-hub's `docs/products.md` and `docs/imports.md` exactly; change them there first if the contract needs + to change. +- Dependencies: the standard library and t5de-api (with its own). Ask before adding others. + +## Notes + +- `gofmt`, `go vet ./...` and `go test ./...` must pass (CI checks them). +- IMVU's CDN (verified 2026-11-07, t5de-hub's docs/imports.md "Spike"): `productdata//` is the CFL + (every entry and the directory LZMA-compressed), `productdata///` the files `_contents.json` + gives a `url` (originals tagged `original`; files only on the CDN). Revisions are numbered from 1 without gaps so + far; the importer stops after 3 missing in a row. IMVU's `index.xml` has no `ProductRating`. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5e47574 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# t5de-importer in a container: a static build on distroless. Its data (key pair, accounts) goes in the /data volume. +# +# docker build -t t5de-importer . +# docker run -v importer-data:/data -e HUB_URL=... -e CATALOG_ID=... -e IMPORTER_KEY=... t5de-importer +FROM golang:1.27-alpine AS build +RUN apk add --no-cache git +# T5DE's modules (t5de-api) come straight from its Gitea. +ENV GOPRIVATE=git.t5de.dev CGO_ENABLED=0 +ARG VERSION=dev +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN go build -trimpath -buildvcs=false \ + -ldflags "-s -w -buildid= -X git.t5de.dev/t5de/t5de-importer/internal/buildinfo.Version=${VERSION}" \ + -o /out/t5de-importer ./cmd/t5de-importer \ + && mkdir /out/data + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /out/t5de-importer /t5de-importer +COPY --from=build --chown=nonroot:nonroot /out/data /data +ENV IMPORTER_DATA=/data +VOLUME /data +ENTRYPOINT ["/t5de-importer"] diff --git a/README.md b/README.md index e9cea5f..9cda985 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,48 @@ # t5de-importer -Imports IMVU products into a T5DE catalog, with their creators' permission. \ No newline at end of file +Imports IMVU products into a T5DE catalog, with their creators' permission. Creators grant a catalog leave to import +their shop (or chosen products) on T5DE's hub; the hub queues the products, and this program, run beside the +catalog ([t5de-catalog](https://git.t5de.dev/t5de/t5de-catalog)), fetches each one from IMVU's CDN, converts it to a +T5 product and uploads it to the catalog. The design is t5de-hub's +[docs/imports.md](https://git.t5de.dev/t5de/t5de-hub/src/branch/main/docs/imports.md). + +Unofficial: not made by or affiliated with IMVU. + +## Running it + +Turn imports on for the catalog on the hub's console (the catalog's Imports page): it shows the importer key once. +Then run the importer with: + +| Variable | | +| --- | --- | +| `HUB_URL` | the hub's API, e.g. `https://api.t5de.dev` | +| `CATALOG_ID` | the catalog's ID on the hub | +| `IMPORTER_KEY` | the importer key | +| `IMPORTER_DATA` | its folder (default `./data`; `/data` in the image): its key pair and the IMVU accounts' passwords | + +``` +docker run -v importer-data:/data -e HUB_URL=https://api.t5de.dev -e CATALOG_ID=... -e IMPORTER_KEY=... \ + git.t5de.dev/t5de/t5de-importer:latest +``` + +Everything else is set on the console: pausing, how many requests a second it makes to IMVU, how many products it +imports at once, and the IMVU accounts it may use. Keep `IMPORTER_DATA`: a new key pair (a new install) means the +accounts' passwords must be entered again. + +## What it does + +- Says hello to the hub with its version and public key (RSA 3072, made on first start). The catalog's team seals + IMVU account passwords for that key in their browser; the hub never holds them readable, and drops its copy once + the importer has it. +- Polls its config every minute and claims jobs (each an IMVU product to import or re-check). +- For each job, finds the product's newest revision on IMVU's CDN (probing revision numbers after the last one + imported), downloads its CFL, swaps the placeholder textures for the originals, drops `_contents.json`, sets + `ProductRating` from IMVU's rating, checks the result by t5de-api's `pack` rules, and uploads it to the catalog + with a one-off import token; the catalog registers it with the hub. The parent product stays on IMVU. + +Not yet: signing in to IMVU with the accounts (needed for Access Pass products, which IMVU hides from the signed +out), and reporting what they see to the hub. + +## Development + +`go test ./...` (tests fake the hub, the catalog and IMVU's CDN; product files are made in code, never IMVU's). diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 0000000..247dd35 --- /dev/null +++ b/cliff.toml @@ -0,0 +1,45 @@ +# git-cliff (https://git-cliff.org), for the release workflow (.gitea/workflows/release.yml): the next version and +# CHANGELOG.md, from the conventional commits on main (one per pull request, titled by it) since the last vX.Y.Z tag. +# feat → minor, fix/perf/revert → patch, a breaking change (`!` or BREAKING CHANGE:) → minor while 0.x, major after. + +[changelog] +header = """ +# Changelog + +Written by release-bot's release pull requests, from the titles of the pull requests merged since the last release. +""" +body = """ +{% if commits | length > 0 %} +{% if version %}## {{ version | trim_start_matches(pat="v") }} ({{ timestamp | date(format="%Y-%m-%d") }}){% else %}## Unreleased{% endif %} +{% for group, commits in commits | group_by(attribute="group") %} +### {{ group | striptags | trim }} +{% for commit in commits %} +- {% if commit.scope %}**{{ commit.scope }}:** {% endif %}{% if commit.breaking %}**Breaking:** {% endif %}{{ commit.message | upper_first }}{% endfor %} +{% endfor %} +{% endif %} +""" +trim = true + +[git] +conventional_commits = true +filter_unconventional = true +protect_breaking_commits = true +commit_parsers = [ + { message = "^chore\\(release\\)", skip = true }, + { message = "^feat", group = "Features" }, + { message = "^fix", group = "Fixes" }, + { message = "^perf", group = "Performance" }, + { message = "^revert", group = "Reverts" }, + { message = "^refactor", group = "Refactoring" }, + { message = "^docs", group = "Documentation" }, + { message = "^(build|ci|chore|style|test)", skip = true }, +] +tag_pattern = "v[0-9]+\\.[0-9]+\\.[0-9]+" +sort_commits = "oldest" + +[bump] +features_always_bump_minor = true +breaking_always_bump_major = false +initial_tag = "v0.1.0" +# Matched against the commit's type: these alone don't make a release. +no_increment_regex = "^(chore|ci|docs|test|style|build|refactor)$" diff --git a/cmd/t5de-importer/main.go b/cmd/t5de-importer/main.go new file mode 100644 index 0000000..f839330 --- /dev/null +++ b/cmd/t5de-importer/main.go @@ -0,0 +1,117 @@ +// Command t5de-importer imports IMVU products into a T5DE catalog, with their creators' permission (t5de-hub's +// docs/imports.md). It runs beside the catalog; everything but what it needs to reach the hub is set on the hub's +// console (the catalog's Imports page). Configured by environment variables: +// +// HUB_URL the hub's API (required), e.g. https://api.t5de.dev +// CATALOG_ID the catalog's ID on the hub (required) +// IMPORTER_KEY the importer key, from turning imports on for the catalog (required) +// IMPORTER_DATA its folder (default ./data): its key pair and the IMVU accounts' passwords, sealed for it +// +// It logs to standard error and stops on SIGINT or SIGTERM. +package main + +import ( + "context" + "fmt" + "log" + "net/http" + "net/url" + "os" + "os/signal" + "path/filepath" + "strings" + "syscall" + "time" + + "git.t5de.dev/t5de/t5de-importer/internal/accounts" + "git.t5de.dev/t5de/t5de-importer/internal/buildinfo" + "git.t5de.dev/t5de/t5de-importer/internal/hub" + "git.t5de.dev/t5de/t5de-importer/internal/importer" + "git.t5de.dev/t5de/t5de-importer/internal/imvu" + "git.t5de.dev/t5de/t5de-importer/internal/keys" +) + +func main() { + if len(os.Args) > 1 && (os.Args[1] == "-version" || os.Args[1] == "--version") { + fmt.Println(buildinfo.Version) + return + } + logger := log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lmicroseconds) + if err := run(logger); err != nil { + logger.Printf("t5de-importer: %v", err) + os.Exit(1) + } +} + +func env(name, def string) string { + if v := strings.TrimSpace(os.Getenv(name)); v != "" { + return v + } + return def +} + +func run(logger *log.Logger) error { + hubURL := strings.TrimRight(env("HUB_URL", ""), "/") + id := env("CATALOG_ID", "") + key := env("IMPORTER_KEY", "") + data := env("IMPORTER_DATA", "data") + + var missing []string + for _, v := range [][2]string{{"HUB_URL", hubURL}, {"CATALOG_ID", id}, {"IMPORTER_KEY", key}} { + if v[1] == "" { + missing = append(missing, v[0]) + } + } + if len(missing) > 0 { + return fmt.Errorf("set %s", strings.Join(missing, ", ")) + } + if u, err := url.Parse(hubURL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return fmt.Errorf("HUB_URL %q isn't an http(s) URL", hubURL) + } + + if err := os.MkdirAll(data, 0o700); err != nil { + return err + } + k, made, err := keys.Load(data) + if err != nil { + return fmt.Errorf("the key pair: %w", err) + } + if made { + logger.Printf("made a new key pair in %s: IMVU account passwords sealed for an old one must be entered again", filepath.Join(data, keys.FileName)) + } + store, err := accounts.Open(data) + if err != nil { + return fmt.Errorf("the accounts: %w", err) + } + tmp := filepath.Join(data, "tmp") + if err := os.RemoveAll(tmp); err != nil { + return err + } + if err := os.MkdirAll(tmp, 0o700); err != nil { + return err + } + + userAgent := "t5de-importer/" + buildinfo.Version + " (+https://t5de.dev)" + client := &http.Client{Timeout: 2 * time.Minute} + im := &importer.Importer{ + Hub: hub.New(hubURL, id, key, userAgent, &http.Client{Timeout: 30 * time.Second}), + CDN: &imvu.CDN{URL: imvu.CDNURL, UserAgent: userAgent, HTTP: client, Limiter: imvu.NewLimiter(1)}, + Key: k, + Accounts: store, + Version: buildinfo.Version, + UserAgent: userAgent, + HTTP: client, + Tmp: tmp, + Logger: logger, + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + logger.Printf("t5de-importer %s for catalog %s at %s", buildinfo.Version, id, hubURL) + err = im.Run(ctx) + if ctx.Err() != nil { + logger.Printf("stopped") + return nil + } + return err +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2668565 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module git.t5de.dev/t5de/t5de-importer + +go 1.27.0 + +require ( + git.t5de.dev/t5de/t5de-api v0.0.0-20261108134602-86d3c1ba2317 + github.com/ulikunitz/xz v0.5.17 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a89bb66 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +git.t5de.dev/t5de/t5de-api v0.0.0-20261108134602-86d3c1ba2317 h1:3xOeYfJIpEB1pJgv52tX7YD08zwzT9rAlLhPrbnWMn4= +git.t5de.dev/t5de/t5de-api v0.0.0-20261108134602-86d3c1ba2317/go.mod h1:aA3xsKvL898E5RxHsgNgaSZ4VBMLDH7lwiSSsSuXfbQ= +github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4= +github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw= diff --git a/internal/accounts/accounts.go b/internal/accounts/accounts.go new file mode 100644 index 0000000..d48f0a7 --- /dev/null +++ b/internal/accounts/accounts.go @@ -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) +} diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go new file mode 100644 index 0000000..8b77edb --- /dev/null +++ b/internal/buildinfo/buildinfo.go @@ -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" diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go new file mode 100644 index 0000000..78f8a3d --- /dev/null +++ b/internal/catalog/catalog.go @@ -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 +} diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go new file mode 100644 index 0000000..f118686 --- /dev/null +++ b/internal/catalog/catalog_test.go @@ -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()) + } +} diff --git a/internal/convert/convert.go b/internal/convert/convert.go new file mode 100644 index 0000000..4ac710b --- /dev/null +++ b/internal/convert/convert.go @@ -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(`\s*([A-Za-z]*)\s*`) + templateOpen = regexp.MustCompile(`]*)?>`) +) + +// 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("" + want + "") + 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