import { users, socialPages, media, posts, postMedia, scheduledPosts, aiGenerations, cloudinaryConfig, openrouterConfig, userPagePermissions, type User, type InsertUser, type SocialPage, type InsertSocialPage, type Media, type InsertMedia, type Post, type InsertPost, type PostMedia, type ScheduledPost, type InsertScheduledPost, type AiGeneration, type InsertAiGeneration, type CloudinaryConfig, type InsertCloudinaryConfig, type OpenrouterConfig, type InsertOpenrouterConfig, type UserPagePermission, type InsertUserPagePermission, musicFavorites, type MusicFavorite, type InsertMusicFavorite, freesoundConfig, type FreesoundConfig, type InsertFreesoundConfig, audioTracks, type AudioTrack, type InsertAudioTrack, } from "@shared/schema"; import { db } from "./db"; import { eq, and, gte, lte, desc, asc, isNull, inArray } from "drizzle-orm"; import { encrypt, decrypt, isEncrypted } from "./utils/encryption"; export interface IStorage { // Users getUser(id: string): Promise; getUserByUsername(username: string): Promise; getAllUsers(): Promise; createUser(user: InsertUser): Promise; updateUser(id: string, user: Partial): Promise; deleteUser(id: string): Promise; // Social Pages getSocialPages(userId: string): Promise; getSocialPage(id: string): Promise; createSocialPage(page: InsertSocialPage): Promise; updateSocialPage(id: string, page: Partial): Promise; deleteSocialPage(id: string): Promise; // Media getMedia(userId: string): Promise; getMediaById(id: string): Promise; createMedia(media: InsertMedia): Promise; deleteMedia(id: string): Promise; getPostMedia(postId: string): Promise; // Posts getPosts(userId: string): Promise; getPost(id: string): Promise; getPostWithMedia(id: string): Promise<{ post: Post; media: Media[] } | undefined>; createPost(post: InsertPost): Promise; updatePost(id: string, post: Partial): Promise; updatePostGenerationStatus(id: string, status: string, progress: number, error?: string): Promise; deletePost(id: string): Promise; updatePostMedia(postId: string, mediaIds: string[]): Promise; countProcessingReels(): Promise; getNextPendingReel(): Promise; // Scheduled Posts getScheduledPosts(userId: string, startDate?: Date, endDate?: Date): Promise; getScheduledPostsByPages(pageIds: string[], startDate?: Date, endDate?: Date): Promise; getScheduledPost(id: string): Promise; getScheduledPostsByPost(postId: string): Promise; createScheduledPost(scheduledPost: InsertScheduledPost): Promise; updateScheduledPost(id: string, scheduledPost: Partial): Promise; deleteScheduledPost(id: string): Promise; getPendingScheduledPosts(): Promise; // AI Generations getAiGenerations(userId: string): Promise; createAiGeneration(generation: InsertAiGeneration): Promise; // Cloudinary Config getCloudinaryConfig(): Promise; createCloudinaryConfig(config: InsertCloudinaryConfig): Promise; updateCloudinaryConfig(config: Partial): Promise; // OpenRouter Config getOpenrouterConfig(userId: string): Promise; getAnyOpenrouterConfig(): Promise; createOpenrouterConfig(config: InsertOpenrouterConfig): Promise; updateOpenrouterConfig(userId: string, config: Partial): Promise; // User Page Permissions getUserPagePermissions(userId: string): Promise; getPagePermissions(pageId: string): Promise; createPagePermission(permission: InsertUserPagePermission): Promise; deletePagePermission(userId: string, pageId: string): Promise; deleteAllUserPagePermissions(userId: string): Promise; getUserAccessiblePages(userId: string): Promise; // Music Favorites getMusicFavorites(userId: string): Promise; addMusicFavorite(favorite: InsertMusicFavorite): Promise; removeMusicFavorite(userId: string, trackId: string): Promise; isMusicFavorite(userId: string, trackId: string): Promise; // Audio Tracks getAudioTracks(): Promise; getAudioTrack(id: string): Promise; createAudioTrack(track: InsertAudioTrack): Promise; deleteAudioTrack(id: string): Promise; // Freesound Config getFreesoundConfig(userId: string): Promise; createFreesoundConfig(config: InsertFreesoundConfig): Promise; updateFreesoundConfig(userId: string, config: Partial): Promise; } export class DatabaseStorage implements IStorage { // Users async getUser(id: string): Promise { const [user] = await db.select().from(users).where(eq(users.id, id)); return user || undefined; } async getUserByUsername(username: string): Promise { const [user] = await db.select().from(users).where(eq(users.username, username)); return user || undefined; } async getAllUsers(): Promise { return await db.select().from(users); } async createUser(insertUser: InsertUser): Promise { const [user] = await db.insert(users).values(insertUser).returning(); return user; } async updateUser(id: string, updateData: Partial): Promise { const [updated] = await db.update(users).set(updateData).where(eq(users.id, id)).returning(); return updated; } async deleteUser(id: string): Promise { await db.delete(users).where(eq(users.id, id)); } // Social Pages async getSocialPages(userId: string): Promise { const pages = await db.select().from(socialPages).where(eq(socialPages.userId, userId)); // Déchiffrer les tokens pour chaque page return pages.map(page => ({ ...page, accessToken: decrypt(page.accessToken) })); } async getSocialPage(id: string): Promise { const [page] = await db.select().from(socialPages).where(eq(socialPages.id, id)); if (page) { // Déchiffrer le token page.accessToken = decrypt(page.accessToken); } return page || undefined; } async createSocialPage(page: InsertSocialPage): Promise { // Chiffrer le token avant stockage const encryptedPage = { ...page, accessToken: encrypt(page.accessToken) }; const [newPage] = await db.insert(socialPages).values(encryptedPage).returning(); // Retourner avec le token déchiffré newPage.accessToken = decrypt(newPage.accessToken); return newPage; } async updateSocialPage(id: string, page: Partial): Promise { // Chiffrer le token si présent dans la mise à jour const updateData = page.accessToken ? { ...page, accessToken: encrypt(page.accessToken) } : page; const [updated] = await db.update(socialPages).set(updateData).where(eq(socialPages.id, id)).returning(); // Retourner avec le token déchiffré updated.accessToken = decrypt(updated.accessToken); return updated; } async deleteSocialPage(id: string): Promise { await db.delete(socialPages).where(eq(socialPages.id, id)); } // Media async getMedia(userId: string): Promise { return await db.select().from(media).where(eq(media.userId, userId)).orderBy(desc(media.createdAt)); } async getMediaById(id: string): Promise { const [mediaItem] = await db.select().from(media).where(eq(media.id, id)); return mediaItem || undefined; } async createMedia(mediaItem: InsertMedia): Promise { const [newMedia] = await db.insert(media).values(mediaItem).returning(); return newMedia; } async deleteMedia(id: string): Promise { await db.delete(media).where(eq(media.id, id)); } async getPostMedia(postId: string): Promise { return await db.select().from(postMedia).where(eq(postMedia.postId, postId)).orderBy(asc(postMedia.displayOrder)); } // Posts async getPosts(userId: string): Promise { return await db.select().from(posts).where(eq(posts.userId, userId)).orderBy(desc(posts.createdAt)); } async getPost(id: string): Promise { const [post] = await db.select().from(posts).where(eq(posts.id, id)); return post || undefined; } async getPostWithMedia(id: string): Promise<{ post: Post; media: Media[] } | undefined> { const post = await this.getPost(id); if (!post) return undefined; const postMediaLinks = await this.getPostMedia(id); const mediaItems: Media[] = []; for (const link of postMediaLinks) { const mediaItem = await this.getMediaById(link.mediaId); if (mediaItem) { mediaItems.push(mediaItem); } } return { post, media: mediaItems }; } async createPost(post: InsertPost): Promise { const [newPost] = await db.insert(posts).values(post).returning(); return newPost; } async updatePost(id: string, post: Partial): Promise { const [updated] = await db.update(posts).set({ ...post, updatedAt: new Date() }).where(eq(posts.id, id)).returning(); return updated; } async deletePost(id: string): Promise { await db.delete(posts).where(eq(posts.id, id)); } async updatePostGenerationStatus( id: string, status: string, progress: number, error?: string ): Promise { const updateData: Record = { generationStatus: status, generationProgress: progress, updatedAt: new Date(), }; if (error !== undefined) { updateData.generationError = error; } const [updated] = await db .update(posts) .set(updateData) .where(eq(posts.id, id)) .returning(); return updated; } async updatePostMedia(postId: string, mediaIds: string[]): Promise { await db.delete(postMedia).where(eq(postMedia.postId, postId)); if (mediaIds.length > 0) { const postMediaEntries = mediaIds.map((mediaId, index) => ({ postId, mediaId, displayOrder: index, })); await db.insert(postMedia).values(postMediaEntries); } } async countProcessingReels(): Promise { const processing = await db .select() .from(posts) .where(eq(posts.generationStatus, "processing")); return processing.length; } async getNextPendingReel(): Promise { const [post] = await db .select() .from(posts) .where(eq(posts.generationStatus, "pending")) .orderBy(asc(posts.createdAt)) .limit(1); return post || undefined; } // Scheduled Posts async getScheduledPosts(userId: string, startDate?: Date, endDate?: Date): Promise { let query = db .select() .from(scheduledPosts) .innerJoin(posts, eq(scheduledPosts.postId, posts.id)) .leftJoin(socialPages, eq(scheduledPosts.pageId, socialPages.id)) .where(eq(posts.userId, userId)); if (startDate && endDate) { const results = await query; return results .filter(r => { const scheduledAt = new Date(r.scheduled_posts.scheduledAt); return scheduledAt >= startDate && scheduledAt <= endDate; }) .map(r => ({ ...r.scheduled_posts, post: r.posts, page: r.social_pages, })); } const results = await query; return results.map(r => ({ ...r.scheduled_posts, post: r.posts, page: r.social_pages, })); } async getScheduledPostsByPages(pageIds: string[], startDate?: Date, endDate?: Date): Promise { if (pageIds.length === 0) { return []; } let query = db .select() .from(scheduledPosts) .innerJoin(posts, eq(scheduledPosts.postId, posts.id)) .leftJoin(socialPages, eq(scheduledPosts.pageId, socialPages.id)) .where(inArray(scheduledPosts.pageId, pageIds)); if (startDate && endDate) { const results = await query; return results .filter(r => { const scheduledAt = new Date(r.scheduled_posts.scheduledAt); return scheduledAt >= startDate && scheduledAt <= endDate; }) .map(r => ({ ...r.scheduled_posts, post: r.posts, page: r.social_pages, })); } const results = await query; return results.map(r => ({ ...r.scheduled_posts, post: r.posts, page: r.social_pages, })); } async getScheduledPost(id: string): Promise { const [scheduledPost] = await db.select().from(scheduledPosts).where(eq(scheduledPosts.id, id)); return scheduledPost || undefined; } async getScheduledPostsByPost(postId: string): Promise { return await db.select().from(scheduledPosts).where(eq(scheduledPosts.postId, postId)); } async createScheduledPost(scheduledPost: InsertScheduledPost): Promise { const [newScheduledPost] = await db.insert(scheduledPosts).values(scheduledPost).returning(); return newScheduledPost; } async updateScheduledPost(id: string, scheduledPost: Partial): Promise { const [updated] = await db.update(scheduledPosts).set(scheduledPost).where(eq(scheduledPosts.id, id)).returning(); return updated; } async deleteScheduledPost(id: string): Promise { await db.delete(scheduledPosts).where(eq(scheduledPosts.id, id)); } async getPendingScheduledPosts(): Promise { const now = new Date(); const results = await db .select() .from(scheduledPosts) .where( and( isNull(scheduledPosts.publishedAt), lte(scheduledPosts.scheduledAt, now) ) ); return results; } // AI Generations async getAiGenerations(userId: string): Promise { return await db.select().from(aiGenerations).where(eq(aiGenerations.userId, userId)).orderBy(desc(aiGenerations.createdAt)); } async createAiGeneration(generation: InsertAiGeneration): Promise { const [newGeneration] = await db.insert(aiGenerations).values(generation).returning(); return newGeneration; } // Cloudinary Config async getCloudinaryConfig(): Promise { const [config] = await db.select().from(cloudinaryConfig).limit(1); return config || undefined; } async createCloudinaryConfig(config: InsertCloudinaryConfig): Promise { const [newConfig] = await db.insert(cloudinaryConfig).values(config).returning(); return newConfig; } async updateCloudinaryConfig(config: Partial): Promise { const existingConfig = await this.getCloudinaryConfig(); if (!existingConfig) throw new Error("Cloudinary config not initialized"); const [updated] = await db.update(cloudinaryConfig) .set({ ...config, updatedAt: new Date() }) .where(eq(cloudinaryConfig.id, existingConfig.id)) .returning(); return updated; } // OpenRouter Config async getOpenrouterConfig(userId: string): Promise { const [config] = await db.select().from(openrouterConfig).where(eq(openrouterConfig.userId, userId)); return config || undefined; } async getAnyOpenrouterConfig(): Promise { const [config] = await db.select().from(openrouterConfig).limit(1); return config || undefined; } async createOpenrouterConfig(config: InsertOpenrouterConfig): Promise { const [newConfig] = await db.insert(openrouterConfig).values(config).returning(); return newConfig; } async updateOpenrouterConfig(userId: string, config: Partial): Promise { const [updated] = await db.update(openrouterConfig) .set({ ...config, updatedAt: new Date() }) .where(eq(openrouterConfig.userId, userId)) .returning(); return updated; } // User Page Permissions async getUserPagePermissions(userId: string): Promise { return await db.select().from(userPagePermissions).where(eq(userPagePermissions.userId, userId)); } async getPagePermissions(pageId: string): Promise { return await db.select().from(userPagePermissions).where(eq(userPagePermissions.pageId, pageId)); } async createPagePermission(permission: InsertUserPagePermission): Promise { const [newPermission] = await db.insert(userPagePermissions).values(permission).returning(); return newPermission; } async deletePagePermission(userId: string, pageId: string): Promise { await db.delete(userPagePermissions).where( and( eq(userPagePermissions.userId, userId), eq(userPagePermissions.pageId, pageId) ) ); } async deleteAllUserPagePermissions(userId: string): Promise { await db.delete(userPagePermissions).where(eq(userPagePermissions.userId, userId)); } async getUserAccessiblePages(userId: string): Promise { const permissions = await db .select() .from(userPagePermissions) .innerJoin(socialPages, eq(userPagePermissions.pageId, socialPages.id)) .where(eq(userPagePermissions.userId, userId)); return permissions.map(p => p.social_pages); } // Music Favorites async getMusicFavorites(userId: string): Promise { return db.select().from(musicFavorites) .where(eq(musicFavorites.userId, userId)) .orderBy(desc(musicFavorites.createdAt)); } async addMusicFavorite(favorite: InsertMusicFavorite): Promise { const [created] = await db.insert(musicFavorites).values(favorite).returning(); return created; } async removeMusicFavorite(userId: string, trackId: string): Promise { await db.delete(musicFavorites).where( and( eq(musicFavorites.userId, userId), eq(musicFavorites.trackId, trackId) ) ); } async isMusicFavorite(userId: string, trackId: string): Promise { const [fav] = await db.select().from(musicFavorites).where( and( eq(musicFavorites.userId, userId), eq(musicFavorites.trackId, trackId) ) ); return !!fav; } // Audio Tracks async getAudioTracks(): Promise { return db.select().from(audioTracks).orderBy(desc(audioTracks.createdAt)); } async getAudioTrack(id: string): Promise { const [track] = await db.select().from(audioTracks).where(eq(audioTracks.id, id)); return track || undefined; } async createAudioTrack(track: InsertAudioTrack): Promise { const [newTrack] = await db.insert(audioTracks).values(track).returning(); return newTrack; } async deleteAudioTrack(id: string): Promise { await db.delete(audioTracks).where(eq(audioTracks.id, id)); } // Freesound Config async getFreesoundConfig(userId: string): Promise { const [config] = await db.select().from(freesoundConfig).where(eq(freesoundConfig.userId, userId)); return config || undefined; } async createFreesoundConfig(config: InsertFreesoundConfig): Promise { const [newConfig] = await db.insert(freesoundConfig).values(config).returning(); return newConfig; } async updateFreesoundConfig(userId: string, config: Partial): Promise { const [updated] = await db.update(freesoundConfig) .set({ ...config, updatedAt: new Date() }) .where(eq(freesoundConfig.userId, userId)) .returning(); return updated; } } export const storage = new DatabaseStorage();