Skip to content

Commit

Permalink
Banner image upload url to nostr event tags working
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesmagoo committed Apr 9, 2024
1 parent ea2a77f commit 39b807c
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 21 deletions.
19 changes: 9 additions & 10 deletions src/ConfirmPublishModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default class ConfirmPublishModal extends Modal {

const frontmatter = this.app.metadataCache.getFileCache(this.file)?.frontmatter;

// TODO check our Progress Bar Component...
// TODO check out Progress Bar Component...

const frontmatterRegex = /---\s*[\s\S]*?\s*---/g;
const content = (await this.app.vault.read(this.file)).replace(frontmatterRegex, "").trim();
Expand Down Expand Up @@ -95,16 +95,16 @@ export default class ConfirmPublishModal extends Modal {
pillsContainer.appendChild(pillElement);
});

contentEl.createEl("h6", { text: `Summary & Banner Image (optional)` });
contentEl.createEl("h6", { text: `Summary` });
let summaryText = new TextAreaComponent(contentEl)
.setPlaceholder("Enter a brief summary here...(optional)")
.setPlaceholder("Optional brief summary of your article...")
.setValue(properties.summary);

let selectedBannerImage: File | null = null;
let selectedBannerImage: any | null = null;

new Setting(contentEl)
.setName("Upload Banner Image")
.setDesc("Upload an image to be shown alongside you articles title.")
.setDesc("Optional image to be shown alongside your articles title.")
.addButton((button) =>
button
.setButtonText("Upload")
Expand Down Expand Up @@ -144,6 +144,7 @@ export default class ConfirmPublishModal extends Modal {


imageNameDiv.textContent = selectedBannerImage.name;
console.log(file)
new Notice(`✅ Selected image : ${file.name}`);
}
} else {
Expand Down Expand Up @@ -175,7 +176,7 @@ export default class ConfirmPublishModal extends Modal {
color: "red",
});

clearImageButton.textContent = "❌ Don't use this image.";
clearImageButton.textContent = "❌ Remove image.";

