Remove dependency Unidata (#473)

This commit is contained in:
DIYgod
2023-05-02 00:32:25 +01:00
committed by GitHub
parent f7068304de
commit 2fe77a563f
75 changed files with 1636 additions and 1713 deletions
+249 -258
View File
@@ -1,38 +1,39 @@
import { NoteMetadata } from "crossbell.js"
import type { Contract } from "crossbell.js"
import type {
CharacterEntity,
Contract,
ListResponse,
MintedNoteEntity,
NoteEntity,
} from "crossbell.js"
import type Unidata from "unidata.js"
import { GeneralAccount } from "@crossbell/connect-kit"
import { indexer } from "@crossbell/indexer"
import { expandCrossbellNote, expandUnidataNote } from "~/lib/expand-unit"
import { expandCrossbellNote } from "~/lib/expand-unit"
import { notFound } from "~/lib/server-side-props"
import { checkSlugReservedWords } from "~/lib/slug-reserved-words"
import { getKeys, getStorage } from "~/lib/storage"
import { ExpandedNote, Note, Notes, PageVisibilityEnum } from "~/lib/types"
import unidata from "~/queries/unidata.server"
import { ExpandedNote, PageVisibilityEnum } from "~/lib/types"
export async function checkPageSlug(
input: {
slug: string
site: string
pageId?: string
},
customUnidata?: Unidata,
) {
export async function checkPageSlug(input: {
slug: string
characterId?: number
}) {
if (!input.characterId) {
return "Character not found"
}
const reserved = checkSlugReservedWords(input.slug)
if (reserved) {
return reserved
} else {
try {
const page = await getPage(
{
page: input.slug,
site: input.site,
},
customUnidata,
)
if (page && page.id !== input.pageId) {
const page = await getPage({
slug: input.slug,
characterId: input.characterId,
})
if (page) {
return `Slug "${input.slug}" has already been used`
}
} catch (error) {}
@@ -58,6 +59,8 @@ export async function createOrUpdatePage(
customUnidata?: Unidata,
newbieToken?: string,
) {
const { default: unidata } = await import("~/queries/unidata.server")
if (!input.published) {
return await (customUnidata || unidata).notes.set(
{
@@ -129,7 +132,7 @@ export async function createOrUpdatePage(
export async function postNotes(
input: {
siteId: string
characterId: string
characterId: number
notes: NoteMetadata[]
},
contract?: Contract,
@@ -142,163 +145,172 @@ export async function postNotes(
)
}
const getLocalPages = (input: { site: string; isPost?: boolean }) => {
const pages: Note[] = []
getKeys(`draft-${input.site}-`).forEach((key) => {
const getLocalPages = (input: { characterId: number; isPost?: boolean }) => {
const pages: ExpandedNote[] = []
getKeys(`draft-${input.characterId}-`).forEach((key) => {
const page = getStorage(key)
if (input.isPost === undefined || page.isPost === input.isPost) {
pages.push({
id: key.replace(`draft-${input.site}-`, ""),
title: page.values?.title,
body: {
content: page.values?.content,
mime_type: "text/markdown",
const note: ExpandedNote = {
characterId: input.characterId,
noteId: 0,
draftKey: key.replace(`draft-${input.characterId}-`, ""),
linkItemType: null,
linkKey: "",
toCharacterId: null,
toAddress: null,
toNoteId: null,
toHeadCharacterId: null,
toHeadNoteId: null,
toContractAddress: null,
toTokenId: null,
toLinklistId: null,
toUri: null,
deleted: false,
locked: false,
contractAddress: null,
uri: null,
operator: "",
owner: "",
createdAt: new Date(page.date).toISOString(),
updatedAt: new Date(page.date).toISOString(),
deletedAt: null,
transactionHash: "",
blockNumber: 0,
logIndex: 0,
updatedTransactionHash: "",
updatedBlockNumber: 0,
updatedLogIndex: 0,
metadata: {
content: {
title: page.values?.title,
content: page.values?.content,
date_published: page.values?.publishedAt,
summary: page.values?.excerpt,
tags: [
page.isPost ? "post" : "page",
...(page.values?.tags
?.split(",")
.map((tag: string) => tag.trim())
.filter((tag: string) => tag) || []),
],
sources: ["xlog"],
},
},
date_updated: new Date(page.date).toISOString(),
date_published: page.values?.publishedAt,
summary: {
content: page.values?.excerpt,
mime_type: "text/markdown",
},
tags: [
page.isPost ? "post" : "page",
...(page.values?.tags
?.split(",")
.map((tag: string) => tag.trim())
.filter((tag: string) => tag) || []),
],
applications: ["xlog"],
...(page.values?.slug && {
attributes: [
{
trait_type: "xlog_slug",
value: page.values?.slug,
},
],
}),
preview: true,
})
local: true,
}
pages.push(note)
}
})
return pages
}
export async function getPagesBySite(
input: {
site?: string
type: "post" | "page"
visibility?: PageVisibilityEnum | null
take?: number | null
cursor?: string | null
tags?: string[]
useStat?: boolean
keepBody?: boolean
},
customUnidata?: Unidata,
) {
if (!input.site) {
export async function getPagesBySite(input: {
characterId?: number
type: "post" | "page"
visibility?: PageVisibilityEnum
limit?: number
cursor?: string
tags?: string[]
useStat?: boolean
keepBody?: boolean
}) {
if (!input.characterId) {
return {
total: 0,
count: 0,
list: [],
cursor: null,
}
}
const visibility = input.visibility || PageVisibilityEnum.All
const crossbell = visibility === PageVisibilityEnum.Crossbell
const options = {
source: "Crossbell Note",
identity: input.site,
platform: "Crossbell",
limit: input.take || 10,
order_by: "date_published" as "date_published",
filter: {
tags: [...(input.tags || []), ...(crossbell ? [] : [input.type])],
applications: [...(crossbell ? [] : ["xlog"])],
},
...(input.cursor && { cursor: input.cursor }),
}
const notes = await indexer.getNotes({
characterId: input.characterId,
limit: input.limit || 10,
cursor: input.cursor,
orderBy: "publishedAt",
tags: [...(input.tags || []), input.type],
sources: "xlog",
})
let pages: Notes = {
total: 0,
list: [],
}
pages = (await (customUnidata || unidata).notes.get(options)) || {
total: 0,
list: [],
}
if (!crossbell) {
const local = getLocalPages({
site: input.site,
isPost: input.type === "post",
})
local.forEach((localPage) => {
const index = pages.list.findIndex((page) => page.id === localPage.id)
if (
index >= 0 &&
new Date(localPage.date_updated) >
new Date(pages.list[index].date_updated)
) {
localPage.metadata = pages.list[index].metadata
pages.list[index] = localPage
} else {
pages.list.push(localPage)
pages.total++
const list = await Promise.all(
notes?.list.map(async (note) => {
const expanded = await expandCrossbellNote(note, input.useStat)
if (!input.keepBody) {
delete expanded.metadata?.content?.content
}
})
pages.list = pages.list.sort(
(a, b) => +new Date(b.date_published) - +new Date(a.date_published),
)
}
return expanded
}),
)
if (pages?.list) {
switch (visibility) {
case PageVisibilityEnum.Published:
pages.list = pages.list.filter(
(page) =>
+new Date(page.date_published) <= +new Date() && page.metadata,
)
break
case PageVisibilityEnum.Draft:
pages.list = pages.list.filter((page) => !page.metadata)
break
case PageVisibilityEnum.Scheduled:
pages.list = pages.list.filter(
(page) => +new Date(page.date_published) > +new Date(),
)
break
case PageVisibilityEnum.Crossbell:
pages.list = pages.list.filter(
(page) => !page.applications?.includes("xlog"),
)
break
const expandedNotes: {
list: ExpandedNote[]
count: number
cursor: string | null
} = Object.assign(notes, {
list,
})
const local = getLocalPages({
characterId: input.characterId,
isPost: input.type === "post",
})
local.forEach((localPage) => {
const index = expandedNotes.list.findIndex(
(page) => localPage.draftKey === page.noteId + "",
)
if (
index !== -1 &&
new Date(localPage.updatedAt) >
new Date(expandedNotes.list[index].updatedAt)
) {
expandedNotes.list[index] = {
...expandedNotes.list[index],
metadata: {
content: localPage.metadata?.content,
},
local: true,
}
} else {
expandedNotes.list.push(localPage)
expandedNotes.count++
}
const allLength = pages.list.length
pages.list = pages.list.filter(
(page) => page.date_published !== new Date("9999-01-01").toISOString(),
)
pages.total = pages.total - (allLength - pages.list.length)
})
await Promise.all(
pages?.list.map(async (page) => {
await expandUnidataNote(page, input.useStat)
if (!input.keepBody) {
delete page.body
}
return page
}),
)
switch (visibility) {
case PageVisibilityEnum.Published:
expandedNotes.list = expandedNotes.list.filter(
(page) =>
(!page.metadata?.content?.date_published ||
+new Date(page.metadata?.content?.date_published) <= +new Date()) &&
page.noteId,
)
break
case PageVisibilityEnum.Draft:
expandedNotes.list = expandedNotes.list.filter((page) => !page.noteId)
break
case PageVisibilityEnum.Scheduled:
expandedNotes.list = expandedNotes.list.filter(
(page) =>
page.metadata?.content?.date_published &&
+new Date(page.metadata?.content?.date_published) > +new Date(),
)
break
}
return pages
expandedNotes.list = expandedNotes.list.sort((a, b) =>
a.metadata?.content?.date_published && b.metadata?.content?.date_published
? +new Date(b.metadata?.content?.date_published) -
+new Date(a.metadata?.content?.date_published)
: 0,
)
return expandedNotes
}
export async function getSearchPagesBySite(input: {
characterId?: string
characterId?: number
keyword?: string
cursor?: string
}) {
@@ -323,80 +335,66 @@ export async function getSearchPagesBySite(input: {
}
}
export async function getPage<TRender extends boolean = false>(
input: {
/** page slug or id, `site` is needed when `page` is a slug */
page?: string
pageId?: string
site?: string
useStat?: boolean
},
customUnidata?: Unidata,
) {
if (!input.site || !(input.page || input.pageId)) {
return null
}
export async function getPage<TRender extends boolean = false>(input: {
slug?: string
characterId: number
useStat?: boolean
noteId?: number
}) {
const mustLocal = input.slug?.startsWith("local-")
const mustLocal = input.pageId?.startsWith("local-")
let page: Note | null = null
let page: NoteEntity | null = null
if (!mustLocal) {
// on-chain page
if (!input.pageId) {
if (!input.site || !input.page) return null
if (!input.noteId) {
const response = await fetch(
`/api/slug2id?${new URLSearchParams({
handle: input.site,
slug: input.page,
characterId: input.characterId + "",
slug: input.slug!,
}).toString()}`,
)
const slug2Id = await response.json()
if (!slug2Id?.noteId) {
return null
}
input.pageId = `${slug2Id.characterId}-${slug2Id.noteId}`
input.noteId = (await response.json())?.noteId
}
if (input.noteId) {
page = await indexer.getNote(input.characterId, input.noteId)
}
const pages = await (customUnidata || unidata).notes.get({
source: "Crossbell Note",
identity: input.site,
platform: "Crossbell",
filter: {
id: input.pageId,
},
})
page = pages?.list[0] || null
}
// local page
const local = getLocalPages({
site: input.site,
characterId: input.characterId,
})
const localPage = local.find(
(page) => page.id === input.page || page.id === input.pageId,
(page) =>
page.draftKey === input.noteId + "" || page.draftKey === input.slug,
)
let expandedNote: ExpandedNote | undefined
if (page) {
expandedNote = await expandCrossbellNote(page, input.useStat)
}
if (localPage) {
if (page) {
if (new Date(localPage.date_updated) > new Date(page.date_updated)) {
localPage.metadata = page.metadata
page = localPage
if (expandedNote) {
if (new Date(localPage.updatedAt) > new Date(expandedNote.updatedAt)) {
expandedNote = {
...expandedNote,
metadata: {
content: localPage.metadata?.content,
},
local: true,
}
}
} else {
page = localPage
expandedNote = localPage
}
}
if (!page && !mustLocal) {
throw notFound(`page ${input.page} not found`)
if (!expandedNote && !mustLocal) {
throw notFound(`page ${input.slug} not found`)
}
if (page) {
await expandUnidataNote(page, input.useStat)
}
return page
return expandedNote
}
export async function deletePage(
@@ -404,6 +402,8 @@ export async function deletePage(
customUnidata?: Unidata,
newbieToken?: string,
) {
const { default: unidata } = await import("~/queries/unidata.server")
return await (customUnidata || unidata).notes.set(
{
source: "Crossbell Note",
@@ -421,22 +421,20 @@ export async function deletePage(
}
export async function getLikes({
pageId,
characterId,
noteId,
cursor,
includeCharacter,
}: {
pageId: string
characterId: number
noteId: number
cursor?: string
includeCharacter?: boolean
}) {
const res = await indexer.getBacklinksOfNote(
pageId.split("-")[0],
pageId.split("-")[1],
{
linkType: "like",
cursor,
},
)
const res = await indexer.getBacklinksOfNote(characterId, noteId, {
linkType: "like",
cursor,
})
if (includeCharacter) {
res.list?.forEach((item) => {
;(item as any).character = item.fromCharacter
@@ -448,18 +446,20 @@ export async function getLikes({
export async function checkLike({
account,
pageId,
characterId,
noteId,
}: {
account: GeneralAccount
pageId: string
characterId: number
noteId: number
}) {
if (!account.characterId) {
throw notFound(`character not found`)
} else {
return indexer.getLinks(account.characterId, {
linkType: "like",
toCharacterId: pageId.split("-")[0],
toNoteId: pageId.split("-")[1],
toCharacterId: characterId,
toNoteId: noteId,
})
}
}
@@ -467,33 +467,33 @@ export async function checkLike({
export async function mintPage(
{
address,
pageId,
characterId,
noteId,
}: {
address: string
pageId: string
characterId: number
noteId: number
},
contract?: Contract,
) {
return contract?.mintNote(pageId.split("-")[0], pageId.split("-")[1], address)
return contract?.mintNote(characterId, noteId, address)
}
export async function getMints({
pageId,
characterId,
noteId,
cursor,
includeCharacter,
}: {
pageId: string
characterId: number
noteId: number
cursor?: string
includeCharacter?: boolean
}) {
const data = await indexer.getMintedNotesOfNote(
pageId.split("-")[0],
pageId.split("-")[1],
{
cursor,
limit: 5,
},
)
const data = await indexer.getMintedNotesOfNote(characterId, noteId, {
cursor,
limit: 5,
})
if (includeCharacter) {
await Promise.all(
@@ -505,32 +505,40 @@ export async function getMints({
)
}
return data
return data as ListResponse<
MintedNoteEntity & {
character: CharacterEntity
}
>
}
export async function checkMint({
address,
pageId,
noteCharacterId,
noteId,
}: {
address: string
pageId: string
noteCharacterId: number
noteId: number
}) {
return indexer.getMintedNotesOfAddress(address, {
noteCharacterId: pageId.split("-")[0],
noteId: pageId.split("-")[1],
noteCharacterId: noteCharacterId,
noteId: noteId,
})
}
export async function getComments({
pageId,
characterId,
noteId,
cursor,
}: {
pageId: string
characterId: number
noteId: number
cursor?: string
}) {
const options = {
toCharacterId: pageId.split("-")[0],
toNoteId: pageId.split("-")[1],
toCharacterId: characterId,
toNoteId: noteId,
cursor,
includeCharacter: true,
includeNestedNotes: true,
@@ -549,17 +557,13 @@ export async function getComments({
export async function updateComment(
{
pageId,
content,
externalUrl,
originalId,
characterId,
noteId,
}: {
pageId: string
content: string
externalUrl: string
originalId?: string
characterId: number
noteId: number
},
@@ -573,19 +577,6 @@ export async function updateComment(
})
}
export function parsePageId(pageId: string) {
const [characterId, noteId] = pageId.split("-").map(Number)
return { characterId, noteId }
}
export function toPageId({
characterId,
noteId,
}: ReturnType<typeof parsePageId>) {
return `${characterId}-${noteId}`
}
export async function getSummary({
cid,
lang,
@@ -598,10 +589,10 @@ export async function getSummary({
).data
}
export async function checkMirror(characterId: string) {
export async function checkMirror(characterId: number) {
const notes = await indexer.getNotes({
characterId,
sources: ["xlog"],
sources: "xlog",
tags: ["post", "Mirror.xyz"],
limit: 0,
})
+49 -177
View File
@@ -1,93 +1,31 @@
import { CharacterOperatorPermission, Indexer } from "crossbell.js"
import { nanoid } from "nanoid"
import type Unidata from "unidata.js"
import type { Profiles as UniProfiles } from "unidata.js"
import type { useContract } from "@crossbell/contract"
import { cacheExchange, createClient, fetchExchange } from "@urql/core"
import { expandUnidataProfile } from "~/lib/expand-unit"
import { Profile, SiteNavigationItem } from "~/lib/types"
import unidata from "~/queries/unidata.server"
import { expandCrossbellCharacter } from "~/lib/expand-unit"
import { SiteNavigationItem } from "~/lib/types"
type Contract = ReturnType<typeof useContract>
const indexer = new Indexer()
export type GetUserSitesParams =
| {
address: string
unidata?: Unidata
}
| {
handle: string
unidata?: Unidata
}
export const getUserSites = async (params: GetUserSitesParams) => {
let profiles: UniProfiles | null = null
try {
const source = "Crossbell Profile"
const filter = { primary: true }
if ("address" in params) {
profiles = await (params.unidata || unidata).profiles.get({
source,
filter,
identity: params.address,
platform: "Ethereum",
})
}
if ("handle" in params) {
profiles = await (params.unidata || unidata).profiles.get({
source,
filter,
identity: params.handle,
platform: "Crossbell",
})
}
} catch (error) {
return null
export const getSite = async (input: string) => {
const result = await indexer.getCharacterByHandle(input)
if (result) {
return expandCrossbellCharacter(result)
}
const sites: Profile[] =
profiles?.list?.map((profile) => {
expandUnidataProfile(profile)
return profile
}) ?? []
return sites.length > 0 ? sites : null
}
export type GetAccountSitesParams = {
handle: string
unidata?: Unidata
}
export const getAccountSites = (
params: GetAccountSitesParams,
): Promise<Profile[] | null> => {
return getUserSites({
handle: params.handle,
unidata: params.unidata,
})
}
export const getSite = async (input: string, customUnidata?: Unidata) => {
const profiles = await (customUnidata || unidata).profiles.get({
source: "Crossbell Profile",
identity: input,
platform: "Crossbell",
export const getSiteByAddress = async (input: string) => {
const result = await indexer.getCharacters(input, {
primary: true,
})
const site: Profile = profiles.list[0]
if (site) {
expandUnidataProfile(site)
if (result?.list?.[0]) {
return expandCrossbellCharacter(result.list[0])
}
return site
}
export const getSubscriptionsFromList = async (
@@ -124,64 +62,38 @@ export const getSubscriptionsFromList = async (
return response.data?.links.map((link: any) => link.toCharacterId)
}
export const getSubscription = async (
siteId: string,
handle: string,
customUnidata?: Unidata,
) => {
const links = await (customUnidata || unidata).links.get({
source: "Crossbell Link",
identity: handle,
platform: "Crossbell",
filter: { to: siteId },
export const getSubscription = async (input: {
toCharacterId: number
characterId: number
}) => {
const result = await indexer.getLinks(input.characterId, {
linkType: "follow",
toCharacterId: input.toCharacterId,
})
return !!links?.list?.length
return !!result?.list?.length
}
export const getSiteSubscriptions = async (
data: {
siteId: string
cursor?: string
limit?: number
},
customUnidata?: Unidata,
) => {
const links = await (customUnidata || unidata).links.get({
source: "Crossbell Link",
identity: data.siteId,
platform: "Crossbell",
reversed: true,
export const getSiteSubscriptions = async (data: {
characterId: number
cursor?: string
limit?: number
}) => {
return indexer.getBacklinksOfCharacter(data.characterId, {
linkType: "follow",
cursor: data.cursor,
limit: data.limit,
})
links?.list.map(async (item: any) => {
item.character = item.metadata.from_raw
}) || []
return links
}
export const getSiteToSubscriptions = async (
data: {
siteId: string
cursor?: string
},
customUnidata?: Unidata,
) => {
const links = await (customUnidata || unidata).links.get({
source: "Crossbell Link",
identity: data.siteId,
platform: "Crossbell",
export const getSiteToSubscriptions = async (data: {
characterId: number
cursor?: string
}) => {
return indexer.getLinks(data.characterId, {
linkType: "follow",
cursor: data.cursor,
})
links?.list.map(async (item: any) => {
item.character = item.metadata.to_raw
}) || []
return links
}
export async function updateSite(
@@ -199,11 +111,17 @@ export async function updateSite(
address: string
mime_type: string
}
connected_accounts?: Profile["connected_accounts"]
connected_accounts?: {
identity: string
platform: string
url?: string | undefined
}[]
},
customUnidata?: Unidata,
newbieToken?: string,
) {
const { default: unidata } = await import("~/queries/unidata.server")
return await (customUnidata || unidata).profiles.set(
{
source: "Crossbell Profile",
@@ -266,56 +184,8 @@ export async function updateSite(
)
}
export async function createSite(
address: string,
payload: { name: string; subdomain: string },
customUnidata?: Unidata,
) {
return await (customUnidata || unidata).profiles.set(
{
source: "Crossbell Profile",
identity: address,
platform: "Ethereum",
action: "add",
},
{
username: payload.subdomain,
name: payload.name,
tags: [
"navigation:" +
JSON.stringify([
{
id: nanoid(),
label: "Archives",
url: "/archives",
},
]),
],
},
)
}
export async function subscribeToSites(
input: {
user: Profile
sites: {
characterId: string
}[]
},
contract?: Contract,
) {
if (input.user.metadata?.proof) {
return contract?.linkCharactersInBatch(
input.user.metadata.proof,
input.sites.map((s) => s.characterId).filter((c) => c) as any,
[],
"follow",
)
}
}
export async function getCommentsBySite(input: {
characterId: string
characterId?: number
cursor?: string
}) {
const notes = await indexer.getNotes({
@@ -344,7 +214,7 @@ const xLogOperatorPermissions: CharacterOperatorPermission[] = [
export async function addOperator(
input: {
characterId: number
characterId?: number
operator: string
},
contract?: Contract,
@@ -416,15 +286,17 @@ export async function removeOperator(
}
}
export async function getNFTs(address: string, customUnidata?: Unidata) {
const assets = await (customUnidata || unidata).assets.get({
export async function getNFTs(address: string) {
const { default: unidata } = await import("~/queries/unidata.server")
const assets = await unidata.assets.get({
source: "Ethereum NFT",
identity: address,
})
return assets
}
export async function getStat({ characterId }: { characterId: string }) {
export async function getStat({ characterId }: { characterId: number }) {
if (characterId) {
const [stat, site, subscriptions, comments, notes] = await Promise.all([
(
@@ -571,7 +443,7 @@ export type AchievementSection = {
}[]
}
export async function getAchievements(characterId: string) {
export async function getAchievements(characterId: number) {
const crossbellAchievements = (await indexer.getAchievements(characterId))
?.list as AchievementSection[] | undefined
const xLogAchievements: AchievementSection[] = [
@@ -647,13 +519,13 @@ export async function getAchievements(characterId: string) {
}
export async function mintAchievement(input: {
characterId: string
characterId: number
achievementId: number
}) {
return indexer.mintAchievement(input.characterId, input.achievementId)
}
export async function getMiraBalance(characterId: string, contract: Contract) {
export async function getMiraBalance(characterId: number, contract: Contract) {
const decimals = await getMiraTokenDecimals(contract)
const result = await contract.getMiraBalanceOfCharacter(characterId)
result.data = (