nixamp 0.61.1 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/ai-label.d.ts +2 -1
  2. package/dist/ai-label.js +5 -3
  3. package/dist/label-routes.js +3 -3
  4. package/dist/license-routes.d.ts +17 -0
  5. package/dist/license-routes.js +241 -0
  6. package/dist/music-hub.d.ts +1 -0
  7. package/dist/music-hub.js +9 -6
  8. package/dist/music-license.d.ts +120 -0
  9. package/dist/music-license.js +266 -0
  10. package/dist/server.d.ts +3 -0
  11. package/dist/server.js +30 -0
  12. package/package.json +1 -1
  13. package/src/ai-label.ts +5 -4
  14. package/src/label-routes.ts +3 -3
  15. package/src/license-routes.ts +258 -0
  16. package/src/music-hub.ts +10 -7
  17. package/src/music-license.ts +349 -0
  18. package/src/server.ts +29 -0
  19. package/web/dist/assets/{ar-CYzjQKmG.js → ar-Eigh2EY7.js} +1 -1
  20. package/web/dist/assets/client-B_mfdrFh.js +1 -0
  21. package/web/dist/assets/{cs-DiSibpnb.js → cs-BiYj6suH.js} +1 -1
  22. package/web/dist/assets/{da-butHBZ3x.js → da-Bbv8v9LC.js} +1 -1
  23. package/web/dist/assets/{de-CmBXpW1X.js → de-Ct4J4O2-.js} +1 -1
  24. package/web/dist/assets/{es-CpqprbhX.js → es-C1QHkBcK.js} +1 -1
  25. package/web/dist/assets/{fi-B1hMfasn.js → fi-BL22uj7L.js} +1 -1
  26. package/web/dist/assets/{fr-Cjc6bkRE.js → fr-CbHGddiD.js} +1 -1
  27. package/web/dist/assets/{hi-DjEO-zwR.js → hi-CEnEoHJB.js} +1 -1
  28. package/web/dist/assets/{hu-BsR0uaL9.js → hu-V6N4YyNP.js} +1 -1
  29. package/web/dist/assets/{id-B9R43LCb.js → id-Dlur-A5Q.js} +1 -1
  30. package/web/dist/assets/{it-qzlsZzmL.js → it-CtiClrIo.js} +1 -1
  31. package/web/dist/assets/main-CFJDb9Yd.js +22 -0
  32. package/web/dist/assets/{music-CVLJhYTF.css → music-Dy7J3PeE.css} +1 -1
  33. package/web/dist/assets/music-gaYfGADg.js +1 -0
  34. package/web/dist/assets/{nl-CZUfUvgR.js → nl-Crjz8b-j.js} +1 -1
  35. package/web/dist/assets/{ru-BBAO-YaP.js → ru-CrwKGInd.js} +1 -1
  36. package/web/dist/assets/{sv-ySaoJU94.js → sv-DG2OJzJH.js} +1 -1
  37. package/web/dist/assets/{uk-FeqZ0VuT.js → uk-BteiNgtQ.js} +1 -1
  38. package/web/dist/assets/{vi-BKb_A-rW.js → vi-CSTApJSE.js} +1 -1
  39. package/web/dist/assets/{zh-DfWRilkD.js → zh-CTag10X-.js} +1 -1
  40. package/web/dist/index.html +2 -1
  41. package/web/dist/music.html +3 -2
  42. package/web/dist/sw.js +22 -21
  43. package/web/dist/assets/main-DACzAtIi.js +0 -22
  44. package/web/dist/assets/music-BTeZvJCU.js +0 -1
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Licences to use the AI label's music in somebody's own work: a game, an
3
+ * app, a video, a podcast. A download (music-store.ts) is for listening; a
4
+ * licence is permission to put the music in a project and publish it.
5
+ *
6
+ * Creator a song, $5 online videos, streams, podcasts, social posts, monetized or not
7
+ * Indie a song, $25 all of Creator, plus games, apps, sites, software and films,
8
+ * an album, $100 for a licensee under US$100,000 of revenue a year
9
+ * Commercial a song, $250 any use in the licensee's own products and ads, any size
10
+ * Catalog $29 a year Indie, for every artist the label releases, unlimited projects
11
+ *
12
+ * Every licence is worldwide, non-exclusive and for good (the catalogue pass:
13
+ * for every project published while it is active), and every use credits the
14
+ * artist with a link to their page. The terms are TERMS below (license-routes.ts
15
+ * serves them at /license/terms); each licence records the version it was sold
16
+ * under. Paid through nixamp.com's CoinPay business like the store.
17
+ */
18
+ import { randomBytes, randomUUID } from "node:crypto";
19
+ import { SupportError } from "./support.js";
20
+ /** In cents, by tier and what is licensed; a missing pair is not sold. */
21
+ export const LICENSE_PRICES = {
22
+ creator: { song: 500 },
23
+ indie: { song: 2500, album: 10000 },
24
+ commercial: { song: 25000 },
25
+ catalog: { catalog: 2900 },
26
+ };
27
+ export const TIER_NAMES = { creator: "Creator", indie: "Indie", commercial: "Commercial", catalog: "Catalog pass" };
28
+ /** What each tier lets a licensee do, in a line. */
29
+ export const TIER_USE = {
30
+ creator: "Online videos, livestreams, podcasts and social posts, monetized or not. Not games, apps, ads or broadcast.",
31
+ indie: "Everything in Creator, plus games, apps, websites, software and films, for a licensee earning under US$100,000 a year.",
32
+ commercial: "Any use in your own products, games, apps, films and advertising, broadcast included, at any size.",
33
+ catalog: "The Indie licence for every song by every artist the label releases, for any number of projects published while the pass is active.",
34
+ };
35
+ export const TERMS_VERSION = "1";
36
+ const YEAR_MS = 365 * 24 * 3600_000;
37
+ const EMAIL = /^[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[a-z]{2,24}$/i;
38
+ const CODE = /^NXL-[A-Z2-9]{4}-[A-Z2-9]{4}$/;
39
+ /** A licence code: unambiguous letters and digits, for reading out or typing in. */
40
+ function newCode() {
41
+ const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
42
+ const bytes = randomBytes(8);
43
+ const chars = [...bytes].map((one) => alphabet[one % alphabet.length]).join("");
44
+ return `NXL-${chars.slice(0, 4)}-${chars.slice(4)}`;
45
+ }
46
+ function clean(value, max) {
47
+ return typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max) : "";
48
+ }
49
+ function httpsUrl(value) {
50
+ const text = clean(value, 300);
51
+ if (!text)
52
+ return "";
53
+ try {
54
+ const url = new URL(text);
55
+ return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : "";
56
+ }
57
+ catch {
58
+ return "";
59
+ }
60
+ }
61
+ function row(one) {
62
+ const time = (value) => (value ? new Date(String(value)).getTime() : 0);
63
+ return {
64
+ id: String(one["id"]), code: String(one["code"]), token: String(one["token"]), email: String(one["email"]), userId: String(one["user_id"] ?? ""),
65
+ licensee: String(one["licensee"]), project: String(one["project"]), projectUrl: String(one["project_url"] ?? ""),
66
+ tier: String(one["tier"]), kind: String(one["kind"]), server: String(one["server"] ?? ""), artist: String(one["artist"] ?? ""),
67
+ album: String(one["album"] ?? ""), n: Number(one["n"] ?? 0), title: String(one["title"]), artistName: String(one["artist_name"]), creditUrl: String(one["credit_url"]),
68
+ amountCents: Number(one["amount_cents"]), coin: String(one["coin"]), paymentId: String(one["payment_id"] ?? ""),
69
+ status: one["status"] === "paid" ? "paid" : "pending", terms: String(one["terms"]), createdAt: time(one["created_at"]), paidAt: time(one["paid_at"]), expiresAt: time(one["expires_at"]),
70
+ };
71
+ }
72
+ export class MusicLicenses {
73
+ options;
74
+ schema = null;
75
+ constructor(options) {
76
+ this.options = options;
77
+ }
78
+ now() {
79
+ return this.options.now?.() ?? Date.now();
80
+ }
81
+ get holder() {
82
+ return this.options.holder ?? "Profullstack, Inc.";
83
+ }
84
+ ready() {
85
+ this.schema ??= (async () => {
86
+ await this.options.db.query(`CREATE TABLE IF NOT EXISTS music_licenses (
87
+ id TEXT PRIMARY KEY, code TEXT NOT NULL UNIQUE, token TEXT NOT NULL, email TEXT NOT NULL, user_id TEXT NOT NULL DEFAULT '',
88
+ licensee TEXT NOT NULL, project TEXT NOT NULL, project_url TEXT NOT NULL DEFAULT '',
89
+ tier TEXT NOT NULL, kind TEXT NOT NULL, server TEXT NOT NULL DEFAULT '', artist TEXT NOT NULL DEFAULT '', album TEXT NOT NULL DEFAULT '', n INTEGER NOT NULL DEFAULT 0,
90
+ title TEXT NOT NULL, artist_name TEXT NOT NULL, credit_url TEXT NOT NULL, amount_cents INTEGER NOT NULL, coin TEXT NOT NULL,
91
+ payment_id TEXT, status TEXT NOT NULL DEFAULT 'pending', terms TEXT NOT NULL,
92
+ created_at TIMESTAMPTZ NOT NULL, paid_at TIMESTAMPTZ, expires_at TIMESTAMPTZ)`);
93
+ await this.options.db.query("CREATE INDEX IF NOT EXISTS music_licenses_email ON music_licenses (lower(email))");
94
+ await this.options.db.query("CREATE INDEX IF NOT EXISTS music_licenses_user ON music_licenses (user_id)");
95
+ await this.options.db.query("CREATE INDEX IF NOT EXISTS music_licenses_payment ON music_licenses (payment_id)");
96
+ })().catch((error) => { this.schema = null; throw error; });
97
+ return this.schema;
98
+ }
99
+ /** What would be licensed and for how much; refused when the pair is not sold or the music is not there. */
100
+ async quote(input) {
101
+ const tier = String(input["tier"] ?? (input["kind"] === "catalog" ? "catalog" : "indie"));
102
+ const kind = (tier === "catalog" ? "catalog" : String(input["kind"] ?? ""));
103
+ const cents = LICENSE_PRICES[tier]?.[kind];
104
+ if (!cents)
105
+ throw new SupportError("That licence is not sold: Creator and Commercial are per song, Indie per song or album, the Catalog pass covers everything.", 400, "invalid_tier");
106
+ if (kind === "catalog") {
107
+ return { tier, kind, server: "", artist: "", album: "", n: 0, title: `Every artist released by ${this.holder}`, artistName: this.holder, creditUrl: `${this.options.site}/music`, amountCents: cents };
108
+ }
109
+ const item = await this.options.store.describe({ ...input, kind });
110
+ return {
111
+ tier, kind, server: item.server, artist: item.artist, album: item.album, n: item.n, title: item.title, artistName: item.artistName,
112
+ creditUrl: `${this.options.site}/music/artist/${this.options.serverId(item.server)}/${item.artist}`, amountCents: cents,
113
+ };
114
+ }
115
+ /** A licence waiting for its payment, and where to pay. */
116
+ async checkout(input, account) {
117
+ if (input["agree"] !== true)
118
+ throw new SupportError("Agree to the licence terms first.", 400, "terms_required");
119
+ const email = (clean(input["email"], 254) || account?.email || "").toLowerCase();
120
+ if (!EMAIL.test(email))
121
+ throw new SupportError("Give the email the licence should go to.", 400, "invalid_email");
122
+ const licensee = clean(input["licensee"], 120);
123
+ if (licensee.length < 2)
124
+ throw new SupportError("Say who the licence is for: your name or your company's.", 400, "licensee_required");
125
+ const project = clean(input["project"], 160);
126
+ if (project.length < 2)
127
+ throw new SupportError("Name the project the music goes in (the catalogue pass: your studio or channel).", 400, "project_required");
128
+ const quote = await this.quote(input);
129
+ await this.ready();
130
+ const id = randomUUID();
131
+ const token = randomUUID().replace(/-/g, "");
132
+ const code = newCode();
133
+ const checkout = await this.options.support.pay({
134
+ amountUsd: quote.amountCents / 100,
135
+ coin: input["coin"],
136
+ order: `license-${id}`,
137
+ description: `${TIER_NAMES[quote.tier]} licence: ${quote.title}${quote.kind === "catalog" ? ", one year" : ` by ${quote.artistName}`} for ${project}`,
138
+ metadata: { product: "music-license", license: id, tier: quote.tier, kind: quote.kind },
139
+ redirect: this.link(id, token),
140
+ });
141
+ await this.options.db.query(`INSERT INTO music_licenses (id, code, token, email, user_id, licensee, project, project_url, tier, kind, server, artist, album, n,
142
+ title, artist_name, credit_url, amount_cents, coin, payment_id, terms, created_at)
143
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22)`, [id, code, token, email, account?.id ?? "", licensee, project, httpsUrl(input["projectUrl"]), quote.tier, quote.kind, quote.server, quote.artist, quote.album, quote.n,
144
+ quote.title, quote.artistName, quote.creditUrl, quote.amountCents, String(input["coin"]).toUpperCase(), checkout.paymentId, TERMS_VERSION, new Date(this.now())]);
145
+ return { url: checkout.url, id, token, code };
146
+ }
147
+ /** The licensee's own page: the certificate once paid. */
148
+ link(id, token) {
149
+ return `${this.options.site}/licenses/${id}?t=${token}`;
150
+ }
151
+ /** Anybody's check of a licence by its code: a client asking whether a game's music is licensed. */
152
+ verifyUrl(code) {
153
+ return `${this.options.site}/license/${code}`;
154
+ }
155
+ async get(id, token) {
156
+ await this.ready();
157
+ const found = (await this.options.db.query("SELECT * FROM music_licenses WHERE id = $1 AND token = $2", [id, token])).rows[0];
158
+ if (!found)
159
+ return null;
160
+ const license = row(found);
161
+ if (license.status === "pending" && license.paymentId && (await this.options.support.isPaid(license.paymentId)) === true)
162
+ return (await this.paid(license.id)) ?? license;
163
+ return license;
164
+ }
165
+ /** A paid licence by its code, for the public check; a pending one is not anybody's business. */
166
+ async byCode(code) {
167
+ if (!CODE.test(code))
168
+ return null;
169
+ await this.ready();
170
+ const found = (await this.options.db.query("SELECT * FROM music_licenses WHERE code = $1 AND status = 'paid'", [code])).rows[0];
171
+ return found ? row(found) : null;
172
+ }
173
+ async owns(paymentId) {
174
+ await this.ready();
175
+ return (await this.options.db.query("SELECT 1 FROM music_licenses WHERE payment_id = $1", [paymentId])).rows.length > 0;
176
+ }
177
+ /** CoinPay's webhook for one of ours. */
178
+ async settle(paymentId) {
179
+ await this.ready();
180
+ const found = (await this.options.db.query("SELECT id, status FROM music_licenses WHERE payment_id = $1", [paymentId])).rows[0];
181
+ if (!found)
182
+ return { settled: false };
183
+ if (found["status"] === "paid")
184
+ return { settled: true, license: String(found["id"]) };
185
+ if ((await this.options.support.isPaid(paymentId)) !== true)
186
+ return { settled: false, license: String(found["id"]) };
187
+ await this.paid(String(found["id"]));
188
+ return { settled: true, license: String(found["id"]) };
189
+ }
190
+ async forAccount(account) {
191
+ await this.ready();
192
+ const rows = await this.options.db.query("SELECT * FROM music_licenses WHERE status = 'paid' AND (user_id = $1 OR lower(email) = lower($2)) ORDER BY paid_at DESC LIMIT 500", [account.id, account.email]);
193
+ return rows.rows.map(row);
194
+ }
195
+ /** Marks it paid once; the catalogue pass runs a year from then. The first to get here sends the certificate. */
196
+ async paid(id) {
197
+ const now = new Date(this.now());
198
+ const updated = (await this.options.db.query("UPDATE music_licenses SET status = 'paid', paid_at = $2, expires_at = CASE WHEN kind = 'catalog' THEN $3::timestamptz ELSE NULL END WHERE id = $1 AND status = 'pending' RETURNING *", [id, now, new Date(this.now() + YEAR_MS)])).rows[0];
199
+ if (!updated) {
200
+ const again = (await this.options.db.query("SELECT * FROM music_licenses WHERE id = $1", [id])).rows[0];
201
+ return again ? row(again) : null;
202
+ }
203
+ const license = row(updated);
204
+ await this.mail(license.email, `Your music licence ${license.code}: ${license.title}`, [
205
+ `Thank you. ${license.licensee} now holds a ${TIER_NAMES[license.tier]} licence (${license.code}) for "${license.title}"${license.kind === "catalog" ? "" : ` by ${license.artistName}`}, for ${license.project}.`,
206
+ `What it covers: ${TIER_USE[license.tier]}${license.expiresAt ? ` Projects published before ${new Date(license.expiresAt).toISOString().slice(0, 10)} stay licensed for good.` : ""}`,
207
+ `Credit the music where your project has credits or a description, with a link to the artist's page: ${creditLine(license)}`,
208
+ `Your certificate, to keep or print: ${this.link(license.id, license.token)}`,
209
+ `Anybody can check it (a store, a platform, a client): ${this.verifyUrl(license.code)}`,
210
+ `The terms (version ${license.terms}): ${this.options.site}/license/terms`,
211
+ ]);
212
+ return license;
213
+ }
214
+ /** What the licensee's page and the public check show. */
215
+ view(license, full) {
216
+ const now = this.now();
217
+ return {
218
+ code: license.code, licensee: license.licensee, project: license.project, projectUrl: license.projectUrl,
219
+ tier: license.tier, tierName: TIER_NAMES[license.tier], use: TIER_USE[license.tier], kind: license.kind,
220
+ title: license.title, artistName: license.artistName, creditUrl: license.creditUrl, credit: creditLine(license),
221
+ status: license.status, active: license.status === "paid" && (!license.expiresAt || license.expiresAt > now),
222
+ paidAt: license.paidAt, expiresAt: license.expiresAt, terms: license.terms, termsUrl: `${this.options.site}/license/terms`, verify: this.verifyUrl(license.code),
223
+ ...(full ? { id: license.id, email: license.email, amountUsd: license.amountCents / 100, coin: license.coin, paymentId: license.paymentId, link: this.link(license.id, license.token) } : {}),
224
+ };
225
+ }
226
+ async mail(to, subject, lines) {
227
+ if (!this.options.mail) {
228
+ this.options.log?.(` licences: no RESEND_API_KEY, so "${subject}" to ${to} was not sent`);
229
+ return;
230
+ }
231
+ try {
232
+ await (this.options.fetcher ?? fetch)("https://api.resend.com/emails", {
233
+ method: "POST",
234
+ signal: AbortSignal.timeout(15_000),
235
+ headers: { authorization: `Bearer ${this.options.mail.apiKey}`, "content-type": "application/json" },
236
+ body: JSON.stringify({ from: this.options.mail.from, to: [to], subject, text: `${lines.join("\n\n")}\n\nnixamp.com` }),
237
+ });
238
+ }
239
+ catch (error) {
240
+ this.options.log?.(` licences: mail to ${to} failed: ${error.message}`);
241
+ }
242
+ }
243
+ }
244
+ /** The credit a licence asks for, ready to paste. */
245
+ export function creditLine(license) {
246
+ return license.kind === "catalog"
247
+ ? `Music: "<song>" by <artist> (<the artist's nixamp page>), licensed from ${license.artistName} on nixamp (${license.code})`
248
+ : `Music: "${license.title}" by ${license.artistName} (${license.creditUrl}), licensed on nixamp (${license.code})`;
249
+ }
250
+ /** The licence terms, version TERMS_VERSION: plain words, shown at /license/terms and agreed to at checkout. */
251
+ export function licenseTerms(holder, site) {
252
+ return [
253
+ { heading: "Who", text: `These terms are between ${holder} ("we"), which releases the AI label's music on nixamp, and the person or company named on the licence ("you").` },
254
+ { heading: "What you may do", text: "Use the licensed recordings, and their lyrics, in your own project: put them in it, edit, cut, loop and mix them, and publish, sell and distribute the project with the music inside it, worldwide, for as long as the project exists. The licence is non-exclusive: others may license the same music." },
255
+ { heading: "Which uses", text: `Creator: ${TIER_USE.creator} Indie: ${TIER_USE.indie} Commercial: ${TIER_USE.commercial} A song or album licence is for the one project named on it; the Catalog pass covers any number of your projects.` },
256
+ { heading: "The Catalog pass", text: `${TIER_USE.catalog} It runs one year from payment. A project first published while it is active stays licensed for good; a project published after it ends needs a new pass or its own licence.` },
257
+ { heading: "Credit", text: "Credit the music where your project shows credits or a description (end credits, an about screen, a video description, show notes), with a link to the artist's page on nixamp. The certificate gives the line to use. If there is nowhere to credit, put it where people can find it, such as your project's website." },
258
+ { heading: "What you may not do", text: "Sell, give away or publish the music on its own or as music (a track, an album, a sample pack, a stock or production library), or let others take it out of your project to use separately. Register the music as yours, or claim it with a content ID system (YouTube Content ID and the like). Use it as a trademark, jingle or sound logo. Use it to train or evaluate AI models. Use it in anything unlawful, defamatory or hateful." },
259
+ { heading: "Transfer", text: "The licence is yours and is not transferable, except with the project it is in: if you sell the project, the licence goes with it." },
260
+ { heading: "AI and rights", text: `The music and lyrics are made with AI and released by ${holder}. In some countries, including the United States, works made by AI have limited or no copyright protection. This licence is our written permission and our promise not to claim against your licensed use; we do not promise that nobody else can use the same music.` },
261
+ { heading: "No warranty", text: "The music is licensed as it is, without warranty. Our total liability under a licence is what you paid for it." },
262
+ { heading: "Ending", text: "If you break these terms the licence ends for new uses; tell us and fix it within 30 days and it continues." },
263
+ { heading: "Proof", text: `Every licence has a code (NXL-XXXX-XXXX) and a public page at ${site}/license/<code> that says who holds it, for what, and whether it is active.` },
264
+ { heading: "Law", text: "California law governs these terms." },
265
+ ];
266
+ }
package/dist/server.d.ts CHANGED
@@ -27,6 +27,7 @@ import { Importer } from "./handoff.ts";
27
27
  import { AiLabel } from "./ai-label.ts";
