-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
247 lines (225 loc) · 9.13 KB
/
server.js
File metadata and controls
247 lines (225 loc) · 9.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* Overlay Image Server
*
* A Node.js microservice that generates Instagram-style image overlays with customizable text.
* Takes an image URL and overlays title and source text with professional styling.
*
* Features:
* - High-performance image processing with Sharp
* - Smart text wrapping and multi-line support
* - Professional typography with stroke outlines
* - Responsive text sizing based on image dimensions
* - Error handling for invalid URLs and missing parameters
*/
import express from 'express';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
// Import endpoint handlers
import { healthCheck } from './endpoints/health.js';
import { overlayHandler } from './endpoints/overlay.js';
import { reelHandler } from './endpoints/reel.js';
import { reel3Handler } from './endpoints/3slidesReel.js';
import { uploadHandler, deleteHandler } from './endpoints/storage.js';
// Import middleware
import { validateApiKey } from './middleware/auth.js';
// Load environment variables from .env file
dotenv.config();
// Initialize Express application
const app = express();
app.use(express.json({ limit: '2mb' }));
// Set port from environment variable or default to 8080
const PORT = process.env.OVERLAY_PORT || 8080;
// API Security Configuration
const API_KEY = process.env.OVERLAY_API_KEY || 'default-api-key-change-in-production';
const REQUIRE_API_KEY = process.env.OVERLAY_REQUIRE_API_KEY !== 'false'; // Default to true unless explicitly disabled
// Media and Path Configuration
const DOMAIN = process.env.OVERLAY_DOMAIN || 'http://localhost:8080';
const MEDIA_DIR = process.env.OVERLAY_MEDIA_DIR || path.join(process.cwd(), 'media');
const REELS_SUBDIR = process.env.OVERLAY_REELS_SUBDIR || 'reels';
const TMP_SUBDIR = process.env.OVERLAY_TMP_SUBDIR || 'tmp';
const BG_DIR = process.env.OVERLAY_BG_DIR || path.join(process.cwd(), 'assets', 'reels_bg');
// Construct full paths
const REELS_DIR = path.join(MEDIA_DIR, REELS_SUBDIR);
const TMP_DIR = path.join(MEDIA_DIR, TMP_SUBDIR);
// Configuration object to pass to endpoints
const config = {
API_KEY,
REQUIRE_API_KEY,
DOMAIN,
MEDIA_DIR,
REELS_SUBDIR,
TMP_SUBDIR,
BG_DIR,
REELS_DIR,
TMP_DIR
};
// Ensure directories exist
const ensureDirectories = () => {
const STORAGE_DIR = path.join(MEDIA_DIR, 'storage');
const directories = [MEDIA_DIR, REELS_DIR, TMP_DIR, BG_DIR, STORAGE_DIR];
for (const dir of directories) {
try {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
console.log(`📁 Created directory: ${dir}`);
}
} catch (error) {
console.warn(`⚠️ Could not create directory ${dir}: ${error.message}`);
}
}
};
// Initialize directories on startup
ensureDirectories();
// Serve media files statically
app.use('/media', express.static(MEDIA_DIR, { fallthrough: false }));
// === ENDPOINT DEFINITIONS ===
/**
* Health check endpoint
* Simple endpoint to verify server is running
*/
app.get('/healthz', healthCheck);
/**
* 2 Slides Reel endpoint
*
* This endpoint creates Instagram reels with two slides
*
* GET /2slidesReel?slide1=<url>&slide2=<url>&title1=<text>&title2=<text>&duration1=<seconds>&duration2=<seconds>&transition=<type>
*
* Parameters:
* - slide1 (required): URL of the first slide image
* - slide2 (required): URL of the second slide image
* - title1 (optional): Overlay text for first slide (default: empty)
* - title2 (optional): Overlay text for second slide (default: empty)
* - duration1 (optional): Duration of first slide in seconds (default: 4)
* - duration2 (optional): Duration of second slide in seconds (default: 4)
* - transition (optional): Transition type between slides (default: 'fade')
*
* Returns:
* - Video file URL or processing status
*/
app.get('/2slidesReel', validateApiKey(config), (req, res) => reelHandler(req, res, config));
/**
* 3 Slides Reel endpoint
*
* This endpoint creates Instagram reels with three slides
*
* GET /3slidesReel?slide1=<url>&slide2=<url>&slide3=<url>&title1=<text>&title2=<text>&title3=<text>&duration1=<seconds>&duration2=<seconds>&duration3=<seconds>&transition=<type>
*
* Parameters:
* - slide1 (required): URL of the first slide image
* - slide2 (required): URL of the second slide image
* - slide3 (required): URL of the third slide image
* - title1 (optional): Overlay text for first slide (default: empty)
* - title2 (optional): Overlay text for second slide (default: empty)
* - title3 (optional): Overlay text for third slide (default: empty)
* - duration1 (optional): Duration of first slide in seconds (default: 4)
* - duration2 (optional): Duration of second slide in seconds (default: 4)
* - duration3 (optional): Duration of third slide in seconds (default: 4)
* - transition (optional): Transition type between slides (default: 'fade')
*
* Returns:
* - Video file URL or processing status
*/
app.get('/3slidesReel', validateApiKey(config), (req, res) => reel3Handler(req, res, config));
/**
* Main API endpoint for image overlay generation
*
* GET /overlay?img=<url>&title=<text>&source=<text>&w=<width>&h=<height>&maxLines=<number>&logo=<boolean>
*
* Parameters:
* - img (required): URL of the source image
* - title (optional): Text to overlay (no character limit, will wrap and truncate as needed)
* - source (optional): Source attribution text (no character limit)
* - w (optional): Output width in pixels (default: 1080)
* - h (optional): Output height in pixels (default: 1350)
* - maxLines (optional): Maximum number of lines for title text (default: 5)
* - logo (optional): Whether to overlay Logo.svg in bottom-left corner (default: false)
*
* Processes an image by:
* 1. Fetching the source image from the provided URL
* 2. Generating an SVG overlay with the specified text
* 3. Compositing the overlay onto the image
* 4. Adding logo overlay if requested
* 5. Returning the final image as JPEG
*/
app.get('/overlay', validateApiKey(config), overlayHandler);
/**
* File upload endpoint for local storage service
*
* POST /store/upload
*
* Accepts audio and video files for storage with the following features:
* - File size limit: 100MB
* - Supported formats: MP3, WAV, OGG, AAC, M4A, FLAC (audio) and MP4, AVI, MOV, WMV, FLV, WEBM, MKV, QuickTime (video)
* - Returns unique file ID and public URL for accessing the file
* - Files are stored in /media/storage/ directory
*
* Request body: multipart/form-data with 'file' field
*
* Response:
* - success: boolean indicating upload success
* - id: unique file identifier (UUID)
* - filename: generated filename
* - originalName: original filename from upload
* - mimeType: detected MIME type
* - size: file size in bytes
* - url: public URL for accessing the file
* - uploadTime: ISO timestamp of upload
*/
app.post('/store/upload', validateApiKey(config), (req, res) => uploadHandler(req, res, config));
/**
* File deletion endpoint for local storage service
*
* DELETE /store/:id
*
* Deletes a previously uploaded file by its unique ID.
*
* Parameters:
* - id (required): UUID of the file to delete
*
* Response:
* - success: boolean indicating deletion success
* - id: file identifier that was deleted
* - filename: name of the deleted file
* - size: size of the deleted file in bytes
* - deletedAt: ISO timestamp of deletion
* - message: confirmation message
*/
app.delete('/store/:id', validateApiKey(config), (req, res) => deleteHandler(req, res, config));
// === SERVER STARTUP ===
// Start the Express server and log the port
app.listen(PORT, () => {
console.log('='.repeat(60));
console.log('🚀 Overlay Image Server Started');
console.log('='.repeat(60));
console.log(`📡 Server running on port: ${PORT}`);
console.log(`🔐 API Key validation: ${REQUIRE_API_KEY ? 'ENABLED' : 'DISABLED'}`);
if (REQUIRE_API_KEY) {
console.log(`🔑 API Key: ${API_KEY.substring(0, 16)}... (use X-API-Key header)`);
}
console.log(`🌐 URL: https://${DOMAIN}`);
console.log(`📁 Media directory: ${MEDIA_DIR}`);
console.log(`🎬 Reels directory: ${REELS_DIR}`);
console.log(`📂 Temp directory: ${TMP_DIR}`);
console.log(`🎨 Background directory: ${BG_DIR}`);
console.log('');
console.log('📋 Available endpoints:');
console.log(` GET /healthz - Health check`);
console.log(` GET /overlay - Image overlay generation`);
console.log(` GET /2slidesReel - Two-slide reel generation`);
console.log(` GET /3slidesReel - Three-slide reel generation`);
console.log(` POST /store/upload - File upload service`);
console.log(` DELETE /store/:id - File deletion service`);
console.log(` GET /media/* - Static media files`);
console.log('');
console.log(`🌐 API endpoint: http://localhost:${PORT}/overlay`);
console.log(`📝 Example: http://localhost:${PORT}/overlay?img=https://example.com/image.jpg&title=Test&logo=true`);
if (REQUIRE_API_KEY) {
console.log(`🔑 With API key: curl -H "X-API-Key: ${API_KEY}" "http://localhost:${PORT}/overlay?img=https://example.com/image.jpg&title=Test"`);
}
console.log('='.repeat(60));
console.log('📊 Monitoring enabled - all requests will be logged');
console.log('⏹️ Press Ctrl+C to stop the server');
console.log('='.repeat(60));
});