Completed
Push — master ( b96d25...64cc65 )
by Amin
03:00
created

Export::saveToGCS()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 6
dl 0
loc 18
rs 10
1
<?php
2
3
/**
4
 * This file is part of the PHP-FFmpeg-video-streaming package.
5
 *
6
 * (c) Amin Yazdanpanah <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Streaming;
13
14
use FFMpeg\Exception\ExceptionInterface;
15
use Streaming\Exception\Exception;
16
use Streaming\Exception\InvalidArgumentException;
17
use Streaming\Exception\RuntimeException;
18
use Streaming\Filters\Filter;
19
use Streaming\Traits\Formats;
20
21
abstract class Export
22
{
23
    use Formats;
24
25
    /** @var object */
26
    protected $media;
27
28
    /** @var Filter */
29
    protected $filter;
30
31
    /** @var array */
32
    protected $path_info;
33
34
    /** @var string */
35
    protected $strict = "-2";
36
37
    /**
38
     * Export constructor.
39
     * @param Media $media
40
     */
41
    public function __construct(Media $media)
42
    {
43
        $this->media = $media;
44
        $this->path_info = pathinfo($media->getPath());
45
    }
46
47
    /**
48
     * @param string $path
49
     * @param bool $analyse
50
     * @return mixed
51
     * @throws Exception
52
     */
53
    public function save(string $path = null, $analyse = true)
54
    {
55
        $path = $this->getPath($path);
56
57
        $this->setFilter();
58
59
        $this->media->addFilter(
60
            $this->getFilter()
61
        );
62
63
        try {
64
            $this->media->save(
65
                $this->getFormat(),
66
                $path
67
            );
68
        } catch (ExceptionInterface $e) {
69
            throw new RuntimeException(sprintf(
70
                "There was an error saving files: \n\n reason: \n %s",
71
                $e->getMessage()
72
            ),
73
                $e->getCode(),
74
                $e->getFile());
75
        }
76
77
78
        $response = ($analyse) ? (new StreamingAnalytics($this))->analyse() : $this;
79
80
        if ($this->media->isTmp()) {
81
            $this->deleteOriginalFile();
82
        }
83
84
        return $response;
85
    }
86
87
    /**
88
     * @return Filter
89
     */
90
    abstract protected function getFilter(): Filter;
91
92
    /**
93
     * @return mixed
94
     */
95
    abstract protected function setFilter();
96
97
    /**
98
     * @param $path
99
     * @return string
100
     * @throws Exception
101
     */
102
    private function getPath($path): string
103
    {
104
        if (null !== $path) {
105
            $this->path_info = pathinfo($path);
106
        }
107
108
        if (null === $path && $this->media->isTmp()) {
109
            $this->deleteOriginalFile();
110
            throw new InvalidArgumentException("You need to specify a path. It is not possible to save to a tmp directory");
111
        }
112
113
        $dirname = str_replace("\\", "/", $this->path_info["dirname"]);
114
        $filename = substr($this->path_info["filename"], -50);
115
116
        FileManager::makeDir($dirname);
117
118
        if ($this instanceof DASH) {
119
            $path = $dirname . "/" . $filename . ".mpd";
120
        } elseif ($this instanceof HLS) {
121
            $representations = $this->getRepresentations();
122
            $path = $dirname . "/" . $filename . "_" . end($representations)->getHeight() . "p.m3u8";
123
            ExportHLSPlaylist::savePlayList($dirname . DIRECTORY_SEPARATOR . $filename . ".m3u8", $this->getRepresentations(), $filename);
124
        }
125
126
        return $path;
127
    }
128
129
    /**
130
     * @param string $url
131
     * @param string $name
132
     * @param string|null $path
133
     * @param string $method
134
     * @param array $headers
135
     * @param array $options
136
     * @param bool $analyse
137
     * @return mixed
138
     * @throws Exception
139
     */
140
    public function saveToCloud(
141
        string $url,
142
        string $name,
143
        string $path = null,
144
        string $method = 'GET',
145
        array $headers = [],
146
        array $options = [],
147
        bool $analyse = true
148
    )
