From 28f65e699ea0262ff8d42581f67cf97e0165a5a9 Mon Sep 17 00:00:00 2001
From: MrFry <mrfry@airmail.cc>
Date: Sat, 26 Oct 2019 20:42:34 +0200
Subject: [PATCH] Video streaming

---
 modules/stuff.js      | 43 +++++++++++++++++++++++++++++++++++++++++++
 views/stuff/video.ejs | 25 +++++++++++++++++++++++++
 2 files changed, 68 insertions(+)
 create mode 100644 views/stuff/video.ejs

diff --git a/modules/stuff.js b/modules/stuff.js
index 4e174eb..3edfdde 100644
--- a/modules/stuff.js
+++ b/modules/stuff.js
@@ -49,6 +49,49 @@ app.use(bodyParser.json({
 
 // --------------------------------------------------------------
 
+app.get('/*.mp4', function (req, res) {
+  let p = req.url.replace(/%20/g, ' ')
+  let fp = p.split('?')
+  fp.pop()
+  const fpath = './public/files' + fp.join('/')
+  if (req.query.stream) {
+    const stat = fs.statSync(fpath)
+    const fileSize = stat.size
+    const range = req.headers.range
+    if (range) {
+      const parts = range.replace(/bytes=/, '').split('-')
+      const start = parseInt(parts[0], 10)
+      const end = parts[1]
+        ? parseInt(parts[1], 10)
+        : fileSize - 1
+      const chunksize = (end - start) + 1
+      const file = fs.createReadStream(fpath, { start, end })
+      const head = {
+        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
+        'Accept-Ranges': 'bytes',
+        'Content-Length': chunksize,
+        'Content-Type': 'video/mp4'
+      }
+      res.writeHead(206, head)
+      file.pipe(res)
+    } else {
+      const head = {
+        'Content-Length': fileSize,
+        'Content-Type': 'video/mp4'
+      }
+      res.writeHead(200, head)
+      fs.createReadStream(fpath).pipe(res)
+    }
+  } else {
+    let fname = p.split('/')
+    fname = fname.pop()
+    res.render('stuff/video', {
+      path: p,
+      fname
+    })
+  }
+})
+
 app.get('/*', function (req, res) {
   let parsedUrl = req.url.replace(/%20/g, ' ')
   let curr = listedFiles + '/' + parsedUrl.substring('/'.length, parsedUrl.length).split('?')[0]
diff --git a/views/stuff/video.ejs b/views/stuff/video.ejs
new file mode 100644
index 0000000..b2f83be
--- /dev/null
+++ b/views/stuff/video.ejs
@@ -0,0 +1,25 @@
+<html>
+
+  <body bgcolor="#212127">
+
+    <head>
+      <title><%= fname %></title>
+      <meta charset="UTF-8">
+      <meta name="viewport" content="width=device-width, initial-scale=0.6" />
+      <style>
+        body {
+          font: normal 14px Verdana;
+          color: #999999;
+        }
+      </style>
+    </head>
+    <center>
+      <h2>
+        <%= fname %>
+      </h2>
+      <video id="videoPlayer" controls muted="muted" autoplay> 
+        <source src="http://localhost:8080<%= path %>?stream=true" type="video/mp4">
+      </video>
+    </center>
+  </body>
+</html>