diff --git a/server.js b/server.js index edc7eb0..ad48e12 100644 --- a/server.js +++ b/server.js @@ -11,6 +11,10 @@ const { S3Client, ListBucketsCommand, ListObjectsV2Command, GetObjectCommand } = dotenv.config(); +const CACHE_DIR = path.join(__dirname, 'cache'); +if (!fs.existsSync(CACHE_DIR)) { + fs.mkdirSync(CACHE_DIR, { recursive: true }); +} const app = express(); const PORT = process.env.PORT || 3000; const HOST = process.env.HOST || process.env.LISTEN_ADDRESS || '0.0.0.0'; @@ -321,7 +325,7 @@ wss.on('connection', (ws) => { const clearDownloadCache = () => { - const tmpDir = os.tmpdir(); + const tmpDir = CACHE_DIR; try { if (!fs.existsSync(tmpDir)) return; const files = fs.readdirSync(tmpDir); @@ -329,6 +333,9 @@ const clearDownloadCache = () => { if (file.startsWith('s3-input-') && file.endsWith('.tmp')) { const filePath = path.join(tmpDir, file); fs.rmSync(filePath, { force: true }); + } else if (file.startsWith('hls-')) { + const filePath = path.join(tmpDir, file); + fs.rmSync(filePath, { recursive: true, force: true }); } } } catch (err) { @@ -475,7 +482,7 @@ app.get('/api/hls/playlist.m3u8', async (req, res) => { const safeKeySegments = key.split('/').map(segment => segment.replace(/[^a-zA-Z0-9_\-]/g, '_')); const safeBucket = bucket.replace(/[^a-zA-Z0-9_\-]/g, '_'); - const tmpInputPath = path.join(os.tmpdir(), `s3-input-${safeBucket}-${safeKeySegments.join('-')}.tmp`); + const tmpInputPath = path.join(CACHE_DIR, `s3-input-${safeBucket}-${safeKeySegments.join('-')}.tmp`); const auth = extractS3Credentials(req); const s3Client = createS3Client(auth); @@ -597,10 +604,10 @@ app.get('/api/hls/segment.ts', async (req, res) => { const safeKeySegments = key.split('/').map(segment => segment.replace(/[^a-zA-Z0-9_\-]/g, '_')); const safeBucket = bucket.replace(/[^a-zA-Z0-9_\-]/g, '_'); - const tmpInputPath = path.join(os.tmpdir(), `s3-input-${safeBucket}-${safeKeySegments.join('-')}.tmp`); + const tmpInputPath = path.join(CACHE_DIR, `s3-input-${safeBucket}-${safeKeySegments.join('-')}.tmp`); const progressKey = safeKeySegments.join('/'); - const hlsDir = path.join(os.tmpdir(), `hls-${safeBucket}-${progressKey}`); + const hlsDir = path.join(CACHE_DIR, `hls-${safeBucket}-${progressKey}`); if (!fs.existsSync(hlsDir)) fs.mkdirSync(hlsDir, { recursive: true }); const targetSegPath = path.join(hlsDir, `segment_${seg}.ts`); @@ -741,7 +748,7 @@ app.get('/api/stream', async (req, res) => { const safeKeySegments = key.split('/').map(segment => segment.replace(/[^a-zA-Z0-9_\-]/g, '_')); const progressKey = safeKeySegments.join('/'); const safeBucket = bucket.replace(/[^a-zA-Z0-9_\-]/g, '_'); - const tmpInputPath = path.join(os.tmpdir(), `s3-input-${safeBucket}-${safeKeySegments.join('-')}.tmp`); + const tmpInputPath = path.join(CACHE_DIR, `s3-input-${safeBucket}-${safeKeySegments.join('-')}.tmp`); const cacheExists = fs.existsSync(tmpInputPath); const auth = extractS3Credentials(req);