Files
akkounts/app/javascript/controllers/nostr_profile_editor_controller.js
raucao 3e3d52ad8b
CI / Test (pull_request) Successful in 1m19s
Release Drafter / Update release notes draft (pull_request) Successful in 2s
Upload the account avatar to Blossom when it fills in for the picture
When a profile has no usable picture, the account avatar is now cropped and uploaded to the configured Blossom server on save, and the returned URL is written to the profile, instead of publishing the account's own avatar URL. A failed upload fails the save.
2026-11-28 21:23:45 +04:00

219 lines
6.5 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
import { signAndPublish } from "lib/nostr_publish"
import { canSign, signEvent } from "lib/nostr_signer"
import { csrfToken } from "lib/csrf"
const PROFILE_KIND = 0
const AUTH_KIND = 24242
const TOKEN_TTL = 5 * 60
const ADDRESS_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
const URL_PATTERN = /^https?:\/\/\S+$/i
export default class extends Controller {
static targets = [ "error", "submit", "picturePreview", "picturePlaceholder", "bannerPreview" ]
static values = {
profile: { type: Object, default: {} },
handle: String,
displayNameKeys: { type: Array, default: [ "display_name" ] },
pictureValue: { type: String, default: "" },
bannerValue: { type: String, default: "" },
pictureFallback: { type: Boolean, default: false },
storeUrl: String,
flushUrl: String
}
connect () {
this.pending = {}
}
async save (event) {
event.preventDefault()
this.clearError()
const nip05 = this.field("nip05_address")
const lud16 = this.field("lud16_address")
const website = this.field("website")
if (nip05 && !ADDRESS_PATTERN.test(nip05)) {
this.showError("Please enter a valid NIP-05 address, e.g. name@example.com.")
return
}
if (lud16 && !ADDRESS_PATTERN.test(lud16)) {
this.showError("Please enter a valid Lightning address, e.g. name@example.com.")
return
}
if (website && !URL_PATTERN.test(website)) {
this.showError("Please enter a valid website URL, e.g. https://example.com.")
return
}
if (!canSign()) {
this.showError("No Nostr signer is available.")
return
}
this.setBusy(true)
try {
await this.seedAccountAvatar()
const content = this.content()
await this.uploadPendingImages(content)
const signedEvent = await signAndPublish({
kind: PROFILE_KIND,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: JSON.stringify(content)
})
this.pending = {}
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
bubbles: true,
detail: { kind: PROFILE_KIND, eventId: signedEvent.id }
}))
} catch (error) {
this.showError(error.message)
} finally {
this.setBusy(false)
}
}
setPending (field, sha256, previewUrl) {
this.pending[field] = { sha256, previewUrl }
this.showPreview(field, previewUrl)
}
showPreview (field, url) {
if (!url) return
if (field === "picture") {
if (this.hasPicturePreviewTarget) {
this.picturePreviewTarget.src = url
this.picturePreviewTarget.classList.remove("hidden")
}
if (this.hasPicturePlaceholderTarget) this.picturePlaceholderTarget.classList.add("hidden")
} else if (field === "banner") {
if (this.hasBannerPreviewTarget) {
this.bannerPreviewTarget.style.backgroundImage = `url('${url}')`
}
}
}
async uploadPendingImages (content) {
const fields = Object.keys(this.pending)
if (fields.length === 0) return
const now = Math.floor(Date.now() / 1000)
const signedEvent = await signEvent({
kind: AUTH_KIND,
created_at: now,
tags: [
[ "t", "upload" ],
...fields.map((field) => [ "x", this.pending[field].sha256 ]),
[ "expiration", String(now + TOKEN_TTL) ]
],
content: "Upload profile images"
})
const response = await fetch(this.flushUrlValue, {
method: "POST",
credentials: "include",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken()
},
body: JSON.stringify({ signed_event: signedEvent })
})
const data = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(data.error || `Upload failed (HTTP ${response.status})`)
const uploads = data.uploads || []
const uploaded = new Set(uploads.map((upload) => upload.field))
uploads.forEach(({ field, url }) => { content[field] = url })
fields.forEach((field) => {
if (!uploaded.has(field)) throw new Error("Could not upload the image. Please try again.")
})
}
async seedAccountAvatar () {
if (!this.pictureFallbackValue || !this.hasStoreUrlValue || !this.storeUrlValue) return
if (this.pending.picture) return
const body = new FormData()
body.append("field", "picture")
body.append("source", "avatar")
const response = await fetch(this.storeUrlValue, {
method: "POST",
credentials: "include",
headers: { "Accept": "application/json", "X-CSRF-Token": csrfToken() },
body
})
const data = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(data.error || `Upload failed (HTTP ${response.status})`)
this.setPending("picture", data.sha256, data.previewUrl)
}
content () {
const content = { ...(this.profileValue || {}) }
const displayName = this.field("display_name")
this.displayNameKeysValue.forEach((key) => this.assign(content, key, displayName))
this.assign(content, "nip05", this.field("nip05_address"))
this.assign(content, "lud16", this.field("lud16_address"))
this.assign(content, "about", this.field("about"))
this.assign(content, "website", this.field("website"))
this.assignIfPresent(content, "picture", this.pictureValue)
this.assignIfPresent(content, "banner", this.bannerValue)
if (!content.name && this.handleValue) {
content.name = this.handleValue
}
return content
}
assign (content, key, value) {
if (value) {
content[key] = value
} else {
delete content[key]
}
}
assignIfPresent (content, key, value) {
if (value) content[key] = value
}
field (name) {
const input = this.element.querySelector(`[name='user[${name}]']`)
return input ? input.value.trim() : ""
}
setBusy (busy) {
if (!this.hasSubmitTarget) return
if (busy) {
this.submitTarget.dataset.originalValue = this.submitTarget.value
this.submitTarget.disabled = true
this.submitTarget.value = "Saving…"
} else {
this.submitTarget.disabled = false
this.submitTarget.value = this.submitTarget.dataset.originalValue || this.submitTarget.value
}
}
showError (message) {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = message
this.errorTarget.classList.remove("hidden")
}
clearError () {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = ""
this.errorTarget.classList.add("hidden")
}
}