|
| 1 | +'use strict' |
| 2 | + |
| 3 | +/* eslint-env browser */ |
| 4 | + |
| 5 | +const Ipfs = require('../../') |
| 6 | +const videoStream = require('videostream') |
| 7 | +const repoPath = 'ipfs-' + Math.random() |
| 8 | +const ipfs = new Ipfs({ repo: repoPath }) |
| 9 | +const through = require('through') |
| 10 | +const unixFs = require('ipfs-unixfs') |
| 11 | +const pull = require('pull-stream') |
| 12 | +const drain = require('pull-stream/sinks/drain') |
| 13 | + |
| 14 | +const log = (line) => { |
| 15 | + document.getElementById('output').appendChild(document.createTextNode(`${line}\r\n`)) |
| 16 | +} |
| 17 | + |
| 18 | +log('Initialising IPFS') |
| 19 | + |
| 20 | +let stream |
| 21 | + |
| 22 | +const cleanUp = () => { |
| 23 | + if (stream && stream.destroy) { |
| 24 | + stream.destroy() |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +ipfs.on('ready', () => { |
| 29 | + const videoElement = createVideoElement() |
| 30 | + |
| 31 | + log('Adding video file') |
| 32 | + |
| 33 | + addVideoFile('/video.mp4') |
| 34 | + .then(hash => { |
| 35 | + log(`Added file with hash ${hash}`) |
| 36 | + |
| 37 | + const hashInput = document.getElementById('hash') |
| 38 | + const goButton = document.getElementById('gobutton') |
| 39 | + |
| 40 | + hashInput.value = hash |
| 41 | + |
| 42 | + goButton.onclick = function () { |
| 43 | + videoStream({ |
| 44 | + createReadStream: function (opts) { |
| 45 | + // Return a readable stream that provides the bytes |
| 46 | + // between offsets "start" and "end" inclusive |
| 47 | + const start = opts.start |
| 48 | + const end = opts.end ? start + opts.end + 1 : undefined |
| 49 | + |
| 50 | + log(`Asked for data starting at byte ${start}`) |
| 51 | + |
| 52 | + cleanUp() |
| 53 | + |
| 54 | + // We will write the requested bytes into this stream |
| 55 | + stream = ipfs.files.catReadableStream(hashInput.value.trim(), start, end) |
| 56 | + |
| 57 | + return stream |
| 58 | + } |
| 59 | + }, videoElement) |
| 60 | + |
| 61 | + return false |
| 62 | + } |
| 63 | + |
| 64 | + hashInput.disabled = false |
| 65 | + goButton.disabled = false |
| 66 | + }) |
| 67 | +}) |
| 68 | + |
| 69 | +const addVideoFile = (path) => { |
| 70 | + return fetch(path) |
| 71 | + .then(response => response.arrayBuffer()) |
| 72 | + .then(buffer => ipfs.files.add(Buffer.from(buffer))) |
| 73 | + .then(result => result.pop().hash) |
| 74 | +} |
| 75 | + |
| 76 | +const createVideoElement = () => { |
| 77 | + const videoElement = document.getElementById('video') |
| 78 | + videoElement.addEventListener('loadedmetadata', () => { |
| 79 | + log('Video metadata loaded') |
| 80 | + |
| 81 | + videoElement.play() |
| 82 | + }) |
| 83 | + videoElement.addEventListener('loadeddata', () => { |
| 84 | + log('First video frame loaded') |
| 85 | + }) |
| 86 | + videoElement.addEventListener('loadstart', () => { |
| 87 | + log('Started loading video') |
| 88 | + }) |
| 89 | + |
| 90 | + return videoElement |
| 91 | +} |
0 commit comments