Restored to '551aaee106c3dc6c34e10193d8683fa67e7f9bea'

Replit-Restored-To: 551aaee106
This commit is contained in:
sebastjanartic
2025-08-04 20:10:59 +00:00
parent bb26fd3cdc
commit 9b192c6e1b
27 changed files with 107 additions and 2599 deletions
+7 -37
View File
@@ -1,5 +1,4 @@
import { type Video, type InsertVideo } from "@shared/schema";
import crypto from 'crypto';
interface BunnyVideo {
guid: string;
@@ -23,13 +22,11 @@ export class BunnyService {
private apiKey: string;
private libraryId: string;
private hostname: string;
private securityKey: string;
constructor() {
this.apiKey = process.env.BUNNY_API_KEY!;
this.libraryId = process.env.BUNNY_LIBRARY_ID!;
this.hostname = process.env.BUNNY_HOSTNAME!;
this.securityKey = process.env.BUNNY_SECURITY_KEY || ''; // CDN security key for signing URLs
if (!this.apiKey || !this.libraryId || !this.hostname) {
throw new Error("Missing Bunny.net configuration");
@@ -54,41 +51,14 @@ export class BunnyService {
return response.json();
}
private generateSignedUrl(path: string, expiryHours: number = 1): string {
if (!this.securityKey) {
// If no security key, return iframe embed as fallback
const videoId = path.split('/')[1];
return `https://iframe.mediadelivery.net/embed/${this.libraryId}/${videoId}?controls=true&autoplay=false`;
}
const expireTimestamp = Math.floor(Date.now() / 1000) + (expiryHours * 3600);
// Bunny.net uses SHA256 for token generation according to docs
// hashableBase = securityKey + signaturePath + expires + userIp + parameterData
const hashableBase = `${this.securityKey}${path}${expireTimestamp}`;
const hash = crypto.createHash('sha256').update(hashableBase).digest();
const token = Buffer.from(hash).toString('base64')
.replace(/\n/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
return `https://${this.hostname}${path}?token=${token}&expires=${expireTimestamp}`;
}
// Public method for generating signed URLs for sharing
generatePublicSignedUrl(path: string, expiryHours: number = 1): string {
return this.generateSignedUrl(path, expiryHours);
}
private bunnyVideoToVideo(bunnyVideo: BunnyVideo): Video {
// Since Bunny.net private library token authentication is not working,
// use iframe embed approach for reliable video playback
const videoUrl = `https://iframe.mediadelivery.net/embed/${this.libraryId}/${bunnyVideo.guid}?controls=true&autoplay=false`;
// Use proxy endpoint that will try multiple thumbnail sources
const thumbnailUrl = `/thumbnail/${bunnyVideo.guid}`;
// For private videos, we'll generate a video poster frame from the iframe
// This is the best approach for private Bunny.net videos
const thumbnailUrl = `https://iframe.mediadelivery.net/embed/${this.libraryId}/${bunnyVideo.guid}?poster=true`;
// For private videos, we'll use an iframe embed URL which handles authentication
// Enable controls, allow fullscreen, and ensure player functionality
const videoUrl = `https://iframe.mediadelivery.net/embed/${this.libraryId}/${bunnyVideo.guid}?controls=true&autoplay=false&preload=metadata`;
return {
id: bunnyVideo.guid,
-15
View File
@@ -1,15 +0,0 @@
import { Pool, neonConfig } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-serverless';
import ws from "ws";
import * as schema from "@shared/schema";
neonConfig.webSocketConstructor = ws;
if (!process.env.DATABASE_URL) {
throw new Error(
"DATABASE_URL must be set. Did you forget to provision a database?",
);
}
export const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const db = drizzle({ client: pool, schema });
-335
View File
@@ -2,11 +2,8 @@ import type { Express } from "express";
import { createServer, type Server } from "http";
import { storage } from "./storage";
import { z } from "zod";
import { BunnyService } from "./bunny";
import { ThumbnailGenerator } from "./thumbnail-generator";
export async function registerRoutes(app: Express): Promise<Server> {
const thumbnailGenerator = new ThumbnailGenerator();
// Get videos with pagination and filtering
app.get("/api/videos", async (req, res) => {
try {
@@ -120,338 +117,6 @@ export async function registerRoutes(app: Express): Promise<Server> {
}
});
// Generate real thumbnail from video frame at specific time
app.get("/thumbnail/:videoId", async (req, res) => {
const timeStamp = req.query.t as string || "5"; // Default to 5 seconds
try {
const { videoId } = req.params;
// Get video info
const video = await storage.getVideo(videoId);
if (!video) {
return res.status(404).json({ message: "Video not found" });
}
// Try to generate real thumbnail from video
const thumbnailPath = await thumbnailGenerator.generateThumbnail({
videoId,
timeStamp,
width: 400,
height: 225,
quality: 85
});
if (thumbnailPath && require('fs').existsSync(thumbnailPath)) {
// Serve the generated thumbnail
res.setHeader('Content-Type', 'image/jpeg');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('Access-Control-Allow-Origin', '*');
return res.sendFile(require('path').resolve(thumbnailPath));
} else {
// Fallback to SVG if thumbnail generation fails
const displayTitle = video.title.replace('.mp4', '').substring(0, 40);
const duration = video.duration ? Math.floor(video.duration / 60) + ':' + String(video.duration % 60).padStart(2, '0') : '';
const svg = `
<svg width="400" height="225" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#374151;stop-opacity:1" />
<stop offset="100%" style="stop-color:#1f2937;stop-opacity:1" />
</linearGradient>
<filter id="shadow">
<feDropShadow dx="2" dy="2" stdDeviation="3"/>
</filter>
</defs>
<rect width="400" height="225" fill="url(#grad)" />
<!-- Video camera icon background -->
<circle cx="120" cy="80" r="25" fill="rgba(255,255,255,0.1)" />
<!-- Camera body -->
<rect x="108" y="72" width="18" height="12" rx="2" fill="rgba(255,255,255,0.6)" />
<!-- Camera lens -->
<circle cx="114" cy="78" r="3" fill="#374151" />
<!-- Camera viewfinder -->
<rect x="126" y="75" width="6" height="4" fill="rgba(255,255,255,0.6)" />
<!-- Play button circle -->
<circle cx="200" cy="112" r="35" fill="rgba(255,255,255,0.9)" filter="url(#shadow)" />
<!-- Play button triangle -->
<polygon points="188,97 188,127 218,112" fill="#374151" />
<!-- Title background -->
<rect x="0" y="175" width="400" height="50" fill="rgba(0,0,0,0.8)" />
<!-- Title text -->
<text x="20" y="200" fill="white" font-family="Arial, sans-serif" font-size="14" font-weight="bold">${displayTitle}</text>
<!-- Duration -->
${duration ? `<rect x="350" y="185" width="35" height="20" rx="3" fill="rgba(0,0,0,0.8)"/>
<text x="367" y="198" fill="white" font-family="Arial, sans-serif" font-size="11" text-anchor="middle">${duration}</text>` : ''}
<!-- Video type indicator -->
<text x="20" y="25" fill="rgba(255,255,255,0.7)" font-family="Arial, sans-serif" font-size="11">VIDEO</text>
</svg>
`;
res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('Access-Control-Allow-Origin', '*');
return res.send(svg);
}
} catch (error) {
console.error("Error creating thumbnail:", error);
res.status(500).json({ message: "Error generating thumbnail" });
}
});
// API endpoint to generate multiple thumbnails for video preview
app.post("/api/thumbnails/:videoId/generate", async (req, res) => {
try {
const { videoId } = req.params;
const { timestamps = ["5", "15", "30", "60"] } = req.body;
const video = await storage.getVideo(videoId);
if (!video) {
return res.status(404).json({ message: "Video not found" });
}
const thumbnailPaths = await thumbnailGenerator.generateMultipleThumbnails(videoId, timestamps);
const thumbnails = thumbnailPaths.map((path, index) => ({
timestamp: timestamps[index],
url: `/thumbnail/${videoId}?t=${timestamps[index]}`,
path: path
}));
res.json({ thumbnails });
} catch (error) {
console.error("Error generating thumbnails:", error);
res.status(500).json({ message: "Error generating thumbnails" });
}
});
// API endpoint to list existing thumbnails for a video
app.get("/api/thumbnails/:videoId", async (req, res) => {
try {
const { videoId } = req.params;
const thumbnailPaths = thumbnailGenerator.listThumbnails(videoId);
const thumbnails = thumbnailPaths.map(path => {
const filename = require('path').basename(path);
const match = filename.match(new RegExp(`${videoId}_(.+)_\\d+x\\d+\\.jpg`));
const timestamp = match ? match[1].replace(/-/g, ':') : 'unknown';
return {
timestamp,
url: `/thumbnail/${videoId}?t=${timestamp}`,
path: path
};
});
res.json({ thumbnails });
} catch (error) {
console.error("Error listing thumbnails:", error);
res.status(500).json({ message: "Error listing thumbnails" });
}
});
// User routes
app.get("/api/users/:id", async (req, res) => {
try {
const user = await storage.getUser(req.params.id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// Don't send password hash
const { passwordHash, ...safeUser } = user;
res.json(safeUser);
} catch (error) {
res.status(500).json({ message: "Failed to fetch user" });
}
});
app.post("/api/users", async (req, res) => {
try {
const userData = req.body;
const user = await storage.createUser(userData);
const { passwordHash, ...safeUser } = user;
res.status(201).json(safeUser);
} catch (error) {
res.status(500).json({ message: "Failed to create user" });
}
});
// Playlist routes
app.get("/api/playlists", async (req, res) => {
try {
const userId = req.query.userId as string;
const limit = parseInt(req.query.limit as string) || 20;
const offset = parseInt(req.query.offset as string) || 0;
if (!userId) {
return res.status(400).json({ message: "userId is required" });
}
const playlists = await storage.getPlaylists(userId, limit, offset);
res.json(playlists);
} catch (error) {
res.status(500).json({ message: "Failed to fetch playlists" });
}
});
app.get("/api/playlists/:id", async (req, res) => {
try {
const userId = req.query.userId as string;
const playlist = await storage.getPlaylist(req.params.id, userId);
if (!playlist) {
return res.status(404).json({ message: "Playlist not found" });
}
res.json(playlist);
} catch (error) {
res.status(500).json({ message: "Failed to fetch playlist" });
}
});
app.post("/api/playlists", async (req, res) => {
try {
const playlist = await storage.createPlaylist(req.body);
res.status(201).json(playlist);
} catch (error) {
res.status(500).json({ message: "Failed to create playlist" });
}
});
app.put("/api/playlists/:id", async (req, res) => {
try {
const userId = req.query.userId as string;
if (!userId) {
return res.status(400).json({ message: "userId is required" });
}
const playlist = await storage.updatePlaylist(req.params.id, req.body, userId);
if (!playlist) {
return res.status(404).json({ message: "Playlist not found or access denied" });
}
res.json(playlist);
} catch (error) {
res.status(500).json({ message: "Failed to update playlist" });
}
});
app.delete("/api/playlists/:id", async (req, res) => {
try {
const userId = req.query.userId as string;
if (!userId) {
return res.status(400).json({ message: "userId is required" });
}
const success = await storage.deletePlaylist(req.params.id, userId);
if (!success) {
return res.status(404).json({ message: "Playlist not found or access denied" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ message: "Failed to delete playlist" });
}
});
// Playlist videos routes
app.get("/api/playlists/:id/videos", async (req, res) => {
try {
const videos = await storage.getPlaylistVideos(req.params.id);
res.json(videos);
} catch (error) {
res.status(500).json({ message: "Failed to fetch playlist videos" });
}
});
app.post("/api/playlists/:id/videos", async (req, res) => {
try {
const playlistVideo = await storage.addVideoToPlaylist({
playlistId: req.params.id,
videoId: req.body.videoId,
position: req.body.position || 0
});
res.status(201).json(playlistVideo);
} catch (error) {
if (error instanceof Error && error.message.includes("already in playlist")) {
return res.status(409).json({ message: error.message });
}
res.status(500).json({ message: "Failed to add video to playlist" });
}
});
app.delete("/api/playlists/:playlistId/videos/:videoId", async (req, res) => {
try {
const success = await storage.removeVideoFromPlaylist(req.params.playlistId, req.params.videoId);
if (!success) {
return res.status(404).json({ message: "Video not found in playlist" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ message: "Failed to remove video from playlist" });
}
});
// Favorites routes
app.get("/api/favorites", async (req, res) => {
try {
const userId = req.query.userId as string;
const limit = parseInt(req.query.limit as string) || 20;
const offset = parseInt(req.query.offset as string) || 0;
if (!userId) {
return res.status(400).json({ message: "userId is required" });
}
const favorites = await storage.getUserFavorites(userId, limit, offset);
res.json(favorites);
} catch (error) {
res.status(500).json({ message: "Failed to fetch favorites" });
}
});
app.post("/api/favorites", async (req, res) => {
try {
const favorite = await storage.addToFavorites({
userId: req.body.userId,
videoId: req.body.videoId
});
res.status(201).json(favorite);
} catch (error) {
if (error instanceof Error && error.message.includes("already in favorites")) {
return res.status(409).json({ message: error.message });
}
res.status(500).json({ message: "Failed to add to favorites" });
}
});
app.delete("/api/favorites/:userId/:videoId", async (req, res) => {
try {
const success = await storage.removeFromFavorites(req.params.userId, req.params.videoId);
if (!success) {
return res.status(404).json({ message: "Favorite not found" });
}
res.json({ success: true });
} catch (error) {
res.status(500).json({ message: "Failed to remove from favorites" });
}
});
app.get("/api/favorites/:userId/:videoId", async (req, res) => {
try {
const isFavorited = await storage.isVideoFavorited(req.params.userId, req.params.videoId);
res.json({ isFavorited });
} catch (error) {
res.status(500).json({ message: "Failed to check favorite status" });
}
});
const httpServer = createServer(app);
return httpServer;
}
+4 -551
View File
@@ -1,69 +1,23 @@
import {
type Video,
type InsertVideo,
type User,
type InsertUser,
type Playlist,
type InsertPlaylist,
type PlaylistVideo,
type InsertPlaylistVideo,
type UserFavorite,
type InsertUserFavorite
} from "@shared/schema";
import { type Video, type InsertVideo } from "@shared/schema";
import { randomUUID } from "crypto";
import { BunnyService } from "./bunny";
export interface IStorage {
// Video operations
getVideos(limit?: number, offset?: number, search?: string, category?: string): Promise<Video[]>;
getVideo(id: string): Promise<Video | undefined>;
createVideo(video: InsertVideo): Promise<Video>;
updateVideoViews(id: string): Promise<void>;
getVideoCount(search?: string, category?: string): Promise<number>;
// User operations
getUser(id: string): Promise<User | undefined>;
getUserByEmail(email: string): Promise<User | undefined>;
getUserByUsername(username: string): Promise<User | undefined>;
createUser(user: InsertUser): Promise<User>;
updateUser(id: string, user: Partial<InsertUser>): Promise<User | undefined>;
// Playlist operations
getPlaylists(userId: string, limit?: number, offset?: number): Promise<Playlist[]>;
getPlaylist(id: string, userId?: string): Promise<Playlist | undefined>;
createPlaylist(playlist: InsertPlaylist): Promise<Playlist>;
updatePlaylist(id: string, playlist: Partial<InsertPlaylist>, userId: string): Promise<Playlist | undefined>;
deletePlaylist(id: string, userId: string): Promise<boolean>;
// Playlist video operations
getPlaylistVideos(playlistId: string): Promise<(PlaylistVideo & { video: Video })[]>;
addVideoToPlaylist(playlistVideo: InsertPlaylistVideo): Promise<PlaylistVideo>;
removeVideoFromPlaylist(playlistId: string, videoId: string): Promise<boolean>;
// Favorites operations
getUserFavorites(userId: string, limit?: number, offset?: number): Promise<(UserFavorite & { video: Video })[]>;
addToFavorites(favorite: InsertUserFavorite): Promise<UserFavorite>;
removeFromFavorites(userId: string, videoId: string): Promise<boolean>;
isVideoFavorited(userId: string, videoId: string): Promise<boolean>;
}
export class MemStorage implements IStorage {
private videos: Map<string, Video>;
private users: Map<string, User>;
private playlists: Map<string, Playlist>;
private playlistVideos: Map<string, PlaylistVideo[]>;
private userFavorites: Map<string, UserFavorite[]>;
constructor() {
this.videos = new Map();
this.users = new Map();
this.playlists = new Map();
this.playlistVideos = new Map();
this.userFavorites = new Map();
// Initialize with some sample videos for demonstration
// In production, these would be fetched from bunny.net API
this.initializeSampleVideos();
this.initializeSampleUsers();
}
private initializeSampleVideos() {
@@ -191,222 +145,6 @@ export class MemStorage implements IStorage {
const videos = await this.getVideos(1000, 0, search, category);
return videos.length;
}
private initializeSampleUsers() {
// Sample user for testing
const sampleUser: User = {
id: "test-user-123",
username: "testuser",
email: "test@example.com",
passwordHash: "hashed_password",
firstName: "Test",
lastName: "User",
avatar: null,
isActive: true,
createdAt: new Date(),
updatedAt: new Date(),
};
this.users.set(sampleUser.id, sampleUser);
}
// User operations
async getUser(id: string): Promise<User | undefined> {
return this.users.get(id);
}
async getUserByEmail(email: string): Promise<User | undefined> {
for (const user of this.users.values()) {
if (user.email === email) {
return user;
}
}
return undefined;
}
async getUserByUsername(username: string): Promise<User | undefined> {
for (const user of this.users.values()) {
if (user.username === username) {
return user;
}
}
return undefined;
}
async createUser(userData: InsertUser): Promise<User> {
const user: User = {
id: randomUUID(),
...userData,
createdAt: new Date(),
updatedAt: new Date(),
};
this.users.set(user.id, user);
return user;
}
async updateUser(id: string, userData: Partial<InsertUser>): Promise<User | undefined> {
const user = this.users.get(id);
if (!user) return undefined;
const updatedUser: User = {
...user,
...userData,
updatedAt: new Date(),
};
this.users.set(id, updatedUser);
return updatedUser;
}
// Playlist operations
async getPlaylists(userId: string, limit = 20, offset = 0): Promise<Playlist[]> {
const userPlaylists = Array.from(this.playlists.values())
.filter(playlist => playlist.userId === userId)
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
.slice(offset, offset + limit);
return userPlaylists;
}
async getPlaylist(id: string, userId?: string): Promise<Playlist | undefined> {
const playlist = this.playlists.get(id);
if (!playlist) return undefined;
// If userId is provided, check ownership or public status
if (userId && playlist.userId !== userId && !playlist.isPublic) {
return undefined;
}
return playlist;
}
async createPlaylist(playlistData: InsertPlaylist): Promise<Playlist> {
const playlist: Playlist = {
id: randomUUID(),
...playlistData,
createdAt: new Date(),
updatedAt: new Date(),
};
this.playlists.set(playlist.id, playlist);
this.playlistVideos.set(playlist.id, []);
return playlist;
}
async updatePlaylist(id: string, playlistData: Partial<InsertPlaylist>, userId: string): Promise<Playlist | undefined> {
const playlist = this.playlists.get(id);
if (!playlist || playlist.userId !== userId) return undefined;
const updatedPlaylist: Playlist = {
...playlist,
...playlistData,
updatedAt: new Date(),
};
this.playlists.set(id, updatedPlaylist);
return updatedPlaylist;
}
async deletePlaylist(id: string, userId: string): Promise<boolean> {
const playlist = this.playlists.get(id);
if (!playlist || playlist.userId !== userId) return false;
this.playlists.delete(id);
this.playlistVideos.delete(id);
return true;
}
// Playlist video operations
async getPlaylistVideos(playlistId: string): Promise<(PlaylistVideo & { video: Video })[]> {
const videos = this.playlistVideos.get(playlistId) || [];
const result = [];
for (const playlistVideo of videos) {
const video = this.videos.get(playlistVideo.videoId);
if (video) {
result.push({ ...playlistVideo, video });
}
}
return result.sort((a, b) => a.position - b.position);
}
async addVideoToPlaylist(playlistVideoData: InsertPlaylistVideo): Promise<PlaylistVideo> {
const videos = this.playlistVideos.get(playlistVideoData.playlistId) || [];
// Check if video is already in playlist
const existingIndex = videos.findIndex(v => v.videoId === playlistVideoData.videoId);
if (existingIndex !== -1) {
throw new Error("Video is already in playlist");
}
const playlistVideo: PlaylistVideo = {
...playlistVideoData,
addedAt: new Date(),
};
videos.push(playlistVideo);
this.playlistVideos.set(playlistVideoData.playlistId, videos);
return playlistVideo;
}
async removeVideoFromPlaylist(playlistId: string, videoId: string): Promise<boolean> {
const videos = this.playlistVideos.get(playlistId) || [];
const filteredVideos = videos.filter(v => v.videoId !== videoId);
if (filteredVideos.length === videos.length) {
return false; // Video not found
}
this.playlistVideos.set(playlistId, filteredVideos);
return true;
}
// Favorites operations
async getUserFavorites(userId: string, limit = 20, offset = 0): Promise<(UserFavorite & { video: Video })[]> {
const favorites = this.userFavorites.get(userId) || [];
const result = [];
for (const favorite of favorites.slice(offset, offset + limit)) {
const video = this.videos.get(favorite.videoId);
if (video) {
result.push({ ...favorite, video });
}
}
return result.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}
async addToFavorites(favoriteData: InsertUserFavorite): Promise<UserFavorite> {
const favorites = this.userFavorites.get(favoriteData.userId) || [];
// Check if already favorited
const existing = favorites.find(f => f.videoId === favoriteData.videoId);
if (existing) {
throw new Error("Video is already in favorites");
}
const favorite: UserFavorite = {
...favoriteData,
createdAt: new Date(),
};
favorites.push(favorite);
this.userFavorites.set(favoriteData.userId, favorites);
return favorite;
}
async removeFromFavorites(userId: string, videoId: string): Promise<boolean> {
const favorites = this.userFavorites.get(userId) || [];
const filteredFavorites = favorites.filter(f => f.videoId !== videoId);
if (filteredFavorites.length === favorites.length) {
return false; // Favorite not found
}
this.userFavorites.set(userId, filteredFavorites);
return true;
}
async isVideoFavorited(userId: string, videoId: string): Promise<boolean> {
const favorites = this.userFavorites.get(userId) || [];
return favorites.some(f => f.videoId === videoId);
}
}
// Use Bunny.net storage if API keys are available, otherwise fallback to memory storage
@@ -482,291 +220,6 @@ class BunnyStorage implements IStorage {
return 0;
}
}
// User operations - Not implemented for BunnyStorage (video-only service)
async getUser(id: string): Promise<User | undefined> {
throw new Error("User operations are not supported with Bunny.net storage");
}
async getUserByEmail(email: string): Promise<User | undefined> {
throw new Error("User operations are not supported with Bunny.net storage");
}
async getUserByUsername(username: string): Promise<User | undefined> {
throw new Error("User operations are not supported with Bunny.net storage");
}
async createUser(user: InsertUser): Promise<User> {
throw new Error("User operations are not supported with Bunny.net storage");
}
async updateUser(id: string, user: Partial<InsertUser>): Promise<User | undefined> {
throw new Error("User operations are not supported with Bunny.net storage");
}
// Playlist operations - Not implemented for BunnyStorage (video-only service)
async getPlaylists(userId: string, limit?: number, offset?: number): Promise<Playlist[]> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async getPlaylist(id: string, userId?: string): Promise<Playlist | undefined> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async createPlaylist(playlist: InsertPlaylist): Promise<Playlist> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async updatePlaylist(id: string, playlist: Partial<InsertPlaylist>, userId: string): Promise<Playlist | undefined> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async deletePlaylist(id: string, userId: string): Promise<boolean> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async getPlaylistVideos(playlistId: string): Promise<(PlaylistVideo & { video: Video })[]> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async addVideoToPlaylist(playlistVideo: InsertPlaylistVideo): Promise<PlaylistVideo> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
async removeVideoFromPlaylist(playlistId: string, videoId: string): Promise<boolean> {
throw new Error("Playlist operations are not supported with Bunny.net storage");
}
// Favorites operations - Not implemented for BunnyStorage (video-only service)
async getUserFavorites(userId: string, limit?: number, offset?: number): Promise<(UserFavorite & { video: Video })[]> {
throw new Error("Favorites operations are not supported with Bunny.net storage");
}
async addToFavorites(favorite: InsertUserFavorite): Promise<UserFavorite> {
throw new Error("Favorites operations are not supported with Bunny.net storage");
}
async removeFromFavorites(userId: string, videoId: string): Promise<boolean> {
throw new Error("Favorites operations are not supported with Bunny.net storage");
}
async isVideoFavorited(userId: string, videoId: string): Promise<boolean> {
throw new Error("Favorites operations are not supported with Bunny.net storage");
}
}
// Create a hybrid storage that combines Bunny.net videos with database user features
import { db } from "./db";
import { eq, and, desc, asc } from "drizzle-orm";
import { users, playlists, playlistVideos, userFavorites } from "@shared/schema";
class HybridStorage implements IStorage {
private bunnyStorage: BunnyStorage;
constructor() {
this.bunnyStorage = new BunnyStorage();
}
// Video operations - delegate to Bunny.net
async getVideos(limit = 20, offset = 0, search?: string, category?: string): Promise<Video[]> {
return this.bunnyStorage.getVideos(limit, offset, search, category);
}
async getVideo(id: string): Promise<Video | undefined> {
return this.bunnyStorage.getVideo(id);
}
async createVideo(video: InsertVideo): Promise<Video> {
return this.bunnyStorage.createVideo(video);
}
async updateVideoViews(id: string): Promise<void> {
return this.bunnyStorage.updateVideoViews(id);
}
async getVideoCount(search?: string, category?: string): Promise<number> {
return this.bunnyStorage.getVideoCount(search, category);
}
// User operations - use database
async getUser(id: string): Promise<User | undefined> {
const [user] = await db.select().from(users).where(eq(users.id, id));
return user;
}
async getUserByEmail(email: string): Promise<User | undefined> {
const [user] = await db.select().from(users).where(eq(users.email, email));
return user;
}
async getUserByUsername(username: string): Promise<User | undefined> {
const [user] = await db.select().from(users).where(eq(users.username, username));
return user;
}
async createUser(userData: InsertUser): Promise<User> {
const [user] = await db.insert(users).values({
...userData,
createdAt: new Date(),
updatedAt: new Date()
}).returning();
return user;
}
async updateUser(id: string, userData: Partial<InsertUser>): Promise<User | undefined> {
const [user] = await db.update(users)
.set({ ...userData, updatedAt: new Date() })
.where(eq(users.id, id))
.returning();
return user;
}
// Playlist operations - use database
async getPlaylists(userId: string, limit = 20, offset = 0): Promise<Playlist[]> {
const userPlaylists = await db.select()
.from(playlists)
.where(eq(playlists.userId, userId))
.orderBy(desc(playlists.createdAt))
.limit(limit)
.offset(offset);
return userPlaylists;
}
async getPlaylist(id: string, userId?: string): Promise<Playlist | undefined> {
let query = db.select().from(playlists).where(eq(playlists.id, id));
if (userId) {
query = query.where(eq(playlists.userId, userId));
}
const [playlist] = await query;
return playlist;
}
async createPlaylist(playlistData: InsertPlaylist): Promise<Playlist> {
const [playlist] = await db.insert(playlists).values({
...playlistData,
createdAt: new Date(),
updatedAt: new Date()
}).returning();
return playlist;
}
async updatePlaylist(id: string, updates: Partial<InsertPlaylist>, userId: string): Promise<Playlist | undefined> {
const [playlist] = await db.update(playlists)
.set({ ...updates, updatedAt: new Date() })
.where(and(eq(playlists.id, id), eq(playlists.userId, userId)))
.returning();
return playlist;
}
async deletePlaylist(id: string, userId: string): Promise<boolean> {
const result = await db.delete(playlists)
.where(and(eq(playlists.id, id), eq(playlists.userId, userId)));
return result.rowCount > 0;
}
// Playlist video operations - use database
async getPlaylistVideos(playlistId: string): Promise<(PlaylistVideo & { video: Video })[]> {
const playlistVideoRecords = await db.select()
.from(playlistVideos)
.where(eq(playlistVideos.playlistId, playlistId))
.orderBy(asc(playlistVideos.position));
const results = [];
for (const record of playlistVideoRecords) {
const video = await this.getVideo(record.videoId);
if (video) {
results.push({ ...record, video });
}
}
return results;
}
async addVideoToPlaylist(data: InsertPlaylistVideo): Promise<PlaylistVideo> {
// Check if video already exists in playlist
const existing = await db.select()
.from(playlistVideos)
.where(and(
eq(playlistVideos.playlistId, data.playlistId),
eq(playlistVideos.videoId, data.videoId)
));
if (existing.length > 0) {
throw new Error("Video is already in playlist");
}
const [playlistVideo] = await db.insert(playlistVideos).values({
...data,
addedAt: new Date()
}).returning();
return playlistVideo;
}
async removeVideoFromPlaylist(playlistId: string, videoId: string): Promise<boolean> {
const result = await db.delete(playlistVideos)
.where(and(
eq(playlistVideos.playlistId, playlistId),
eq(playlistVideos.videoId, videoId)
));
return result.rowCount > 0;
}
// Favorites operations - use database
async getUserFavorites(userId: string, limit = 20, offset = 0): Promise<(UserFavorite & { video: Video })[]> {
const favoriteRecords = await db.select()
.from(userFavorites)
.where(eq(userFavorites.userId, userId))
.orderBy(desc(userFavorites.createdAt))
.limit(limit)
.offset(offset);
const results = [];
for (const record of favoriteRecords) {
const video = await this.getVideo(record.videoId);
if (video) {
results.push({ ...record, video });
}
}
return results;
}
async addToFavorites(data: InsertUserFavorite): Promise<UserFavorite> {
// Check if video already favorited
const existing = await db.select()
.from(userFavorites)
.where(and(
eq(userFavorites.userId, data.userId),
eq(userFavorites.videoId, data.videoId)
));
if (existing.length > 0) {
throw new Error("Video is already in favorites");
}
const [favorite] = await db.insert(userFavorites).values({
...data,
createdAt: new Date()
}).returning();
return favorite;
}
async removeFromFavorites(userId: string, videoId: string): Promise<boolean> {
const result = await db.delete(userFavorites)
.where(and(
eq(userFavorites.userId, userId),
eq(userFavorites.videoId, videoId)
));
return result.rowCount > 0;
}
async isVideoFavorited(userId: string, videoId: string): Promise<boolean> {
const [favorite] = await db.select()
.from(userFavorites)
.where(and(
eq(userFavorites.userId, userId),
eq(userFavorites.videoId, videoId)
));
return !!favorite;
}
}
// Try to use Bunny.net storage, fallback to memory storage if not configured
@@ -777,10 +230,10 @@ const hasBunnyConfig = process.env.BUNNY_API_KEY && process.env.BUNNY_LIBRARY_ID
if (hasBunnyConfig) {
try {
storage = new HybridStorage();
console.log('✅ Using Hybrid storage (Bunny.net + Database) with library ID:', process.env.BUNNY_LIBRARY_ID);
storage = new BunnyStorage();
console.log('✅ Using Bunny.net storage with library ID:', process.env.BUNNY_LIBRARY_ID);
} catch (error) {
console.error('❌ Failed to initialize Hybrid storage:', error);
console.error('❌ Failed to initialize Bunny.net storage:', error);
console.log('📁 Falling back to memory storage');
storage = new MemStorage();
}
-158
View File
@@ -1,158 +0,0 @@
import { exec } from 'child_process';
import { promisify } from 'util';
import * as fs from 'fs';
import * as path from 'path';
const execAsync = promisify(exec);
export interface ThumbnailOptions {
videoId: string;
timeStamp?: string; // Format: "00:01:30" or "90" (seconds)
width?: number;
height?: number;
quality?: number;
}
export class ThumbnailGenerator {
private thumbnailDir: string;
constructor() {
this.thumbnailDir = path.join(process.cwd(), 'thumbnails');
this.ensureThumbnailDir();
}
private ensureThumbnailDir() {
if (!fs.existsSync(this.thumbnailDir)) {
fs.mkdirSync(this.thumbnailDir, { recursive: true });
}
}
async generateThumbnail(options: ThumbnailOptions): Promise<string | null> {
const { videoId, timeStamp = "5", width = 400, height = 225, quality = 85 } = options;
// Create unique filename based on parameters
const filename = `${videoId}_${timeStamp.replace(/:/g, '-')}_${width}x${height}.jpg`;
const outputPath = path.join(this.thumbnailDir, filename);
// Check if thumbnail already exists
if (fs.existsSync(outputPath)) {
return outputPath;
}
try {
// Use Bunny.net direct video URL for FFmpeg
const videoUrl = `https://vz-7982dfc4-cc8.b-cdn.net/${videoId}/playlist.m3u8`;
// FFmpeg command to extract frame at specific time
const ffmpegCommand = [
'ffmpeg',
'-i', `"${videoUrl}"`,
'-ss', timeStamp,
'-vframes', '1',
'-vf', `scale=${width}:${height}`,
'-q:v', quality.toString(),
`"${outputPath}"`,
'-y'
].join(' ');
console.log(`Generating thumbnail: ${ffmpegCommand}`);
const { stdout, stderr } = await execAsync(ffmpegCommand);
if (fs.existsSync(outputPath)) {
console.log(`Thumbnail generated successfully: ${outputPath}`);
return outputPath;
} else {
console.error('Thumbnail file was not created');
return null;
}
} catch (error) {
console.error('Error generating thumbnail:', error);
return null;
}
}
async generateMultipleThumbnails(videoId: string, timestamps: string[]): Promise<string[]> {
const results: string[] = [];
for (const timestamp of timestamps) {
const thumbnailPath = await this.generateThumbnail({
videoId,
timeStamp: timestamp
});
if (thumbnailPath) {
results.push(thumbnailPath);
}
}
return results;
}
async enhanceThumbnail(inputPath: string, outputPath: string): Promise<string | null> {
try {
// Use ImageMagick to enhance the thumbnail
const magickCommand = [
'convert',
`"${inputPath}"`,
'-auto-level',
'-enhance',
'-unsharp', '0x1',
`"${outputPath}"`
].join(' ');
await execAsync(magickCommand);
if (fs.existsSync(outputPath)) {
return outputPath;
}
return null;
} catch (error) {
console.error('Error enhancing thumbnail:', error);
return null;
}
}
listThumbnails(videoId: string): string[] {
try {
const files = fs.readdirSync(this.thumbnailDir);
return files
.filter(file => file.startsWith(videoId) && file.endsWith('.jpg'))
.map(file => path.join(this.thumbnailDir, file));
} catch (error) {
console.error('Error listing thumbnails:', error);
return [];
}
}
deleteThumbnail(videoId: string, timestamp?: string): boolean {
try {
if (timestamp) {
// Delete specific thumbnail
const filename = `${videoId}_${timestamp.replace(/:/g, '-')}_400x225.jpg`;
const filePath = path.join(this.thumbnailDir, filename);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
return true;
}
} else {
// Delete all thumbnails for video
const files = fs.readdirSync(this.thumbnailDir);
const videoThumbnails = files.filter(file => file.startsWith(videoId));
for (const file of videoThumbnails) {
fs.unlinkSync(path.join(this.thumbnailDir, file));
}
return videoThumbnails.length > 0;
}
return false;
} catch (error) {
console.error('Error deleting thumbnail:', error);
return false;
}
}
}