208 lines
7.3 KiB
TypeScript
208 lines
7.3 KiB
TypeScript
import { nostrService } from './nostr'
|
|
import type { SimplePoolWithSub } from '@/types/nostr-tools-extended'
|
|
import type { AlbyInvoice } from '@/types/alby'
|
|
import { getStoredPrivateContent, getStoredInvoice, removeStoredPrivateContent } from './articleStorage'
|
|
import { buildPresentationEvent, fetchAuthorPresentationFromPool, sendEncryptedContent } from './articlePublisherHelpers'
|
|
import type { ArticleDraft, AuthorPresentationDraft, PublishedArticle } from './articlePublisherTypes'
|
|
import { prepareAuthorKeys, isValidCategory, type PublishValidationResult } from './articlePublisherValidation'
|
|
import { buildFailure, encryptAndPublish } from './articlePublisherPublish'
|
|
|
|
export type { ArticleDraft, AuthorPresentationDraft, PublishedArticle } from './articlePublisherTypes'
|
|
|
|
/**
|
|
* Service for publishing articles on Nostr
|
|
* Handles publishing preview (public note), creating invoice, and storing full content for later private message
|
|
*/
|
|
export class ArticlePublisher {
|
|
// Removed unused siteTag - using new tag system instead
|
|
|
|
private async validatePublishRequest(
|
|
draft: ArticleDraft,
|
|
authorPubkey: string,
|
|
authorPrivateKey?: string
|
|
): Promise<PublishValidationResult> {
|
|
const keySetup = prepareAuthorKeys(authorPubkey, authorPrivateKey)
|
|
if (!keySetup.success) {
|
|
return { success: false, error: keySetup.error ?? 'Key setup failed' }
|
|
}
|
|
|
|
const authorPrivateKeyForEncryption = authorPrivateKey ?? nostrService.getPrivateKey()
|
|
if (!authorPrivateKeyForEncryption) {
|
|
return { success: false, error: 'Private key required for encryption' }
|
|
}
|
|
|
|
const presentation = await this.getAuthorPresentation(authorPubkey)
|
|
if (!presentation) {
|
|
return { success: false, error: 'Vous devez créer un article de présentation avant de publier des articles.' }
|
|
}
|
|
|
|
if (!isValidCategory(draft.category)) {
|
|
return { success: false, error: 'Vous devez sélectionner une catégorie (science-fiction ou recherche scientifique).' }
|
|
}
|
|
|
|
const expectedAmount = 800
|
|
if (draft.zapAmount !== expectedAmount) {
|
|
return {
|
|
success: false,
|
|
error: `Invalid zap amount: ${draft.zapAmount} sats. Expected ${expectedAmount} sats (700 to author, 100 commission)`,
|
|
}
|
|
}
|
|
|
|
return { success: true, authorPrivateKeyForEncryption, category: draft.category }
|
|
}
|
|
|
|
/**
|
|
* Publish an article with encrypted content as a public note (kind:1)
|
|
* Creates a Lightning invoice for the article
|
|
* The content is encrypted and published, and the decryption key is sent via private message after payment
|
|
*/
|
|
async publishArticle(
|
|
draft: ArticleDraft,
|
|
authorPubkey: string,
|
|
authorPrivateKey?: string
|
|
): Promise<PublishedArticle> {
|
|
try {
|
|
const validation = await this.validatePublishRequest(draft, authorPubkey, authorPrivateKey)
|
|
if (!validation.success) {
|
|
return buildFailure(validation.error)
|
|
}
|
|
|
|
const presentation = await this.getAuthorPresentation(authorPubkey)
|
|
if (!presentation) {
|
|
return buildFailure('Presentation not found')
|
|
}
|
|
|
|
return await encryptAndPublish(draft, authorPubkey, validation.authorPrivateKeyForEncryption, validation.category, presentation.id)
|
|
} catch (error) {
|
|
console.error('Error publishing article:', error)
|
|
return buildFailure(error instanceof Error ? error.message : 'Unknown error')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update an existing article by publishing a new event that references the original
|
|
*/
|
|
/**
|
|
* Get stored private content for an article
|
|
*/
|
|
getStoredPrivateContent(articleId: string): Promise<{
|
|
content: string
|
|
authorPubkey: string
|
|
invoice?: AlbyInvoice
|
|
} | null> {
|
|
return getStoredPrivateContent(articleId)
|
|
}
|
|
|
|
/**
|
|
* Get stored invoice for an article
|
|
*/
|
|
getStoredInvoice(articleId: string): Promise<AlbyInvoice | null> {
|
|
return getStoredInvoice(articleId)
|
|
}
|
|
|
|
/**
|
|
* Send private content to a user after payment confirmation
|
|
* Returns detailed result with message event ID and verification status
|
|
*/
|
|
private logSendResult(result: import('./articlePublisherHelpers').SendContentResult, articleId: string, recipientPubkey: string) {
|
|
if (result.success) {
|
|
console.log('Private content sent successfully', {
|
|
articleId,
|
|
recipientPubkey,
|
|
messageEventId: result.messageEventId,
|
|
verified: result.verified,
|
|
timestamp: new Date().toISOString(),
|
|
})
|
|
} else {
|
|
console.error('Failed to send private content', {
|
|
articleId,
|
|
recipientPubkey,
|
|
error: result.error,
|
|
timestamp: new Date().toISOString(),
|
|
})
|
|
}
|
|
}
|
|
|
|
async sendPrivateContent(
|
|
articleId: string,
|
|
recipientPubkey: string,
|
|
authorPrivateKey: string
|
|
): Promise<import('./articlePublisherHelpers').SendContentResult> {
|
|
try {
|
|
const stored = await getStoredPrivateContent(articleId)
|
|
if (!stored) {
|
|
const error = 'Private content not found for article'
|
|
console.error(error, { articleId, recipientPubkey })
|
|
return { success: false, error }
|
|
}
|
|
|
|
const result = await sendEncryptedContent(articleId, recipientPubkey, stored, authorPrivateKey)
|
|
this.logSendResult(result, articleId, recipientPubkey)
|
|
return result
|
|
} catch (error) {
|
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
|
console.error('Error sending private content', {
|
|
articleId,
|
|
recipientPubkey,
|
|
error: errorMessage,
|
|
timestamp: new Date().toISOString(),
|
|
})
|
|
return { success: false, error: errorMessage }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remove stored private content (after successful send or expiry)
|
|
*/
|
|
async removeStoredPrivateContent(articleId: string): Promise<void> {
|
|
await removeStoredPrivateContent(articleId)
|
|
}
|
|
|
|
/**
|
|
* Publish an author presentation article (obligatory for all authors)
|
|
* This article is free and contains the author's presentation, content description, and mainnet address
|
|
*/
|
|
async publishPresentationArticle(
|
|
draft: AuthorPresentationDraft,
|
|
authorPubkey: string,
|
|
authorPrivateKey: string
|
|
): Promise<PublishedArticle> {
|
|
try {
|
|
nostrService.setPublicKey(authorPubkey)
|
|
nostrService.setPrivateKey(authorPrivateKey)
|
|
|
|
// Generate event ID before building event (using a temporary ID that will be replaced by Nostr)
|
|
const tempEventId = `temp_${Math.random().toString(36).substring(7)}`
|
|
const publishedEvent = await nostrService.publishEvent(buildPresentationEvent(draft, tempEventId, 'sciencefiction'))
|
|
|
|
if (!publishedEvent) {
|
|
return buildFailure('Failed to publish presentation article')
|
|
}
|
|
|
|
return {
|
|
articleId: publishedEvent.id,
|
|
previewEventId: publishedEvent.id,
|
|
success: true,
|
|
}
|
|
} catch (error) {
|
|
console.error('Error publishing presentation article:', error)
|
|
return buildFailure(error instanceof Error ? error.message : 'Unknown error')
|
|
}
|
|
}
|
|
|
|
async getAuthorPresentation(pubkey: string): Promise<import('@/types/nostr').AuthorPresentationArticle | null> {
|
|
try {
|
|
const pool = nostrService.getPool()
|
|
if (!pool) {
|
|
return null
|
|
}
|
|
return await fetchAuthorPresentationFromPool(pool as SimplePoolWithSub, pubkey)
|
|
} catch (error) {
|
|
console.error('Error getting author presentation:', error)
|
|
return null
|
|
}
|
|
}
|
|
}
|
|
|
|
export const articlePublisher = new ArticlePublisher()
|