function clearSelectedImage() {
selectedBannerImage = null;
Expand Down Expand Up @@ -254,20 +255,18 @@ export default class ConfirmPublishModal extends Modal {
const fileContent = content;
const title = titleText.getValue();
const summary = summaryText.getValue();
// TODO pass the uplaoded banner image file for uploading
const imageUrl = imageUrlText.getValue();
let res = await this.nostrService.publishNote(
fileContent,
this.file,
summary,
imageUrl,
selectedBannerImage.path ? selectedBannerImage.path : null,
title,
noteCategoryTags,
selectedProfileKey
);
if (res.success) {
setTimeout(() => {
new Notice(`Successfully sent note to Nostr.`);
new Notice(`Successfully sent note to Nostr.`);
}, 500);
for (let relay of res.publishedRelays) {
setTimeout(() => {
Expand Down
35 changes: 30 additions & 5 deletions src/service/ImageUploadService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import NostrWriterPlugin from "main";
import axios from 'axios';
import { App, RequestUrlParam, TFile, requestUrl } from "obsidian";
import { App, FileSystemAdapter, RequestUrlParam, TFile, normalizePath, requestUrl } from "obsidian";
import { NostrWriterPluginSettings } from "src/settings";

export default class ImageUploadService {
Expand All @@ -21,10 +21,34 @@ export default class ImageUploadService {
this.app = app;
}

async uploadImagesToStorageProvider(imageFilePaths: string[]): Promise<{ success: boolean, results: { filePath: string, stringToReplace: string, replacementStringURL: string, uploadMetadata : any }[] }> {
async uploadArticleBannerImage(imageFilePath: string): Promise<string | null> {
let result = null;
try {
let path = normalizePath(imageFilePath);
let imageBuffer = await FileSystemAdapter.readLocalFile(path);
if (imageBuffer) {
const formData = new FormData();
formData.append('file', new Blob([imageBuffer]));
const response = await axios.post('https://nostr.build/api/v2/upload/files', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
const { data } = response;
if (Array.isArray(data.data) && data.data.length > 0) {
result = data.data[0].url;
}
}
} catch (error) {
console.error(`Problem with image file reading : ${error}`)
}
return result;
}

async uploadImagesToStorageProvider(imageFilePaths: string[]): Promise<{ success: boolean, results: { filePath: string, stringToReplace: string, replacementStringURL: string, uploadMetadata: any }[] }> {
console.log("Uploading images....", imageFilePaths);

let uploadResults = [];
let uploadResults = [];
let success = true;

for (let imagePath of imageFilePaths) {
Expand All @@ -34,6 +58,7 @@ export default class ImageUploadService {
console.log(`Uploading....${imageFile.name}`)
let imageBinary = await this.app.vault.readBinary(imageFile);


const formData = new FormData();
formData.append('file', new Blob([imageBinary]), imageFile.name);

Expand Down Expand Up @@ -61,7 +86,7 @@ export default class ImageUploadService {
//let response = await requestUrl(requestUrlParams);
console.log(response)
//const { data } = response.json();
const { data } = response ;
const { data } = response;
console.log(`full Response from nostr build`, data);

console.log('Upload successful:', data.data);
Expand All @@ -71,7 +96,7 @@ export default class ImageUploadService {
filePath: imagePath,
stringToReplace: `![[${imageFile.name}]]`,
replacementStringURL: data.data[0].url,
uploadMetadata : data.data[0]
uploadMetadata: data.data[0]
};
uploadResults.push(result);
}
Expand Down
19 changes: 13 additions & 6 deletions src/service/NostrService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { SimplePool } from 'nostr-tools/pool';
import { Event } from "nostr-tools/core"
import { finalizeEvent, getPublicKey } from "nostr-tools/pure";
import { Relay } from "nostr-tools/relay";
import { App, TFile } from "obsidian";
import { App, Notice, TFile } from "obsidian";
import { NostrWriterPluginSettings } from "src/settings";
import { v4 as uuidv4 } from "uuid";
import ImageUploadService from "./ImageUploadService";
Expand Down Expand Up @@ -221,7 +221,7 @@ export default class NostrService {
fileContent: string,
activeFile: TFile,
summary: string,
imageUrl: string,
imageBannerFilePath: string | null,
title: string,
userSelectedTags: string[],
profileNickname: string
Expand All @@ -247,8 +247,15 @@ export default class NostrService {
tags.push(["summary", summary]);
}

if (imageUrl) {
tags.push(["image", imageUrl]);
if (imageBannerFilePath !== null) {
let imageUploadResult = await this.imageUploadService.uploadArticleBannerImage(imageBannerFilePath);
if (imageUploadResult !== null) {
console.log(`Banner image here: ${imageUploadResult}`)
tags.push(["image", imageUploadResult]);
new Notice("✅ Uploaded Banner Image")
} else {
new Notice("❌ Problem Uploading Banner Image..")
}
}

let timestamp = Math.floor(Date.now() / 1000);
Expand All @@ -267,6 +274,7 @@ export default class NostrService {
tags.push(["title", noteTitle]);
}

// Handle inline images, upload if possible, and replace their strings with urls in the .md content
const imagePaths: string[] = [];

try {
Expand All @@ -283,6 +291,7 @@ export default class NostrService {
}
console.log("Content Before: ", fileContent);
if (imagePaths.length > 0) {
new Notice("✅ Found inline images - uploading with article.")
let imageUploadResult = await this.imageUploadService.uploadImagesToStorageProvider(imagePaths)
if (imageUploadResult.success && imageUploadResult.results && imageUploadResult.results.length > 0) {
console.log(`Got the images uploaded ${imageUploadResult}`)
Expand Down Expand Up @@ -380,7 +389,6 @@ export default class NostrService {
return imageExtensions.includes(ext);
}


async getUserBookmarkIDs(): Promise<{ success: boolean; bookmark_event_ids: string[], longform_event_ids: string[] }> {
const bookmark_event_ids: string[] = [];
const longform_event_ids: string[] = [];
Expand Down Expand Up @@ -411,7 +419,6 @@ export default class NostrService {
}
}


async loadUserBookmarks(): Promise<Event[]> {
let events: Event[] = [];
try {
Expand Down

0 comments on commit 39b807c

Please sign in to comment.