340 lines
12 KiB
TypeScript
340 lines
12 KiB
TypeScript
import { type Event } from 'nostr-tools'
|
|
import { nip19 } from 'nostr-tools'
|
|
import type { AuthorPresentationDraft } from './articlePublisher'
|
|
import type { SimplePoolWithSub } from '@/types/nostr-tools-extended'
|
|
import { buildTags, extractTagsFromEvent, buildTagFilter } from './nostrTagSystem'
|
|
import { getPrimaryRelaySync } from './config'
|
|
import { PLATFORM_SERVICE, MIN_EVENT_DATE } from './platformConfig'
|
|
import { generateAuthorHashId } from './hashIdGenerator'
|
|
import { generateObjectUrl, buildObjectId, parseObjectId } from './urlGenerator'
|
|
import { getLatestVersion } from './versionManager'
|
|
import { objectCache } from './objectCache'
|
|
|
|
export async function buildPresentationEvent(
|
|
draft: AuthorPresentationDraft,
|
|
authorPubkey: string,
|
|
authorName: string,
|
|
category: 'sciencefiction' | 'research' = 'sciencefiction',
|
|
version: number = 0,
|
|
index: number = 0
|
|
): Promise<{
|
|
kind: 1
|
|
created_at: number
|
|
tags: string[][]
|
|
content: string
|
|
}> {
|
|
// Extract presentation and contentDescription from draft.content
|
|
// Format: "${presentation}\n\n---\n\nDescription du contenu :\n${contentDescription}"
|
|
const separator = '\n\n---\n\nDescription du contenu :\n'
|
|
const separatorIndex = draft.content.indexOf(separator)
|
|
const presentation = separatorIndex !== -1 ? draft.content.substring(0, separatorIndex) : draft.presentation
|
|
let contentDescription = separatorIndex !== -1 ? draft.content.substring(separatorIndex + separator.length) : draft.contentDescription
|
|
|
|
// Remove Bitcoin address from contentDescription if present (should not be visible in note content)
|
|
// Remove lines matching "Adresse Bitcoin mainnet (pour le sponsoring) : ..."
|
|
if (contentDescription) {
|
|
contentDescription = contentDescription
|
|
.split('\n')
|
|
.filter((line) => !line.includes('Adresse Bitcoin mainnet (pour le sponsoring)'))
|
|
.join('\n')
|
|
.trim()
|
|
}
|
|
|
|
// Generate hash ID from author data first (needed for URL)
|
|
const hashId = await generateAuthorHashId({
|
|
pubkey: authorPubkey,
|
|
authorName,
|
|
presentation,
|
|
contentDescription,
|
|
mainnetAddress: draft.mainnetAddress ?? undefined,
|
|
pictureUrl: draft.pictureUrl ?? undefined,
|
|
category,
|
|
})
|
|
|
|
// Build URL: https://zapwall.fr/author/<hash>_<index>_<version> (using hash ID)
|
|
const profileUrl = generateObjectUrl('author', hashId, index, version)
|
|
|
|
// Encode pubkey to npub (for metadata JSON)
|
|
const npub = nip19.npubEncode(authorPubkey)
|
|
|
|
// Build visible content message
|
|
// If picture exists, use it as preview image for the link (markdown format)
|
|
// Note: The image will display at full size in most Nostr clients, not as a thumbnail
|
|
const linkWithPreview = draft.pictureUrl
|
|
? `[](${profileUrl})`
|
|
: profileUrl
|
|
|
|
const visibleContent = [
|
|
'Nouveau profil auteur publié sur zapwall.fr (plateforme de publications scientifiques)',
|
|
linkWithPreview,
|
|
`Présentation personnelle : ${presentation}`,
|
|
...(contentDescription ? [`Description de votre contenu : ${contentDescription}`] : []),
|
|
].join('\n')
|
|
|
|
// Build profile JSON for metadata (stored in tag, not in content)
|
|
const profileJson = JSON.stringify({
|
|
authorName,
|
|
npub,
|
|
pubkey: authorPubkey,
|
|
presentation,
|
|
contentDescription,
|
|
mainnetAddress: draft.mainnetAddress,
|
|
pictureUrl: draft.pictureUrl,
|
|
category,
|
|
url: profileUrl,
|
|
version,
|
|
index,
|
|
})
|
|
|
|
// Build tags (profile JSON is in tag, not in content)
|
|
const tags = buildTags({
|
|
type: 'author',
|
|
category,
|
|
id: hashId,
|
|
service: PLATFORM_SERVICE,
|
|
version,
|
|
hidden: false,
|
|
paywall: false,
|
|
title: draft.title,
|
|
preview: draft.preview,
|
|
mainnetAddress: draft.mainnetAddress,
|
|
...(draft.pictureUrl ? { pictureUrl: draft.pictureUrl } : {}),
|
|
})
|
|
|
|
// Add JSON metadata as a tag (not in visible content)
|
|
tags.push(['json', profileJson])
|
|
|
|
return {
|
|
kind: 1 as const,
|
|
created_at: Math.floor(Date.now() / 1000),
|
|
tags,
|
|
content: visibleContent,
|
|
}
|
|
}
|
|
|
|
export async function parsePresentationEvent(event: Event): Promise<import('@/types/nostr').AuthorPresentationArticle | null> {
|
|
const tags = extractTagsFromEvent(event)
|
|
|
|
// Check if it's an author type (tag is 'author' in English)
|
|
if (tags.type !== 'author') {
|
|
return null
|
|
}
|
|
|
|
// Try to extract profile JSON from tag first (new format)
|
|
let profileData: {
|
|
authorName?: string
|
|
presentation?: string
|
|
contentDescription?: string
|
|
mainnetAddress?: string
|
|
pictureUrl?: string
|
|
category?: string
|
|
} | null = null
|
|
|
|
if (tags.json) {
|
|
try {
|
|
profileData = JSON.parse(tags.json)
|
|
} catch (jsonError) {
|
|
console.error('Error parsing JSON from tag:', jsonError)
|
|
}
|
|
}
|
|
|
|
// Fallback to content format (for backward compatibility with old notes)
|
|
if (!profileData) {
|
|
// Try invisible format (with zero-width characters)
|
|
const invisibleJsonMatch = event.content.match(/[\u200B\u200C]\[Metadata JSON\][\u200B\u200C]\n[\u200B\u200C](.+)[\u200B\u200C]$/s)
|
|
if (invisibleJsonMatch?.[1]) {
|
|
try {
|
|
// Remove zero-width characters from JSON
|
|
const cleanedJson = invisibleJsonMatch[1].replace(/[\u200B\u200C\u200D\u200E\u200F]/g, '').trim()
|
|
profileData = JSON.parse(cleanedJson)
|
|
} catch (invisibleJsonError) {
|
|
console.error('Error parsing profile JSON from invisible content:', invisibleJsonError)
|
|
}
|
|
}
|
|
|
|
// Fallback to visible format in content
|
|
if (!profileData) {
|
|
const jsonMatch = event.content.match(/\[Metadata JSON\]\n(.+)$/s)
|
|
if (jsonMatch?.[1]) {
|
|
try {
|
|
profileData = JSON.parse(jsonMatch[1].trim())
|
|
} catch (contentJsonError) {
|
|
console.error('Error parsing profile JSON from content:', contentJsonError)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Map tag category to article category
|
|
const articleCategory = tags.category === 'sciencefiction' ? 'science-fiction' : tags.category === 'research' ? 'scientific-research' : undefined
|
|
|
|
// Extract hash, version, index from id tag or parse it
|
|
let hash: string
|
|
let version = tags.version ?? 0
|
|
let index = 0
|
|
|
|
if (tags.id) {
|
|
const parsed = parseObjectId(tags.id)
|
|
if (parsed.hash) {
|
|
hash = parsed.hash
|
|
version = parsed.version ?? version
|
|
index = parsed.index ?? index
|
|
} else {
|
|
// If id is just a hash, use it directly
|
|
hash = tags.id
|
|
}
|
|
} else {
|
|
// Generate hash from author data
|
|
hash = await generateAuthorHashId({
|
|
pubkey: event.pubkey,
|
|
authorName: profileData?.authorName ?? '',
|
|
presentation: profileData?.presentation ?? '',
|
|
contentDescription: profileData?.contentDescription ?? '',
|
|
mainnetAddress: profileData?.mainnetAddress ?? (typeof tags.mainnetAddress === 'string' ? tags.mainnetAddress : undefined),
|
|
pictureUrl: profileData?.pictureUrl ?? (typeof tags.pictureUrl === 'string' ? tags.pictureUrl : undefined),
|
|
category: profileData?.category ?? tags.category ?? 'sciencefiction',
|
|
})
|
|
}
|
|
|
|
const id = buildObjectId(hash, index, version)
|
|
|
|
// totalSponsoring is calculated from cache, not from tags
|
|
// It will be set when the article is loaded from cache or calculated on demand
|
|
const result: import('@/types/nostr').AuthorPresentationArticle = {
|
|
id,
|
|
hash,
|
|
version,
|
|
index,
|
|
pubkey: event.pubkey,
|
|
title: tags.title ?? 'Présentation',
|
|
preview: tags.preview ?? event.content.substring(0, 200),
|
|
content: event.content,
|
|
description: profileData?.presentation ?? tags.description ?? '', // Required field
|
|
contentDescription: ((): string => {
|
|
const raw = profileData?.contentDescription ?? tags.description ?? ''
|
|
// Remove Bitcoin address from contentDescription if present (should not be visible)
|
|
return raw
|
|
.split('\n')
|
|
.filter((line) => !line.includes('Adresse Bitcoin mainnet (pour le sponsoring)'))
|
|
.join('\n')
|
|
.trim()
|
|
})(), // Required field
|
|
thumbnailUrl: (typeof profileData?.pictureUrl === 'string' ? profileData.pictureUrl : typeof tags.pictureUrl === 'string' ? tags.pictureUrl : ''), // Required field
|
|
createdAt: event.created_at,
|
|
zapAmount: 0,
|
|
paid: true,
|
|
category: 'author-presentation',
|
|
isPresentation: true,
|
|
mainnetAddress: profileData?.mainnetAddress ?? tags.mainnetAddress ?? '',
|
|
totalSponsoring: 0, // Will be calculated from cache when needed
|
|
originalCategory: articleCategory ?? 'science-fiction', // Store original category for filtering
|
|
}
|
|
|
|
// Add bannerUrl if available
|
|
if (profileData?.pictureUrl !== undefined && profileData?.pictureUrl !== null) {
|
|
result.bannerUrl = profileData.pictureUrl
|
|
} else if (tags.pictureUrl !== undefined && tags.pictureUrl !== null && typeof tags.pictureUrl === 'string') {
|
|
result.bannerUrl = tags.pictureUrl
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
export async function fetchAuthorPresentationFromPool(
|
|
pool: SimplePoolWithSub,
|
|
pubkey: string
|
|
): Promise<import('@/types/nostr').AuthorPresentationArticle | null> {
|
|
// Check cache first - this is the primary source
|
|
const cached = await objectCache.getAuthorByPubkey(pubkey)
|
|
if (cached) {
|
|
// Calculate totalSponsoring from cache
|
|
const { getAuthorSponsoring } = await import('./sponsoring')
|
|
cached.totalSponsoring = await getAuthorSponsoring(pubkey)
|
|
return cached
|
|
}
|
|
|
|
const filters = [
|
|
{
|
|
...buildTagFilter({
|
|
type: 'author',
|
|
authorPubkey: pubkey,
|
|
service: PLATFORM_SERVICE,
|
|
}),
|
|
since: MIN_EVENT_DATE,
|
|
limit: 100, // Get all versions to find the latest
|
|
},
|
|
]
|
|
|
|
return new Promise<import('@/types/nostr').AuthorPresentationArticle | null>((resolve) => {
|
|
let resolved = false
|
|
const relayUrl = getPrimaryRelaySync()
|
|
const { createSubscription } = require('@/types/nostr-tools-extended')
|
|
const sub = createSubscription(pool, [relayUrl], filters)
|
|
|
|
const events: Event[] = []
|
|
|
|
const finalize = async (value: import('@/types/nostr').AuthorPresentationArticle | null): Promise<void> => {
|
|
if (resolved) {
|
|
return
|
|
}
|
|
resolved = true
|
|
sub.unsub()
|
|
|
|
// Cache the result if found
|
|
if (value && events.length > 0) {
|
|
const event = events.find(e => e.id === value.id) || events[0]
|
|
if (event) {
|
|
const tags = extractTagsFromEvent(event)
|
|
if (value.hash) {
|
|
// Calculate totalSponsoring from cache before storing
|
|
const { getAuthorSponsoring } = await import('./sponsoring')
|
|
value.totalSponsoring = await getAuthorSponsoring(value.pubkey)
|
|
const { writeService } = await import('./writeService')
|
|
await writeService.writeObject('author', value.hash, event, value, tags.version ?? 0, tags.hidden, value.index, false)
|
|
}
|
|
}
|
|
}
|
|
|
|
resolve(value)
|
|
}
|
|
|
|
sub.on('event', (event: Event): void => {
|
|
// Collect all events first
|
|
const tags = extractTagsFromEvent(event)
|
|
if (tags.type === 'author' && !tags.hidden) {
|
|
events.push(event)
|
|
}
|
|
})
|
|
|
|
sub.on('eose', (): void => {
|
|
void (async (): Promise<void> => {
|
|
// Get the latest version from all collected events
|
|
const latestEvent = getLatestVersion(events)
|
|
if (latestEvent) {
|
|
const parsed = await parsePresentationEvent(latestEvent)
|
|
if (parsed) {
|
|
await finalize(parsed)
|
|
return
|
|
}
|
|
}
|
|
await finalize(null)
|
|
})()
|
|
})
|
|
// Reduced timeout for faster feedback when cache is empty
|
|
setTimeout((): void => {
|
|
void (async (): Promise<void> => {
|
|
// Get the latest version from all collected events
|
|
const latestEvent = getLatestVersion(events)
|
|
if (latestEvent) {
|
|
const parsed = await parsePresentationEvent(latestEvent)
|
|
if (parsed) {
|
|
await finalize(parsed)
|
|
return
|
|
}
|
|
}
|
|
await finalize(null)
|
|
})()
|
|
}, 2000).unref?.()
|
|
})
|
|
}
|