Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.8 kB
2
Indexable
Never
require('dotenv').config();
const app = require("./app");
const fs = require('fs').promises;
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const AWS = require('aws-sdk');

// Cloudflare R2 configuration
const s3 = new AWS.S3({
    endpoint: process.env.AWS_ENDPOINT,
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    signatureVersion: 'v4',
    region: 'auto'
});

io.on('connection', (socket) => {
  const chunks = [];

  socket.on('videoChunk', (data) => {
    console.log('chunk received');
    chunks.push(data);
    socket.emit('videoChunkCompleted', chunks.length);
  });

  socket.on('getVideoLink', async () => {
    try {
      const date = new Date();
      const fileName = `${date.getFullYear()}${date.getMonth()+1}${date.getDate()}_${date.getHours()}${date.getMinutes()}${date.getSeconds()}.webm`;
      const videoBuffer = Buffer.concat(chunks);
      await fs.writeFile(fileName, videoBuffer);

      const file = await fs.readFile(fileName);

      const params = {
        Bucket: 'test',
        Key: fileName,
        Body: file
      };

      s3.upload(params, function(err, data) {
        if (err) {
          console.error(err);
          socket.emit('sendVideoLink', false);
          return;
        }
        socket.emit('sendVideoLink', `https://r2.recram.com/${data.Bucket}/${data.Key}`);
      });
    } catch (error) {
      console.error(error);
      socket.emit('sendVideoLink', false);
    }
  });

  socket.on('disconnect', () => {
    console.log('disconnected');
  });
});

const PORT = process.env.PORT || 7777;
server.listen(PORT, () => {
  console.log(`Socket server is listening on port ${PORT}`);
});
Leave a Comment