149
    {
150
        if ($this instanceof HLS && $this->getTsSubDirectory()) {
151
            throw new InvalidArgumentException("It is not possible to create subdirectory in a cloud");
152
        }
153
        list($results, $tmp_dir) = $this->saveToTemporaryFolder($path, $analyse);
154
        sleep(1);
155
156
        $file_manager = new FileManager($url, $method, $options);
157
        $file_manager->uploadDirectory($tmp_dir, $name, $headers);
158
159
        $this->moveTmpFolder($path, $tmp_dir);
160
161
        return $results;
162
    }
163
164
    /**
165
     * @param array $config
166
     * @param string $dest
167
     * @param string|null $path
168
     * @param bool $analyse
169
     * @return mixed
170
     * @throws Exception
171
     */
172
    public function saveToS3(
173
        array $config,
174
        string $dest,
175
        string $path = null,
176
        bool $analyse = true
177
    )
178
    {
179
        list($results, $tmp_dir) = $this->saveToTemporaryFolder($path, $analyse);
180
        sleep(1);
181
182
        $aws = new AWS($config);
183
        $aws->uploadAndDownloadDirectory($tmp_dir, $dest);
184
185
        $this->moveTmpFolder($path, $tmp_dir);
186
187
        return $results;
188
    }
189
190
    /**
191
     * @param array $config
192
     * @param string $bucket
193
     * @param string|null $path
194
     * @param array $options
195
     * @param bool $userProject
196
     * @param bool $analyse
197
     * @return mixed
198
     * @throws Exception
199
     */
200
    public function saveToGCS(
201
        array $config,
202
        string $bucket,
203
        string $path = null,
204
        array $options = [],
205
        $userProject = false,
206
        bool $analyse = true
207
    )
208
    {
209
        list($results, $tmp_dir) = $this->saveToTemporaryFolder($path, $analyse);
210
        sleep(1);
211
212
        $google_cloud = new GoogleCloudStorage($config, $bucket, $userProject);
213
        $google_cloud->uploadDirectory($tmp_dir, $options);
214
215
        $this->moveTmpFolder($path, $tmp_dir);
216
217
        return $results;
218
    }
219
220
    /**
221
     * @return array
222
     */
223
    public function getPathInfo(): array
224
    {
225
        return $this->path_info;
226
    }
227
228
    /**
229
     * @return object|Media
230
     */
231
    public function getMedia(): Media
232
    {
233
        return $this->media;
234
    }
235
236
    private function deleteOriginalFile()
237
    {
238
        sleep(1);
239
        @unlink($this->media->getPath());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

239
        /** @scrutinizer ignore-unhandled */ @unlink($this->media->getPath());

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
240
    }
241
242
    /**
243
     * @param $path
244
     * @param $analyse
245
     * @return array
246
     * @throws Exception
247
     */
248
    private function saveToTemporaryFolder($path, $analyse)
249
    {
250
        $basename = Helper::randomString();
251
252
        if (null !== $path) {
253
            $basename = pathinfo($path, PATHINFO_BASENAME);
254
        }
255
256
        $tmp_dir = FileManager::tmpDir();
257
        $tmp_file = $tmp_dir . $basename;
258
259
        return [$this->save($tmp_file, $analyse), $tmp_dir];
260
    }
261
262
    /**
263
     * @param string|null $path
264
     * @param $tmp_dir
265
     * @throws Exception
266
     */
267
    private function moveTmpFolder(?string $path, $tmp_dir)
268
    {
269
        if (null !== $path) {
270
            FileManager::moveDir($tmp_dir, pathinfo($path, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR);
271
        } else {
272
            FileManager::deleteDirectory($tmp_dir);
273
        }
274
    }
275
276
    /**
277
     * @param string $strict
278
     * @return Export
279
     */
280
    public function setStrict(string $strict): Export
281
    {
282
        $this->strict = $strict;
283
        return $this;
284
    }
285
286
    /**
287
     * @return string
288
     */
289
    public function getStrict(): string
290
    {
291
        return $this->strict;
292
    }
293
}