28
28
  import { MusicStore } from "./music-store.ts";
29
29
  import { MusicHub } from "./music-hub.ts";
30
+ import { MusicLicenses } from "./music-license.ts";
30
31
  import { AiRadio } from "./ai-radio.ts";
31
32
  import { ListenerShares } from "./listener-shares.ts";
32
33
  import { Support, SupportSubscriptions } from "./support.ts";
@@ -834,6 +835,8 @@ export interface HandlerOptions {
834
835
  coinpayWebhookSecret?: string;
835
836
  /** The AI label's songs for sale, nixamp.com only (music-store.ts). */
836
837
  musicStore?: MusicStore;
838
+ /** Licences to use that music in games, apps and videos, nixamp.com only (music-license.ts). */
839
+ musicLicenses?: MusicLicenses;
837
840
  /** nixamp.com/music: every server's label in one app (music-hub.ts). */
838
841
  music?: {
839
842
  hub: MusicHub;
package/dist/server.js CHANGED
@@ -68,6 +68,8 @@ import { handleMusicRoutes, isMusicPath, MusicHub, musicPageFor, serverId } from
68
68
  import { fileLedger, pgLedger, VeoBudgetError, VeoStudio } from "./veo-studio.js";
69
69
  import { KnownServers } from "./known-servers.js";
70
70
  import { handleStoreRoutes, isStorePath } from "./store-routes.js";
71
+ import { MusicLicenses } from "./music-license.js";
72
+ import { handleLicenseRoutes, isLicensePath } from "./license-routes.js";
71
73
  import { AiRadio } from "./ai-radio.js";
72
74
  import { ListenerShares } from "./listener-shares.js";
73
75
  import { HolderStore, TagReader, factsFor } from "./track-facts.js";
@@ -2179,6 +2181,10 @@ export function createHandler(engine, options) {
2179
2181
  json(response, 200, await options.musicStore.settle(event.paymentId));
2180
2182
  return;
2181
2183
  }
2184
+ if (options.musicLicenses && await options.musicLicenses.owns(event.paymentId)) {
2185
+ json(response, 200, await options.musicLicenses.settle(event.paymentId));
2186
+ return;
2187
+ }
2182
2188
  }
2183
2189
  catch (error) {
2184
2190
  console.error(`nixamp: CoinPay webhook for ${event.paymentId} (music) could not settle: ${error instanceof Error ? error.message : String(error)}`);
@@ -2321,6 +2327,7 @@ export function createHandler(engine, options) {
2321
2327
  !(isPublicLabelPath(path) && Boolean(options.stations?.label)) &&
2322
2328
  // The music store: its pages, checkout, receipts and grants (nixamp.com).
2323
2329
  !(isStorePath(path) && Boolean(options.musicStore)) &&
2330
+ !(isLicensePath(path) && Boolean(options.musicLicenses)) &&
2324
2331
  // nixamp.com/music: the app and its catalogue, for anybody.
2325
2332
  !(isMusicPath(path) && Boolean(options.music)) &&
2326
2333
  !(/^\/radio\/(artist|album)\//.test(path) && Boolean(options.music)) &&
@@ -2918,6 +2925,18 @@ export function createHandler(engine, options) {
2918
2925
  }))
2919
2926
  return;
2920
2927
  }
2928
+ if (options.musicLicenses && isLicensePath(path)) {
2929
+ const accounts = options.accounts;
2930
+ if (await handleLicenseRoutes(request, response, path, url, {
2931
+ licenses: options.musicLicenses,
2932
+ account: async () => (accounts ? await accounts.whoIs(tokenFrom(request.headers)) : null),
2933
+ json,
2934
+ readBody,
2935
+ serverId,
2936
+ site: (process.env["NIXAMP_SITE"] || "https://nixamp.com").replace(/\/+$/, ""),
2937
+ }))
2938
+ return;
2939
+ }
2921
2940
  if (options.stations?.label && (isPublicLabelPath(path) || path === "/api/v1/stations/label" || path.startsWith("/api/v1/stations/label/"))) {
2922
2941
  const control = isPublicLabelPath(path) ? { allowed: false } : await controlOf();
2923
2942
  if (await handleLabelRoutes(request, response, path, {
@@ -7514,6 +7533,16 @@ export async function serve(argv, version = "0.1.0") {
7514
7533
  ...(musicHub ? { resolveServer: (id) => musicHub.resolve(id) } : {}),
7515
7534
  log: (line) => console.log(line),
7516
7535
  }) : undefined;
7536
+ // Licences to use that music in games, apps and videos (music-license.ts), paid the same way.
7537
+ const musicLicenses = musicStore && supportPayments && pool ? new MusicLicenses({
7538
+ db: pool,
7539
+ support: supportPayments,
7540
+ store: musicStore,
7541
+ mail: process.env["RESEND_API_KEY"] ? { apiKey: process.env["RESEND_API_KEY"], from: process.env["NIXAMP_MAIL_FROM"] ?? "nixamp <notifications@nixamp.com>" } : null,
7542
+ site: nixampSite,
7543
+ serverId,
7544
+ log: (line) => console.log(line),
7545
+ }) : undefined;
7517
7546
  /**
7518
7547
  * A server says an album (or song) of its label landed: its artist's
7519
7548
  * followers are told. Only the account that owns a listed server may say
@@ -8151,6 +8180,7 @@ export async function serve(argv, version = "0.1.0") {
8151
8180
  ...(supportPayments ? { support: supportPayments } : {}),
8152
8181
  ...(supportMonthly ? { supportSubscriptions: supportMonthly } : {}),
8153
8182
  ...(musicStore ? { musicStore } : {}),
8183
+ ...(musicLicenses ? { musicLicenses } : {}),
8154
8184
  ...(musicHub ? { music: { hub: musicHub, released: musicReleased, veo: musicVeo } } : {}),
8155
8185
  ...(process.env["COINPAY_WEBHOOK_SECRET"] ? { coinpayWebhookSecret: process.env["COINPAY_WEBHOOK_SECRET"] } : {}),
8156
8186
  ...(sharedTranslations ? { sharedTranslations } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nixamp",
3
- "version": "0.61.1",
3
+ "version": "0.62.0",
4
4
  "description": "It really whips the terminal's ass. A Winamp-shaped audio player for your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/ai-label.ts CHANGED
@@ -1662,7 +1662,7 @@ export class AiLabel {
1662
1662
  .filter((album) => album.songs.some((song) => song.file))
1663
1663
  .map((album) => ({
1664
1664
  key: album.key, title: album.title, year: album.year, concept: album.concept, cover: Boolean(album.cover), complete: album.doneAt > 0,
1665
- songs: album.songs.filter((song) => song.file).map((song) => ({ n: song.n, title: song.title, seconds: song.seconds, lyrics: song.lyrics })),
1665
+ songs: album.songs.filter((song) => song.file).map((song) => ({ n: song.n, title: song.title, seconds: song.seconds, lyrics: song.lyrics, ...(song.video ? { video: true } : {}) })),
1666
1666
  }))
1667
1667
  .reverse(),
1668
1668
  }))
@@ -1671,14 +1671,15 @@ export class AiLabel {
1671
1671
  return { holder: this.settings.holder, genres };
1672
1672
  }
1673
1673
 
1674
- /** A released file anybody may fetch: a song, its words, or its album's cover. */
1674
+ /** A released file anybody may fetch: its words, its music video, or its album's cover. */
1675
1675
  publicFile(artistKey: string, albumKey: string, what: string): { path: string; type: string } | null {
1676
1676
  const album = this.artists.get(artistKey)?.albums.find((one) => one.key === albumKey);
1677
1677
  if (!album) return null;
1678
1678
  if (what === "cover.jpg") return album.cover ? { path: album.cover, type: "image/jpeg" } : null;
1679
- const match = /^(\d{1,3})\.(mp3|txt)$/.exec(what);
1679
+ const match = /^(\d{1,3})\.(mp3|txt|mp4)$/.exec(what);
1680
1680
  const song = match ? album.songs.find((one) => one.n === Number(match[1]) && one.file) : undefined;
1681
1681
  if (!song) return null;
1682
+ if (match![2] === "mp4") return song.video ? { path: song.video, type: "video/mp4" } : null;
1682
1683
  return match![2] === "mp3" ? { path: song.file, type: "audio/mpeg" } : { path: song.lyricsFile, type: "text/plain; charset=utf-8" };
1683
1684
  }
1684
1685
 
@@ -1830,5 +1831,5 @@ export interface PublicArtist {
1830
1831
  bio: string;
1831
1832
  /** The people (profile pages at /api/v1/label/<artist>/members/<slug>.md, portraits .jpg). */
1832
1833
  members: Array<{ slug: string; name: string; role: string; bio: string }>;
1833
- albums: Array<{ key: string; title: string; year: number; concept: string; cover: boolean; complete: boolean; songs: Array<{ n: number; title: string; seconds: number; lyrics: string }> }>;
1834
+ albums: Array<{ key: string; title: string; year: number; concept: string; cover: boolean; complete: boolean; songs: Array<{ n: number; title: string; seconds: number; lyrics: string; video?: boolean }> }>;
1834
1835
  }
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Public, no key: `/label` (the catalogue as a page: every artist, album and
5
5
  * song, playable, with its words), `/api/v1/label` (the same as JSON) and
6
- * `/api/v1/label/<artist>/<album>/<n>.mp3|<n>.txt|cover.jpg` (the released
7
- * files themselves). The owner's are under /api/v1/stations/label.
6
+ * `/api/v1/label/<artist>/<album>/<n>.mp3|<n>.txt|<n>.mp4|cover.jpg` (the released
7
+ * files themselves; a music video is free to watch, like a promo). The owner's are under /api/v1/stations/label.
8
8
  */
9
9
  import { createHash } from "node:crypto";
10
10
  import { createReadStream, statSync } from "node:fs";
@@ -19,7 +19,7 @@ import { adCsp, withPageAd, type GuideAds } from "./station-guide.ts";
19
19
  // Listening is free on the live stations (with their breaks); the songs as
20
20
  // files are sold, so only the words and the cover are public here, and an
21
21
  // MP3 or a zip needs a grant from nixamp.com's store (music-store.ts).
22
- const FILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/([a-f0-9]{8})\/(\d{1,3}\.(?:txt|mp3)|cover\.jpg)$/;
22
+ const FILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/([a-f0-9]{8})\/(\d{1,3}\.(?:txt|mp3|mp4)|cover\.jpg)$/;
23
23
 
24
24
  /** An artist's OpenProfile pages and portraits: artist.md, members/<slug>.md, members/<slug>.jpg. */
25
25
  const PROFILE = /^\/api\/v1\/label\/([a-f0-9]{10})\/(artist\.md|members\/[a-z0-9-]{1,40}\.(?:md|jpg))$/;