so now we're on fly.io
This commit is contained in:
@@ -0,0 +1,326 @@
|
||||
import { nanoid } from "nanoid"
|
||||
import {
|
||||
prismaPrimary,
|
||||
Prisma,
|
||||
prismaRead,
|
||||
PageType,
|
||||
MembershipRole,
|
||||
} from "~/lib/db.server"
|
||||
import { type Gate } from "~/lib/gate.server"
|
||||
import { sendEmailForNewPost } from "~/lib/mailgun.server"
|
||||
import { getAutoExcerpt, renderPageContent } from "~/lib/markdown.server"
|
||||
import { notFound } from "~/lib/server-side-props"
|
||||
import { PageVisibilityEnum } from "~/lib/types"
|
||||
import { isUUID } from "~/lib/uuid"
|
||||
import { getSite } from "./site.model"
|
||||
|
||||
const checkPageSlug = async ({
|
||||
slug,
|
||||
excludePage,
|
||||
siteId,
|
||||
}: {
|
||||
slug: string
|
||||
excludePage?: string
|
||||
siteId: string
|
||||
}) => {
|
||||
if (!slug) {
|
||||
throw new Error("Missing page slug")
|
||||
}
|
||||
const page = await prismaPrimary.page.findFirst({
|
||||
where: {
|
||||
siteId,
|
||||
slug,
|
||||
id: excludePage && {
|
||||
not: excludePage,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!page) return
|
||||
|
||||
if (page.deletedAt) {
|
||||
await prismaPrimary.page.delete({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
throw new Error("Page slug already used")
|
||||
}
|
||||
|
||||
export async function createOrUpdatePage(
|
||||
gate: Gate,
|
||||
input: {
|
||||
pageId?: string
|
||||
siteId: string
|
||||
slug?: string
|
||||
title?: string
|
||||
content?: string
|
||||
published?: boolean
|
||||
publishedAt?: string
|
||||
excerpt?: string
|
||||
isPost?: boolean
|
||||
}
|
||||
) {
|
||||
const page = input.pageId
|
||||
? await prismaPrimary.page.findUnique({
|
||||
where: {
|
||||
id: input.pageId,
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
: await prismaPrimary.page.create({
|
||||
data: {
|
||||
title: "Untitled",
|
||||
slug: `untitled-${nanoid(4)}`,
|
||||
site: {
|
||||
connect: {
|
||||
id: input.siteId,
|
||||
},
|
||||
},
|
||||
content: "",
|
||||
excerpt: "",
|
||||
autoExcerpt: "",
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!page || page.deletedAt) {
|
||||
throw new Error(`Page not found`)
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-create-page", siteId: page.siteId })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
const slug = input.slug || page.slug
|
||||
await checkPageSlug({ slug, excludePage: page.id, siteId: page.siteId })
|
||||
|
||||
const autoExcerpt = input.content ? getAutoExcerpt(input.content) : undefined
|
||||
|
||||
const updated = await prismaPrimary.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
title: input.title,
|
||||
content: input.content,
|
||||
published: input.published,
|
||||
publishedAt: input.publishedAt && new Date(input.publishedAt),
|
||||
excerpt: input.excerpt,
|
||||
slug,
|
||||
type: input.isPost ? "POST" : "PAGE",
|
||||
autoExcerpt,
|
||||
},
|
||||
})
|
||||
|
||||
if (
|
||||
updated.type === PageType.POST &&
|
||||
!updated.subscribersNotifiedAt &&
|
||||
updated.published &&
|
||||
updated.publishedAt <= new Date()
|
||||
) {
|
||||
await notifySubscribersForNewPost(gate, {
|
||||
pageId: updated.id,
|
||||
})
|
||||
}
|
||||
|
||||
return { page: updated }
|
||||
}
|
||||
|
||||
export async function getPagesBySite(
|
||||
gate: Gate,
|
||||
input: {
|
||||
site: string
|
||||
type: "post" | "page"
|
||||
visibility?: PageVisibilityEnum | null
|
||||
take?: number | null
|
||||
cursor?: string | null
|
||||
autoExcerpt?: boolean
|
||||
}
|
||||
) {
|
||||
const site = await getSite(input.site)
|
||||
|
||||
const visibility = input.visibility || PageVisibilityEnum.Published
|
||||
|
||||
if (!gate.allows({ type: "can-list-page", visibility, siteId: site.id })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
const where: Prisma.PageWhereInput = {
|
||||
siteId: site.id,
|
||||
deletedAt: null,
|
||||
type: input.type === "post" ? "POST" : "PAGE",
|
||||
}
|
||||
if (visibility === PageVisibilityEnum.Published) {
|
||||
where.published = true
|
||||
where.publishedAt = {
|
||||
lte: now,
|
||||
}
|
||||
} else if (visibility === PageVisibilityEnum.Scheduled) {
|
||||
where.published = true
|
||||
where.publishedAt = {
|
||||
gt: now,
|
||||
}
|
||||
} else if (visibility === PageVisibilityEnum.Draft) {
|
||||
where.published = false
|
||||
}
|
||||
|
||||
const take = input.take || 100
|
||||
const [nodes, total] = await Promise.all([
|
||||
prismaRead.page.findMany({
|
||||
where,
|
||||
orderBy: {
|
||||
publishedAt: "desc",
|
||||
},
|
||||
take: take + 1,
|
||||
cursor: input.cursor
|
||||
? {
|
||||
id: input.cursor,
|
||||
}
|
||||
: undefined,
|
||||
}),
|
||||
await prismaRead.page.count({
|
||||
where: {
|
||||
siteId: site.id,
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
const hasMore = nodes.length > take
|
||||
|
||||
return {
|
||||
nodes: nodes,
|
||||
total,
|
||||
hasMore,
|
||||
}
|
||||
}
|
||||
|
||||
export async function deletePage(gate: Gate, { id }: { id: string }) {
|
||||
const page = await prismaPrimary.page.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
})
|
||||
|
||||
if (!page) {
|
||||
throw notFound("page not found")
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-delete-page", siteId: page.siteId })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
await prismaPrimary.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getPage(
|
||||
gate: Gate,
|
||||
input: {
|
||||
/** page slug or id, `site` is needed when `page` is a slug */
|
||||
page: string
|
||||
site?: string
|
||||
renderContent?: boolean
|
||||
}
|
||||
) {
|
||||
const site = input.site ? await getSite(input.site) : null
|
||||
|
||||
if (input.site && !site) {
|
||||
throw notFound(`site not found`)
|
||||
}
|
||||
|
||||
const isPageUUID = isUUID(input.page)
|
||||
if (!isPageUUID && !input.site) {
|
||||
throw new Error("input.site is required because input.page is a slug")
|
||||
}
|
||||
|
||||
const page = isPageUUID
|
||||
? await prismaRead.page.findUnique({
|
||||
where: {
|
||||
id: input.page,
|
||||
},
|
||||
})
|
||||
: site
|
||||
? await prismaRead.page.findFirst({
|
||||
where: { siteId: site.id, slug: input.page },
|
||||
})
|
||||
: null
|
||||
|
||||
if (!page || page.deletedAt) {
|
||||
throw notFound(`page ${input.page} not found`)
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-read-page", page })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
if (input.renderContent) {
|
||||
const rendered = await renderPageContent(page.content)
|
||||
page.content = rendered.html
|
||||
}
|
||||
|
||||
return page
|
||||
}
|
||||
|
||||
export const notifySubscribersForNewPost = async (
|
||||
gate: Gate,
|
||||
input: {
|
||||
pageId: string
|
||||
}
|
||||
) => {
|
||||
const page = await getPage(gate, { page: input.pageId, renderContent: true })
|
||||
const site = await getSite(page.siteId)
|
||||
|
||||
if (!gate.allows({ type: "can-notify-site-subscribers", site })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
if (page.subscribersNotifiedAt) {
|
||||
throw new Error("You have already notified subscribers for this post")
|
||||
}
|
||||
|
||||
const memberships = await prismaPrimary.membership.findMany({
|
||||
where: {
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
siteId: site.id,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (memberships.length === 0) return
|
||||
|
||||
await prismaPrimary.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
subscribersNotifiedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
const emailSubscribers = memberships
|
||||
.filter((member) => (member.config as Prisma.JsonObject).email)
|
||||
.map((member) => member.user)
|
||||
|
||||
await sendEmailForNewPost({
|
||||
post: page,
|
||||
site,
|
||||
subscribers: emailSubscribers,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
import { prismaPrimary, prismaRead } from "~/lib/db.server"
|
||||
import { isUUID } from "~/lib/uuid"
|
||||
import { MembershipRole, PageType, type Site } from "~/lib/db.server"
|
||||
import { Gate } from "~/lib/gate.server"
|
||||
import dayjs from "dayjs"
|
||||
import { sendLoginEmail } from "~/lib/mailgun.server"
|
||||
import { SiteNavigationItem, SubscribeFormData } from "~/lib/types"
|
||||
import { nanoid } from "nanoid"
|
||||
|
||||
export const checkSubdomain = async ({
|
||||
subdomain,
|
||||
updatingSiteId,
|
||||
}: {
|
||||
subdomain: string
|
||||
updatingSiteId?: string
|
||||
}) => {
|
||||
const existingSite = await prismaPrimary.site.findUnique({
|
||||
where: {
|
||||
subdomain,
|
||||
},
|
||||
})
|
||||
|
||||
if (existingSite?.deletedAt) {
|
||||
// Actuall delete the site so that the subdomain can be used again
|
||||
await prismaPrimary.site.delete({
|
||||
where: {
|
||||
id: existingSite.id,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (existingSite && (!updatingSiteId || existingSite.id !== updatingSiteId)) {
|
||||
throw new Error(`Subdomain already taken`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSitesForViewer(gate: Gate) {
|
||||
const user = gate.getUser(true)
|
||||
const sites = await getSitesByUser({ userId: user.id })
|
||||
return sites
|
||||
}
|
||||
|
||||
export const getUserLastActiveSite = async (userId: string) => {
|
||||
const memberships = await prismaPrimary.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
in: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
orderBy: {
|
||||
lastSwitchedTo: "desc",
|
||||
},
|
||||
})
|
||||
|
||||
const site = memberships[0]?.site
|
||||
|
||||
if (!site || site.deletedAt) return null
|
||||
|
||||
return site
|
||||
}
|
||||
|
||||
export const getSite = async (input: string) => {
|
||||
const site = isUUID(input)
|
||||
? await prismaRead.site.findUnique({
|
||||
where: {
|
||||
id: input,
|
||||
},
|
||||
})
|
||||
: await prismaRead.site.findUnique({
|
||||
where: {
|
||||
subdomain: input,
|
||||
},
|
||||
})
|
||||
|
||||
if (!site || site.deletedAt) {
|
||||
throw new Error(`Site not found`)
|
||||
}
|
||||
|
||||
return site as Omit<Site, "navigation"> & {
|
||||
navigation: SiteNavigationItem[] | null
|
||||
}
|
||||
}
|
||||
|
||||
export const getMembership = async (data: {
|
||||
siteId: string
|
||||
userId: string
|
||||
role: MembershipRole
|
||||
}) => {
|
||||
const first = await prismaRead.membership.findFirst({
|
||||
where: {
|
||||
role: data.role,
|
||||
userId: data.userId,
|
||||
siteId: data.siteId,
|
||||
},
|
||||
})
|
||||
|
||||
return first
|
||||
}
|
||||
|
||||
export const getSitesByUser = async ({ userId }: { userId: string }) => {
|
||||
const memberships = await prismaRead.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
in: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
return memberships.map((m) => m.site)
|
||||
}
|
||||
|
||||
export const getSubscription = async (data: {
|
||||
userId: string
|
||||
siteId: string
|
||||
}) => {
|
||||
const membership = await getMembership({
|
||||
...data,
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
})
|
||||
if (!membership) return
|
||||
const config = membership.config as any
|
||||
return {
|
||||
...membership,
|
||||
config: config && {
|
||||
telegram: config.telegram,
|
||||
email: config.email,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateSite(
|
||||
gate: Gate,
|
||||
payload: {
|
||||
site: string
|
||||
name?: string
|
||||
description?: string
|
||||
icon?: string | null
|
||||
subdomain?: string
|
||||
navigation?: SiteNavigationItem[]
|
||||
}
|
||||
) {
|
||||
const site = await getSite(payload.site)
|
||||
|
||||
if (!gate.allows({ type: "can-update-site", site })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
if (payload.subdomain) {
|
||||
await checkSubdomain({
|
||||
subdomain: payload.subdomain,
|
||||
updatingSiteId: site.id,
|
||||
})
|
||||
}
|
||||
|
||||
const updated = await prismaPrimary.site.update({
|
||||
where: {
|
||||
id: site.id,
|
||||
},
|
||||
data: {
|
||||
name: payload.name,
|
||||
subdomain: payload.subdomain,
|
||||
description: payload.description,
|
||||
icon: payload.icon,
|
||||
navigation: payload.navigation,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
site: updated,
|
||||
subdomainUpdated: updated.subdomain !== site.subdomain,
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSite(
|
||||
gate: Gate,
|
||||
payload: { name: string; subdomain: string }
|
||||
) {
|
||||
const user = gate.getUser(true)
|
||||
await checkSubdomain({ subdomain: payload.subdomain })
|
||||
|
||||
const navigation: SiteNavigationItem[] = [
|
||||
{
|
||||
id: nanoid(),
|
||||
label: "About",
|
||||
url: "/about",
|
||||
},
|
||||
{
|
||||
id: nanoid(),
|
||||
label: "Archives",
|
||||
url: "/archives",
|
||||
},
|
||||
]
|
||||
const site = await prismaPrimary.site.create({
|
||||
data: {
|
||||
name: payload.name,
|
||||
subdomain: payload.subdomain,
|
||||
navigation,
|
||||
memberships: {
|
||||
create: {
|
||||
role: MembershipRole.OWNER,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
create: {
|
||||
title: "About",
|
||||
slug: "about",
|
||||
excerpt: "",
|
||||
autoExcerpt: "",
|
||||
content: `My name is ${payload.name} and I'm a new site.`,
|
||||
published: true,
|
||||
publishedAt: new Date(),
|
||||
type: PageType.PAGE,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return { site }
|
||||
}
|
||||
|
||||
export async function subscribeToSite(
|
||||
gate: Gate,
|
||||
input: {
|
||||
siteId: string
|
||||
email?: boolean
|
||||
telegram?: boolean
|
||||
newUser?: {
|
||||
email: string
|
||||
url: string
|
||||
}
|
||||
}
|
||||
) {
|
||||
const { newUser } = input
|
||||
if (newUser) {
|
||||
// Create the login token instead
|
||||
const subscribeFormData: SubscribeFormData = {
|
||||
email: input.email,
|
||||
telegram: input.telegram,
|
||||
siteId: input.siteId,
|
||||
}
|
||||
const loginToken = await prismaPrimary.loginToken.create({
|
||||
data: {
|
||||
email: newUser.email,
|
||||
expiresAt: dayjs().add(10, "minutes").toDate(),
|
||||
subscribeForm: subscribeFormData,
|
||||
},
|
||||
})
|
||||
sendLoginEmail({
|
||||
token: loginToken.id,
|
||||
email: loginToken.email,
|
||||
url: newUser.url,
|
||||
subscribeForm: subscribeFormData,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const user = gate.getUser(true)
|
||||
|
||||
const site = await getSite(input.siteId)
|
||||
const subscription = await getSubscription({
|
||||
userId: user.id,
|
||||
siteId: site.id,
|
||||
})
|
||||
if (!subscription) {
|
||||
await prismaPrimary.membership.create({
|
||||
data: {
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
connect: {
|
||||
id: site.id,
|
||||
},
|
||||
},
|
||||
config: {
|
||||
email: input.email,
|
||||
telegram: input.telegram,
|
||||
},
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await prismaPrimary.membership.update({
|
||||
where: {
|
||||
id: subscription.id,
|
||||
},
|
||||
data: {
|
||||
config: {
|
||||
email: input.email,
|
||||
telegram: input.telegram,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function unsubscribeFromSite(
|
||||
gate: Gate,
|
||||
input: { siteId: string }
|
||||
) {
|
||||
const user = gate.getUser(true)
|
||||
|
||||
const subscription = await getSubscription({
|
||||
userId: user.id,
|
||||
siteId: input.siteId,
|
||||
})
|
||||
|
||||
if (!subscription) {
|
||||
throw new Error(`Subscription not found`)
|
||||
}
|
||||
|
||||
await prismaPrimary.membership.delete({
|
||||
where: {
|
||||
id: subscription.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { prismaPrimary } from "~/lib/db.server"
|
||||
import { Gate } from "~/lib/gate.server"
|
||||
|
||||
export const userModel = {
|
||||
async updateProfile(
|
||||
gate: Gate,
|
||||
payload: {
|
||||
name?: string
|
||||
username?: string
|
||||
avatar?: string
|
||||
bio?: string
|
||||
email?: string
|
||||
}
|
||||
) {
|
||||
const user = gate.getUser(true)
|
||||
|
||||
if (payload.email) {
|
||||
const userByEmail = await prismaPrimary.user.findUnique({
|
||||
where: {
|
||||
email: payload.email,
|
||||
},
|
||||
})
|
||||
if (userByEmail && userByEmail.id !== user.id) {
|
||||
throw new Error("email already in use")
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.username) {
|
||||
const userByUsername = await prismaPrimary.user.findUnique({
|
||||
where: {
|
||||
username: payload.username,
|
||||
},
|
||||
})
|
||||
if (userByUsername && userByUsername.id !== user.id) {
|
||||
throw new Error("username already in use")
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prismaPrimary.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
name: payload.name,
|
||||
avatar: payload.avatar,
|
||||
username: payload.username,
|
||||
email: payload.email,
|
||||
emailVerified: payload.email !== user.email ? null : undefined,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
updated,
|
||||
}
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user