Passed
Pull Request — master (#265)
by Pascal
02:42
created

replaceAbsolutePathsHLSEncryption()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 15
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 25
rs 9.7666
1
<?php
2
3
namespace ProtoneMedia\LaravelFFMpeg\Exporters;
4
5
use Closure;
6
use Illuminate\Filesystem\Filesystem;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
use ProtoneMedia\LaravelFFMpeg\FFMpeg\StdListener;
10
use ProtoneMedia\LaravelFFMpeg\Filesystem\Disk;
11
use ProtoneMedia\LaravelFFMpeg\Filesystem\TemporaryDirectories;
12
use Symfony\Component\Process\Process;
13
14
trait EncryptsHLSSegments
15
{
16
    /**
17
     * The encryption key.
18
     *
19
     * @var string
20
     */
21
    private $encryptionKey;
22
23
    /**
24
     * Gets called whenever a new encryption key is set.
25
     *
26
     * @var callable
27
     */
28
    private $onNewEncryptionKey;
29
30
    /**
31
     * Disk to store the secrets.
32
     */
33
    private $encryptionSecretsRoot;
34
35
    /**
36
     * Encryption IV
37
     *
38
     * @var string
39
     */
40
    private $encryptionIV;
41
42
    /**
43
     * Wether to rotate the key on every segment.
44
     *
45
     * @var boolean
46
     */
47
    private $rotateEncryptiongKey = false;
48
49
    /**
50
     * Number of opened segments.
51
     *
52
     * @var integer
53
     */
54
    private $segmentsOpened = 0;
55
56
    /**
57
     * Number of segments that can use the same key.
58
     *
59
     * @var integer
60
     */
61
    private $segmentsPerKey = 1;
62
63
    /**
64
     * Listener that will rotate the key.
65
     *
66
     * @var \ProtoneMedia\LaravelFFMpeg\FFMpeg\StdListener
67
     */
68
    private $listener;
69
70
    private $nextEncryptionKey;
71
72
    /**
73
     * Creates a new encryption key.
74
     *
75
     * @return string
76
     */
77
    public static function generateEncryptionKey(): string
78
    {
79
        return random_bytes(16);
80
    }
81
    /**
82
     * Creates a new encryption key filename.
83
     *
84
     * @return string
85
     */
86
    public static function generateEncryptionKeyFilename(): string
87
    {
88
        return bin2hex(random_bytes(8)) . '.key';
89
    }
90
91
    /**
92
     * Sets the encryption key with the given value or generates a new one.
93
     *
94
     * @param string $key
95
     * @return string
96
     */
97
    private function setEncryptionKey($key = null): string
98
    {
99
        return $this->encryptionKey = $key ?: static::generateEncryptionKey();
100
    }
101
102
    /**
103
     * Initialises the disk, info and IV for encryption and sets the key.
104
     *
105
     * @param string $key
106
     * @return self
107
     */
108
    public function withEncryptionKey($key): self
109
    {
110
        $this->encryptionSecretsRoot = app(TemporaryDirectories::class)->create();
111
112
        $this->encryptionIV = bin2hex(static::generateEncryptionKey());
113
114
        $this->setEncryptionKey($key);
115
116
        return $this;
117
    }
118
119
    /**
120
     * Enables encryption with rotating keys. The callable will receive every new
121
     * key and the integer sets the number of segments that can
122
     * use the same key.
123
     *
124
     * @param Closure $callback
125
     * @param int $segmentsPerKey
126
     * @return self
127
     */
128
    public function withRotatingEncryptionKey(Closure $callback, int $segmentsPerKey = 1): self
129
    {
130
        $this->rotateEncryptiongKey = true;
131
        $this->onNewEncryptionKey   = $callback;
132
        $this->segmentsPerKey       = $segmentsPerKey;
133
134
        return $this->withEncryptionKey(static::generateEncryptionKey());
135
    }
136
137
    /**
138
     * Rotates the key and returns the absolute path to the info file. This method
139
     * should be executed as fast as possible, or we might be too late for FFmpeg
140
     * opening the next segment. That's why we don't use the Disk-class magic.
141
     *
142
     * @return string
143
     */
144
    private function rotateEncryptionKey(): string
145
    {
146
        $hlsKeyInfoPath = $this->encryptionSecretsRoot . '/' . HLSExporter::HLS_KEY_INFO_FILENAME;
147
148
        // get the absolute path to the encryption key
149
        $keyFilename = $this->nextEncryptionKey ? $this->nextEncryptionKey[0] : static::generateEncryptionKeyFilename();
150
        $keyPath     = $this->encryptionSecretsRoot . '/' . $keyFilename;
151
152
        $encryptionKey = $this->setEncryptionKey($this->nextEncryptionKey ? $this->nextEncryptionKey[1] : null);
153
154
        // generate an info file with a reference to the encryption key and IV
155
        file_put_contents(
156
            $hlsKeyInfoPath,
157
            $keyPath . PHP_EOL . $keyPath . PHP_EOL . $this->encryptionIV,
158
        );
159
160
        // randomize the encryption key
161
        file_put_contents($keyPath, $encryptionKey);
162
163
        // call the callback
164
        if ($this->onNewEncryptionKey) {
165
            call_user_func($this->onNewEncryptionKey, $keyFilename, $encryptionKey, $this->listener);
166
        }
167
168
        if ($this->listener) {
169
            $this->listener->handle(Process::OUT, "Generated new key with filename: {$keyFilename}");
170
        }
171
172
        $this->nextEncryptionKey = [static::generateEncryptionKeyFilename(), static::generateEncryptionKey()];
173
174
        // return the absolute path to the info file
175
        return Disk::normalizePath($hlsKeyInfoPath);
176
    }
177
178
    /**
179
     * Returns an array with the encryption parameters.
180
     *
181
     * @return array
182
     */
183
    private function getEncrypedHLSParameters(): array
184
    {
185
        if (!$this->encryptionKey) {
186
            return [];
187
        }
188
189
        $keyInfoPath = $this->rotateEncryptionKey();
190
        $parameters  = ['-hls_key_info_file', $keyInfoPath];
191
192
        if ($this->rotateEncryptiongKey) {
193
            $parameters[] = '-hls_flags';
194
            $parameters[] = 'periodic_rekey';
195
        }
196
197
        return $parameters;
198
    }
199
200
    /**
201
     * Adds a listener and handler to rotate the key on
202
     * every new HLS segment.
203
     *
204
     * @return void
205
     */
206
    private function addHandlerToRotateEncryptionKey()
207
    {
208
        if (!$this->rotateEncryptiongKey) {
209
            return;
210
        }
211
212
        $this->addListener($this->listener = new StdListener)->onEvent('listen', function ($line) {
0 ignored issues
show
Bug introduced by
It seems like addListener() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

212
        $this->/** @scrutinizer ignore-call */ 
213
               addListener($this->listener = new StdListener)->onEvent('listen', function ($line) {
Loading history...
213
            $opensEncryptedSegment = Str::contains($line, ".keyinfo' for reading");
214
215
            if (!$opensEncryptedSegment) {
216
                return;
217
            }
218
219
            $this->segmentsOpened++;
220
221
            if ($this->segmentsOpened % $this->segmentsPerKey === 0) {
222
                $this->rotateEncryptionKey();
223
            }
224
        });
225
    }
226
227
    /**
228
     * While encoding, the encryption keys are saved to a temporary directory.
229
     * With this method, we loop through all segment playlists and replace
230
     * the absolute path to the keys to a relative ones.
231
     *
232
     * @param \Illuminate\Support\Collection $playlistMedia
233
     * @return void
234
     */
235
    private function replaceAbsolutePathsHLSEncryption(Collection $playlistMedia)
236
    {
237
        if (!$this->encryptionSecretsRoot) {
238
            return;
239
        }
240
241
        $playlistMedia->each(function ($playlistMedia) {
242
            $disk = $playlistMedia->getDisk();
243
            $path = $playlistMedia->getPath();
244
245
            $prefix = '#EXT-X-KEY:METHOD=AES-128,URI="';
246
247
            $content = str_replace(
0 ignored issues
show
Unused Code introduced by
The assignment to $content is dead and can be removed.
Loading history...
248
                $prefix . $this->encryptionSecretsRoot . '/',
249
                $prefix,
250
                $disk->get($path)
251
            );
252
253
            $content = str_replace(
254
                $prefix . Disk::normalizePath($this->encryptionSecretsRoot) . '/',
255
                $prefix,
256
                $disk->get($path)
257
            );
258
259
            $disk->put($path, $content);
260
        });
261
    }
262
263
    /**
264
     * Removes the encryption keys from the temporary disk.
265
     *
266
     * @return void
267
     */
268
    private function cleanupHLSEncryption()
269
    {
270
        if (!$this->encryptionSecretsRoot) {
271
            return;
272
        }
273
274
        (new Filesystem)->deleteDirectory($this->encryptionSecretsRoot);
275
    }
276
}
277