Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

7.2 KB
Raw Blame
import { TRPCError } from '@trpc/server';
import { z } from 'zod';

import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { GenerationTopicModel } from '@/database/models/generationTopic';
import { type GenerationTopicItem } from '@/database/schemas/generation';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
import { GenerationService } from '@/server/services/generation';

import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';

const generationTopicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
  const { ctx } = opts;
  const wsId = ctx.workspaceId ?? undefined;

  return opts.next({
    ctx: {
      fileService: new FileService(ctx.serverDB, ctx.userId, wsId),
      generationService: new GenerationService(ctx.serverDB, ctx.userId, wsId),
      generationTopicModel: new GenerationTopicModel(ctx.serverDB, ctx.userId, wsId),
    },
  });
});

// Define input schemas
const updateTopicSchema = z.object({
  id: z.string(),
  // No `coverUrl`: it must only reference cover objects the server created
  // (`updateTopicCover` / generation success), because cover replacement and
  // topic deletion delete that key from storage. An arbitrary key here would
  // let a caller delete objects they do not own.
  value: z.object({
    title: z.string().nullish(),
  }),
});

const updateTopicCoverSchema = z.object({
  coverUrl: z.string(),
  id: z.string(),
});

export const generationTopicRouter = router({
  createTopic: generationTopicProcedure
    .use(withScopedPermission('topic:create'))
    .input(
      z
        .object({
          title: z.string().trim().min(1).max(100).optional(),
          type: z.enum(['image', 'music', 'video']).optional(),
          visibility: z.enum(['private', 'public']).optional(),
        })
        .optional(),
    )
    .mutation(async ({ ctx, input }) => {
      const data = await ctx.generationTopicModel.create(
        input?.title ?? '',
        input?.type,
        input?.visibility,
      );
      return data.id;
    }),
  deleteTopic: generationTopicProcedure
    .use(withScopedPermission('topic:delete'))
    .input(z.object({ id: z.string() }))
    .mutation(async ({ ctx, input }) => {
      const topic = await ctx.generationTopicModel.findById(input.id);
      // Missing row → keep the delete idempotent, nothing to authorize.
      if (!topic) return;
      assertWorkspaceRowManageable(ctx, topic.userId, 'generation topic');

      // 1. Delete database records and get file URLs to clean
      const result = await ctx.generationTopicModel.delete(input.id);

      // If topic not found, throw an error instead of returning undefined
      if (!result) {
        return;
      }

      const { deletedTopic, filesToDelete } = result;

      // 2. Clean up all files from S3 (cover image and thumbnails)
      // Note: Even if file deletion fails, we consider the topic deletion successful
      // since the database record has been removed and users won't see the topic anymore
      if (filesToDelete.length > 0) {
        try {
          await ctx.fileService.deleteFiles(filesToDelete);
        } catch (error) {
          // Log the error but don't throw - file cleanup failure shouldn't affect
          // the user experience since the database operation succeeded
          console.error('Failed to delete files from S3:', error);
        }
      }

      return deletedTopic;
    }),
  getAllGenerationTopics: generationTopicProcedure
    .input(z.object({ type: z.enum(['image', 'music', 'video']).optional() }).optional())
    .query(async ({ ctx, input }) => {
      return ctx.generationTopicModel.queryAll(input?.type);
    }),
  updateTopic: generationTopicProcedure
    .use(withScopedPermission('topic:update'))
    .input(updateTopicSchema)
    .mutation(async ({ ctx, input }) => {
      const topic = await ctx.generationTopicModel.findById(input.id);
      if (!topic) {
        throw new TRPCError({ code: 'NOT_FOUND', message: 'Generation topic not found' });
      }
      assertWorkspaceRowManageable(ctx, topic.userId, 'generation topic');

      return ctx.generationTopicModel.update(input.id, input.value as Partial<GenerationTopicItem>);
    }),
  updateTopicCover: generationTopicProcedure
    .use(withScopedPermission('topic:update'))
    .input(updateTopicCoverSchema)
    .mutation(async ({ ctx, input }) => {
      const topic = await ctx.generationTopicModel.findById(input.id);
      if (!topic) {
        throw new TRPCError({ code: 'NOT_FOUND', message: 'Generation topic not found' });
      }
      assertWorkspaceRowManageable(ctx, topic.userId, 'generation topic');

      // Process the cover image and get key
      const newCoverKey = await ctx.generationService.createCoverFromUrl(input.coverUrl);

      // Update the topic with the new cover key
      const replaced = await ctx.generationTopicModel.replaceCover(input.id, newCoverKey);
      const previousCoverUrl = replaced?.previousCoverUrl;

      // Each cover is a dedicated object, so a replaced one is unreachable once the
      // topic points elsewhere (e.g. an older client overwriting a server-set cover).
      // Use the cover the update displaced, not the one read before the upload:
      // another cover may have been set in between.
      if (previousCoverUrl && previousCoverUrl !== newCoverKey) {
        try {
          await ctx.fileService.deleteFile(previousCoverUrl);
        } catch (error) {
          console.error('[generationTopic] Failed to delete replaced cover:', error);
        }
      }

      return replaced?.topic;
    }),

  /**
   * Toggle a generation topic's workspace visibility. Creator-only. Personal
   * mode has no workspace visibility concept, so the call is rejected there.
   */
  setTopicVisibility: generationTopicProcedure
    .use(withScopedPermission('topic:update'))
    .input(
      z.object({
        id: z.string(),
        visibility: z.enum(['private', 'public']),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      if (!ctx.workspaceId) {
        throw new TRPCError({
          code: 'BAD_REQUEST',
          message: 'Generation topic visibility only applies inside a workspace',
        });
      }

      const topic = await ctx.generationTopicModel.findById(input.id);
      if (!topic) {
        throw new TRPCError({ code: 'NOT_FOUND', message: 'Generation topic not found' });
      }

      if (topic.userId !== ctx.userId) {
        throw new TRPCError({
          code: 'FORBIDDEN',
          message: 'Only the creator can change a generation topic’s visibility',
        });
      }

      if (topic.visibility === input.visibility) return { success: true };

      await ctx.generationTopicModel.setVisibility(input.id, input.visibility);
      return { success: true };
    }),
});

export type GenerationTopicRouter = typeof generationTopicRouter;

// Export input types for client/server service consistency
export type UpdateTopicInput = z.infer<typeof updateTopicSchema>;
export type UpdateTopicValue = UpdateTopicInput['value'];
export type UpdateTopicCoverInput = z.infer<typeof updateTopicCoverSchema>;