Upload the account avatar to Blossom when it fills in for the picture #276
No files matched your search
@@ -15,6 +15,8 @@
|
||||
:'nostr-profile-editor-display-name-keys-value' => NostrManagerService::DISPLAY_NAME_KEYS.to_json,
|
||||
:'nostr-profile-editor-picture-value' => picture_value,
|
||||
:'nostr-profile-editor-banner-value' => banner_value,
|
||||
:'nostr-profile-editor-picture-fallback-value' => seed_picture_from_avatar?,
|
||||
:'nostr-profile-editor-store-url-value' => nostr_profile_images_settings_path,
|
||||
:'nostr-profile-editor-flush-url-value' => nostr_media_settings_path
|
||||
}
|
||||
}) do |f| %>
|
||||
|
||||
@@ -56,6 +56,10 @@ module Settings
|
||||
BlossomManagerService.server_url.present?
|
||||
end
|
||||
|
||||
def seed_picture_from_avatar?
|
||||
blossom_enabled? && safe_image_url(@profile["picture"]).nil? && account_avatar_url.present?
|
||||
end
|
||||
|
||||
def asset_descriptions
|
||||
{
|
||||
"picture" => "Square image, cropped to 400×400. JPEG, PNG, WebP or GIF up to " \
|
||||
|
||||
@@ -17,11 +17,14 @@ module Settings
|
||||
def create
|
||||
return render_error("Media server is not configured", :unprocessable_entity) if BlossomManagerService.server_url.blank?
|
||||
return render_error("Too many upload attempts. Please try again later.", :too_many_requests) if rate_limited?
|
||||
return render_error("File is too large", :payload_too_large) if request.content_length.to_i > MAX_CAP + REQUEST_SLACK
|
||||
|
||||
field = upload_field
|
||||
return render_error("Invalid upload", :unprocessable_entity) if field.nil?
|
||||
|
||||
return create_from_avatar(field) if params[:source] == "avatar"
|
||||
|
||||
return render_error("File is too large", :payload_too_large) if request.content_length.to_i > MAX_CAP + REQUEST_SLACK
|
||||
|
||||
file = params.require(:file)
|
||||
return render_error("Invalid upload", :unprocessable_entity) unless file.is_a?(ActionDispatch::Http::UploadedFile)
|
||||
return render_error("File is too large", :payload_too_large) if file.size > BlossomManagerService.max_upload_bytes(field)
|
||||
@@ -32,10 +35,7 @@ module Settings
|
||||
bytes = NostrManager::ProcessProfileImage.call(field: field, io: file, content_type: content_type)
|
||||
return render_error("Could not process image", :unprocessable_entity) if bytes.blank?
|
||||
|
||||
store(field, bytes)
|
||||
|
||||
sha256 = Digest::SHA256.hexdigest(bytes)
|
||||
render json: { sha256: sha256, previewUrl: nostr_profile_image_settings_path(field, v: sha256) }
|
||||
store_and_respond(field, bytes)
|
||||
rescue ActionController::ParameterMissing, ArgumentError, TypeError => e
|
||||
Rails.logger.warn("[nostr] Malformed profile image upload: #{e.class}: #{e.message}")
|
||||
render_error("Invalid upload", :unprocessable_entity)
|
||||
@@ -77,6 +77,29 @@ module Settings
|
||||
current_user.save
|
||||
end
|
||||
|
||||
def create_from_avatar(field)
|
||||
return render_error("Invalid upload", :unprocessable_entity) unless field == "picture"
|
||||
return render_error("No account avatar", :unprocessable_entity) unless current_user.avatar.attached?
|
||||
|
||||
blob = current_user.avatar.blob
|
||||
content_type = blob.content_type
|
||||
return render_error("Unsupported file type", :unprocessable_entity) unless ALLOWED_CONTENT_TYPES.include?(content_type)
|
||||
|
||||
bytes = NostrManager::ProcessProfileImage.call(
|
||||
field: field, io: StringIO.new(blob.download), content_type: content_type
|
||||
)
|
||||
return render_error("Could not process image", :unprocessable_entity) if bytes.blank?
|
||||
|
||||
store_and_respond(field, bytes)
|
||||
end
|
||||
|
||||
def store_and_respond(field, bytes)
|
||||
store(field, bytes)
|
||||
|
||||
sha256 = Digest::SHA256.hexdigest(bytes)
|
||||
render json: { sha256: sha256, previewUrl: nostr_profile_image_settings_path(field, v: sha256) }
|
||||
end
|
||||
|
||||
def rate_limited?
|
||||
key = "nostr_profile_image:#{current_user.id}"
|
||||
count = Rails.cache.read(key).to_i
|
||||
|
||||
@@ -17,6 +17,8 @@ export default class extends Controller {
|
||||
displayNameKeys: { type: Array, default: [ "display_name" ] },
|
||||
pictureValue: { type: String, default: "" },
|
||||
bannerValue: { type: String, default: "" },
|
||||
pictureFallback: { type: Boolean, default: false },
|
||||
storeUrl: String,
|
||||
flushUrl: String
|
||||
}
|
||||
|
||||
@@ -52,6 +54,7 @@ export default class extends Controller {
|
||||
this.setBusy(true)
|
||||
|
||||
try {
|
||||
await this.seedAccountAvatar()
|
||||
const content = this.content()
|
||||
await this.uploadPendingImages(content)
|
||||
|
||||
@@ -131,6 +134,26 @@ export default class extends Controller {
|
||||
})
|
||||
}
|
||||
|
||||
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 || {}) }
|
||||
|
||||
|
||||
+9
-7
@@ -69,7 +69,8 @@ The account settings page lets users publish their own Nostr data:
|
||||
preserved. The display name is read from the first present of `display_name`, `displayName`,
|
||||
`name` or `username`, and written to all of them for maximum client compatibility. When the
|
||||
published profile has no usable `picture` (missing, blank, or not an http(s) URL), the account
|
||||
avatar's public URL is used instead and written to the profile on save. The avatar and header
|
||||
avatar is uploaded to the configured Blossom server on save (cropped to 400×400, like a manually
|
||||
chosen avatar) and the returned URL is written to the profile. The avatar and header
|
||||
image can be replaced from an upload panel: the browser uploads the image to akkounts, which
|
||||
crops it server-side (avatar 400×400, header 1500×500; animated GIFs pass through) and stores it
|
||||
as a pending attachment that is shown as the preview. When the profile is saved, the browser
|
||||
@@ -104,12 +105,13 @@ Relevant settings (admin → Services → Nostr):
|
||||
* Metadata discovery is sequential (relays → profile → media server list) and can take a while on
|
||||
slow relays.
|
||||
* The account-avatar fallback for `picture` carves out an exception to preserving existing values:
|
||||
a `picture` that is missing, blank, or not an http(s) URL is replaced by the account avatar URL.
|
||||
* That fallback is one-shot and can go stale: the published URL embeds the avatar's content hash, so
|
||||
it starts 404ing once the account avatar is replaced, and — because the published `picture` is
|
||||
then no longer blank — the fallback does not re-trigger.
|
||||
* The fallback URL's host is taken from the request at save time, so saving from an alternate
|
||||
hostname publishes that hostname.
|
||||
a `picture` that is missing, blank, or not an http(s) URL is replaced by the account avatar,
|
||||
uploaded to Blossom on save.
|
||||
* The fallback only runs while no usable `picture` is published. Once the profile carries the
|
||||
Blossom URL, replacing the account avatar does not re-upload it; the `picture` has to be cleared
|
||||
for the fallback to run again.
|
||||
* A failed fallback upload fails the save (like any other image upload), so a profile is never
|
||||
published with a non-Blossom `picture`.
|
||||
* Avatar and header uploads are processed server-side (cover-cropped, EXIF/GPS stripped; animated
|
||||
GIFs passed through unchanged) and stored as one pending attachment per field. The avatar is
|
||||
limited to 1 MB and the header image to 2 MB; both accept JPEG/PNG/WebP/GIF, MIME-sniffed from
|
||||
|
||||
@@ -220,6 +220,7 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
let(:avatar_src) { %r{users/alice/avatars/#{img_hash}\.jpg} }
|
||||
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_blossom_server_url).and_return("https://blossom.example.com")
|
||||
ActiveStorage::Blob.create_and_upload!(
|
||||
io: File.open(fixture_path),
|
||||
filename: "#{img_hash}.jpg",
|
||||
@@ -252,9 +253,27 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-nostr-profile-editor-picture-value"]).to match(avatar_src)
|
||||
end
|
||||
|
||||
it "flags the account avatar for upload to Blossom" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-nostr-profile-editor-picture-fallback-value"]).to eq("true")
|
||||
expect(form["data-nostr-profile-editor-store-url-value"]).to eq("/settings/nostr_profile_images")
|
||||
end
|
||||
|
||||
it "does not flag the fallback when the profile already has a picture" do
|
||||
profile_event = { "content" => { "picture" => "https://example.com/p.png" }.to_json }
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: profile_event))
|
||||
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-nostr-profile-editor-picture-fallback-value"]).to eq("false")
|
||||
end
|
||||
end
|
||||
|
||||
context "without an account avatar" do
|
||||
before { allow(Setting).to receive(:nostr_blossom_server_url).and_return("https://blossom.example.com") }
|
||||
|
||||
it "renders the placeholder and seeds an empty picture value" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
@@ -267,6 +286,35 @@ RSpec.describe Settings::NostrEditProfileComponent, type: :component do
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-nostr-profile-editor-picture-value"]).to eq("")
|
||||
end
|
||||
|
||||
it "does not flag the account avatar fallback" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-nostr-profile-editor-picture-fallback-value"]).to eq("false")
|
||||
end
|
||||
end
|
||||
|
||||
context "with an account avatar but no Blossom server configured" do
|
||||
let(:user) { create(:user, cn: "alice") }
|
||||
let(:fixture_path) { Rails.root.join("spec/fixtures/files/taipei.jpg") }
|
||||
let(:img_hash) { Digest::SHA256.hexdigest(File.read(fixture_path)) }
|
||||
|
||||
before do
|
||||
allow(Setting).to receive(:nostr_blossom_server_url).and_return(nil)
|
||||
ActiveStorage::Blob.create_and_upload!(
|
||||
io: File.open(fixture_path),
|
||||
filename: "#{img_hash}.jpg",
|
||||
content_type: "image/jpeg"
|
||||
).tap { |blob| user.avatar.attach(blob) }
|
||||
end
|
||||
|
||||
it "does not flag the account avatar fallback" do
|
||||
rendered = render_inline(described_class.new(user: user, profile_event: nil))
|
||||
|
||||
form = rendered.css("form").first
|
||||
expect(form["data-nostr-profile-editor-picture-fallback-value"]).to eq("false")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -86,6 +86,55 @@ RSpec.describe "Settings::NostrProfileImages", type: :request do
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /settings/nostr_profile_images with source=avatar" do
|
||||
let(:avatar_blob) do
|
||||
ActiveStorage::Blob.create_and_upload!(
|
||||
io: File.open(fixture_path), filename: "avatar.jpg", content_type: "image/jpeg"
|
||||
)
|
||||
end
|
||||
|
||||
before { user.avatar.attach(avatar_blob) }
|
||||
|
||||
it "stores a cropped copy of the account avatar and returns the hash and preview url" do
|
||||
post nostr_profile_images_settings_path, params: { field: "picture", source: "avatar" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
body = JSON.parse(response.body)
|
||||
expect(body["previewUrl"]).to eq("/settings/nostr_profile_images/picture?v=#{body["sha256"]}")
|
||||
|
||||
user.reload
|
||||
expect(user.nostr_picture).to be_attached
|
||||
stored = user.nostr_picture.blob.download
|
||||
expect(body["sha256"]).to eq(Digest::SHA256.hexdigest(stored))
|
||||
expect(dimensions(stored)).to eq([400, 400])
|
||||
end
|
||||
|
||||
it "rejects when the account has no avatar" do
|
||||
user.avatar.purge
|
||||
|
||||
post nostr_profile_images_settings_path, params: { field: "picture", source: "avatar" }
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "rejects a non-picture field" do
|
||||
post nostr_profile_images_settings_path, params: { field: "banner", source: "avatar" }
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "rejects a non-image avatar" do
|
||||
user.avatar.attach(
|
||||
io: File.open(Rails.root.join("spec/fixtures/files/bitcoin.pdf")),
|
||||
filename: "avatar.pdf", content_type: "application/pdf"
|
||||
)
|
||||
|
||||
post nostr_profile_images_settings_path, params: { field: "picture", source: "avatar" }
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /settings/nostr_profile_images/:field" do
|
||||
it "serves the stored preview" do
|
||||
upload(field: "picture")
|
||||
|
||||
Reference in new issue
Block a user