WIP Upload multiple photos
This commit is contained in:
164
app/components/place-photo-item.gjs
Normal file
164
app/components/place-photo-item.gjs
Normal file
@@ -0,0 +1,164 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
import { inject as service } from '@ember/service';
|
||||
import { task } from 'ember-concurrency';
|
||||
import { EventFactory } from 'applesauce-core';
|
||||
import Icon from '#components/icon';
|
||||
import { on } from '@ember/modifier';
|
||||
import { fn } from '@ember/helper';
|
||||
|
||||
const DEFAULT_BLOSSOM_SERVER = 'https://blossom.nostr.build';
|
||||
|
||||
function bufferToHex(buffer) {
|
||||
return Array.from(new Uint8Array(buffer))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
export default class PlacePhotoItem extends Component {
|
||||
@service nostrAuth;
|
||||
@service nostrData;
|
||||
|
||||
@tracked thumbnailUrl = '';
|
||||
@tracked error = '';
|
||||
@tracked isUploaded = false;
|
||||
|
||||
get blossomServer() {
|
||||
return this.nostrData.blossomServers[0] || DEFAULT_BLOSSOM_SERVER;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
if (this.args.file) {
|
||||
this.thumbnailUrl = URL.createObjectURL(this.args.file);
|
||||
this.uploadTask.perform(this.args.file);
|
||||
}
|
||||
}
|
||||
|
||||
willDestroy() {
|
||||
super.willDestroy(...arguments);
|
||||
if (this.thumbnailUrl) {
|
||||
URL.revokeObjectURL(this.thumbnailUrl);
|
||||
}
|
||||
}
|
||||
|
||||
uploadTask = task(async (file) => {
|
||||
this.error = '';
|
||||
try {
|
||||
if (!this.nostrAuth.isConnected) throw new Error('Not connected');
|
||||
|
||||
const dim = await new Promise((resolve) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(`${img.width}x${img.height}`);
|
||||
img.onerror = () => resolve('');
|
||||
img.src = this.thumbnailUrl;
|
||||
});
|
||||
|
||||
const buffer = await file.arrayBuffer();
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
|
||||
const payloadHash = bufferToHex(hashBuffer);
|
||||
|
||||
let serverUrl = this.blossomServer;
|
||||
if (serverUrl.endsWith('/')) {
|
||||
serverUrl = serverUrl.slice(0, -1);
|
||||
}
|
||||
const uploadUrl = `${serverUrl}/upload`;
|
||||
|
||||
const factory = new EventFactory({ signer: this.nostrAuth.signer });
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const serverHostname = new URL(serverUrl).hostname;
|
||||
|
||||
const authTemplate = {
|
||||
kind: 24242,
|
||||
created_at: now,
|
||||
content: 'Upload photo for place',
|
||||
tags: [
|
||||
['t', 'upload'],
|
||||
['x', payloadHash],
|
||||
['expiration', String(now + 3600)],
|
||||
['server', serverHostname],
|
||||
],
|
||||
};
|
||||
|
||||
const authEvent = await factory.sign(authTemplate);
|
||||
const base64 = btoa(JSON.stringify(authEvent));
|
||||
const base64url = base64
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
const authHeader = `Nostr ${base64url}`;
|
||||
|
||||
// eslint-disable-next-line warp-drive/no-external-request-patterns
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
'X-SHA-256': payloadHash,
|
||||
},
|
||||
body: file,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(`Upload failed (${response.status}): ${text}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
this.isUploaded = true;
|
||||
|
||||
if (this.args.onSuccess) {
|
||||
this.args.onSuccess({
|
||||
file,
|
||||
url: result.url,
|
||||
type: file.type,
|
||||
dim,
|
||||
hash: payloadHash,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
this.error = e.message;
|
||||
}
|
||||
});
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="photo-item
|
||||
{{if this.uploadTask.isRunning 'is-uploading'}}
|
||||
{{if this.error 'has-error'}}"
|
||||
>
|
||||
<img src={{this.thumbnailUrl}} alt="thumbnail" class="photo-item-img" />
|
||||
|
||||
{{#if this.uploadTask.isRunning}}
|
||||
<div class="photo-item-overlay">
|
||||
<Icon
|
||||
@name="loading-ring"
|
||||
@size={{24}}
|
||||
@color="white"
|
||||
class="spin-animation"
|
||||
/>
|
||||
</div>
|
||||
{{/if}}
|
||||
|
||||
{{#if this.error}}
|
||||
<div class="photo-item-overlay error-overlay" title={{this.error}}>
|
||||
<Icon @name="alert-circle" @size={{24}} @color="white" />
|
||||
</div>
|
||||
{{/if}}
|
||||
|
||||
{{#if this.isUploaded}}
|
||||
<div class="photo-item-overlay success-overlay">
|
||||
<Icon @name="check" @size={{24}} @color="white" />
|
||||
</div>
|
||||
{{/if}}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn-remove-photo"
|
||||
title="Remove photo"
|
||||
{{on "click" (fn @onRemove @file)}}
|
||||
>
|
||||
<Icon @name="x" @size={{16}} @color="white" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
}
|
||||
@@ -5,26 +5,20 @@ import { inject as service } from '@ember/service';
|
||||
import { on } from '@ember/modifier';
|
||||
import { EventFactory } from 'applesauce-core';
|
||||
import Geohash from 'latlon-geohash';
|
||||
|
||||
const DEFAULT_BLOSSOM_SERVER = 'https://blossom.nostr.build';
|
||||
|
||||
function bufferToHex(buffer) {
|
||||
return Array.from(new Uint8Array(buffer))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
import PlacePhotoItem from './place-photo-item';
|
||||
import Icon from '#components/icon';
|
||||
import { or, not } from 'ember-truth-helpers';
|
||||
|
||||
export default class PlacePhotoUpload extends Component {
|
||||
@service nostrAuth;
|
||||
@service nostrData;
|
||||
@service nostrRelay;
|
||||
|
||||
@tracked photoUrl = '';
|
||||
@tracked photoType = 'image/jpeg';
|
||||
@tracked photoDim = '';
|
||||
@tracked files = [];
|
||||
@tracked uploadedPhotos = [];
|
||||
@tracked status = '';
|
||||
@tracked error = '';
|
||||
@tracked isUploading = false;
|
||||
@tracked isPublishing = false;
|
||||
@tracked isDragging = false;
|
||||
|
||||
get place() {
|
||||
return this.args.place || {};
|
||||
@@ -34,106 +28,56 @@ export default class PlacePhotoUpload extends Component {
|
||||
return this.place.title || 'this place';
|
||||
}
|
||||
|
||||
get blossomServer() {
|
||||
return this.nostrData.blossomServers[0] || DEFAULT_BLOSSOM_SERVER;
|
||||
get allUploaded() {
|
||||
return (
|
||||
this.files.length > 0 && this.files.length === this.uploadedPhotos.length
|
||||
);
|
||||
}
|
||||
|
||||
@action
|
||||
async handleFileSelected(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
handleFileSelect(event) {
|
||||
this.addFiles(event.target.files);
|
||||
event.target.value = ''; // Reset input
|
||||
}
|
||||
|
||||
this.error = '';
|
||||
this.status = 'Preparing upload...';
|
||||
this.isUploading = true;
|
||||
this.photoType = file.type;
|
||||
@action
|
||||
handleDragOver(event) {
|
||||
event.preventDefault();
|
||||
this.isDragging = true;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!this.nostrAuth.isConnected) {
|
||||
throw new Error('You must connect Nostr first.');
|
||||
}
|
||||
@action
|
||||
handleDragLeave(event) {
|
||||
event.preventDefault();
|
||||
this.isDragging = false;
|
||||
}
|
||||
|
||||
// 1. Get image dimensions
|
||||
const dim = await new Promise((resolve) => {
|
||||
const url = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
resolve(`${img.width}x${img.height}`);
|
||||
};
|
||||
img.onerror = () => resolve('');
|
||||
img.src = url;
|
||||
});
|
||||
this.photoDim = dim;
|
||||
@action
|
||||
handleDrop(event) {
|
||||
event.preventDefault();
|
||||
this.isDragging = false;
|
||||
this.addFiles(event.dataTransfer.files);
|
||||
}
|
||||
|
||||
// 2. Read file & compute hash
|
||||
this.status = 'Computing hash...';
|
||||
const buffer = await file.arrayBuffer();
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
|
||||
const payloadHash = bufferToHex(hashBuffer);
|
||||
addFiles(fileList) {
|
||||
if (!fileList) return;
|
||||
const newFiles = Array.from(fileList).filter((f) =>
|
||||
f.type.startsWith('image/')
|
||||
);
|
||||
this.files = [...this.files, ...newFiles];
|
||||
}
|
||||
|
||||
// 3. Create BUD-11 Auth Event
|
||||
this.status = 'Signing auth event...';
|
||||
let serverUrl = this.blossomServer;
|
||||
if (serverUrl.endsWith('/')) {
|
||||
serverUrl = serverUrl.slice(0, -1);
|
||||
}
|
||||
const uploadUrl = `${serverUrl}/upload`;
|
||||
@action
|
||||
handleUploadSuccess(photoData) {
|
||||
this.uploadedPhotos = [...this.uploadedPhotos, photoData];
|
||||
}
|
||||
|
||||
const factory = new EventFactory({ signer: this.nostrAuth.signer });
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const serverHostname = new URL(serverUrl).hostname;
|
||||
|
||||
const authTemplate = {
|
||||
kind: 24242,
|
||||
created_at: now,
|
||||
content: 'Upload photo for place',
|
||||
tags: [
|
||||
['t', 'upload'],
|
||||
['x', payloadHash],
|
||||
['expiration', String(now + 3600)],
|
||||
['server', serverHostname],
|
||||
],
|
||||
};
|
||||
|
||||
const authEvent = await factory.sign(authTemplate);
|
||||
const base64 = btoa(JSON.stringify(authEvent));
|
||||
const base64url = base64
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
const authHeader = `Nostr ${base64url}`;
|
||||
|
||||
// 4. Upload to Blossom
|
||||
this.status = `Uploading to ${serverUrl}...`;
|
||||
// eslint-disable-next-line warp-drive/no-external-request-patterns
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: authHeader,
|
||||
'X-SHA-256': payloadHash,
|
||||
},
|
||||
body: file,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(`Upload failed (${response.status}): ${text}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
this.photoUrl = result.url;
|
||||
this.status = 'Photo uploaded! Ready to publish.';
|
||||
} catch (e) {
|
||||
this.error = e.message;
|
||||
this.status = '';
|
||||
} finally {
|
||||
this.isUploading = false;
|
||||
if (event && event.target) {
|
||||
event.target.value = '';
|
||||
}
|
||||
}
|
||||
@action
|
||||
removeFile(fileToRemove) {
|
||||
this.files = this.files.filter((f) => f !== fileToRemove);
|
||||
this.uploadedPhotos = this.uploadedPhotos.filter(
|
||||
(p) => p.file !== fileToRemove
|
||||
);
|
||||
}
|
||||
|
||||
@action
|
||||
@@ -143,8 +87,8 @@ export default class PlacePhotoUpload extends Component {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.photoUrl) {
|
||||
this.error = 'Please upload a photo.';
|
||||
if (!this.allUploaded) {
|
||||
this.error = 'Please wait for all photos to finish uploading.';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -158,6 +102,7 @@ export default class PlacePhotoUpload extends Component {
|
||||
|
||||
this.status = 'Publishing event...';
|
||||
this.error = '';
|
||||
this.isPublishing = true;
|
||||
|
||||
try {
|
||||
const factory = new EventFactory({ signer: this.nostrAuth.signer });
|
||||
@@ -171,19 +116,21 @@ export default class PlacePhotoUpload extends Component {
|
||||
tags.push(['g', Geohash.encode(lat, lon, 9)]);
|
||||
}
|
||||
|
||||
const imeta = [
|
||||
'imeta',
|
||||
`url ${this.photoUrl}`,
|
||||
`m ${this.photoType}`,
|
||||
'alt A photo of a place',
|
||||
];
|
||||
for (const photo of this.uploadedPhotos) {
|
||||
const imeta = [
|
||||
'imeta',
|
||||
`url ${photo.url}`,
|
||||
`m ${photo.type}`,
|
||||
'alt A photo of a place',
|
||||
];
|
||||
|
||||
if (this.photoDim) {
|
||||
imeta.splice(3, 0, `dim ${this.photoDim}`);
|
||||
if (photo.dim) {
|
||||
imeta.splice(3, 0, `dim ${photo.dim}`);
|
||||
}
|
||||
|
||||
tags.push(imeta);
|
||||
}
|
||||
|
||||
tags.push(imeta);
|
||||
|
||||
// NIP-XX draft Place Photo event
|
||||
const template = {
|
||||
kind: 360,
|
||||
@@ -199,16 +146,21 @@ export default class PlacePhotoUpload extends Component {
|
||||
await this.nostrRelay.publish(event);
|
||||
|
||||
this.status = 'Published successfully!';
|
||||
this.photoUrl = '';
|
||||
|
||||
// Clear out the files so user can upload more or be done
|
||||
this.files = [];
|
||||
this.uploadedPhotos = [];
|
||||
} catch (e) {
|
||||
this.error = 'Failed to publish: ' + e.message;
|
||||
this.status = '';
|
||||
} finally {
|
||||
this.isPublishing = false;
|
||||
}
|
||||
}
|
||||
|
||||
<template>
|
||||
<div class="place-photo-upload">
|
||||
<h2>Add Photo for {{this.title}}</h2>
|
||||
<h2>Add Photos for {{this.title}}</h2>
|
||||
|
||||
{{#if this.error}}
|
||||
<div class="alert alert-error">
|
||||
@@ -222,38 +174,53 @@ export default class PlacePhotoUpload extends Component {
|
||||
</div>
|
||||
{{/if}}
|
||||
|
||||
<div>
|
||||
{{#if this.photoUrl}}
|
||||
<div class="preview-group">
|
||||
<p>Photo Preview:</p>
|
||||
<img
|
||||
src={{this.photoUrl}}
|
||||
alt="Preview"
|
||||
class="photo-preview-img"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-primary"
|
||||
{{on "click" this.publish}}
|
||||
>
|
||||
Publish Event (kind: 360)
|
||||
</button>
|
||||
{{else}}
|
||||
<label for="photo-upload-input">Select Photo</label>
|
||||
<input
|
||||
id="photo-upload-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
class="file-input"
|
||||
disabled={{this.isUploading}}
|
||||
{{on "change" this.handleFileSelected}}
|
||||
/>
|
||||
{{#if this.isUploading}}
|
||||
<p>Uploading...</p>
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
<div
|
||||
class="dropzone {{if this.isDragging 'is-dragging'}}"
|
||||
{{on "dragover" this.handleDragOver}}
|
||||
{{on "dragleave" this.handleDragLeave}}
|
||||
{{on "drop" this.handleDrop}}
|
||||
>
|
||||
<label for="photo-upload-input" class="dropzone-label">
|
||||
<Icon @name="upload-cloud" @size={{48}} />
|
||||
<p>Drag and drop photos here, or click to browse</p>
|
||||
</label>
|
||||
<input
|
||||
id="photo-upload-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
class="file-input-hidden"
|
||||
disabled={{this.isPublishing}}
|
||||
{{on "change" this.handleFileSelect}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{{#if this.files.length}}
|
||||
<div class="photo-grid">
|
||||
{{#each this.files as |file|}}
|
||||
<PlacePhotoItem
|
||||
@file={{file}}
|
||||
@onSuccess={{this.handleUploadSuccess}}
|
||||
@onRemove={{this.removeFile}}
|
||||
/>
|
||||
{{/each}}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-primary btn-publish"
|
||||
disabled={{or (not this.allUploaded) this.isPublishing}}
|
||||
{{on "click" this.publish}}
|
||||
>
|
||||
{{#if this.isPublishing}}
|
||||
Publishing...
|
||||
{{else}}
|
||||
Publish
|
||||
{{this.files.length}}
|
||||
Photo(s)
|
||||
{{/if}}
|
||||
</button>
|
||||
{{/if}}
|
||||
</div>
|
||||
</template>
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user