-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathEncoder.php
More file actions
3834 lines (3445 loc) · 153 KB
/
Copy pathEncoder.php
File metadata and controls
3834 lines (3445 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
if (empty($global)) {
$global = [];
}
if (!class_exists('CURLFile')) {
$phpVersion = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;
$msg = "The CURLFile class is not found. You might need the PHP cURL extension.<br>";
$msg .= "You can try installing it with:<br>";
$msg .= "sudo apt-get install php{$phpVersion}-curl<br>";
echo $msg;
_error_log($msg);
exit;
}
global $sentImage;
$sentImage = [];
require_once $global['systemRootPath'] . 'objects/Format.php';
require_once $global['systemRootPath'] . 'objects/Login.php';
require_once $global['systemRootPath'] . 'objects/Streamer.php';
require_once $global['systemRootPath'] . 'objects/Upload.php';
require_once $global['systemRootPath'] . 'objects/functions.php';
class Encoder extends ObjectYPT
{
const STATUS_ENCODING = 'encoding';
const STATUS_DOWNLOADING = 'downloading';
const STATUS_DOWNLOADED = 'downloaded';
const STATUS_QUEUE = 'queue';
const STATUS_ERROR = 'error';
const STATUS_DONE = 'done';
const STATUS_TRANSFERRING = 'transferring';
const STATUS_PACKING = 'packing';
const STATUS_FIXING = 'fixing';
const LOG_TYPE_StatusObs = 'StatusObs';
const LOG_TYPE_StatusChanged = 'StatusChanged';
const LOG_TYPE_ERROR = 'error';
const LOG_TYPE_INFO = 'info';
const AUDIO_EXTENSIONS = ['mp3', 'aac', 'm4a', 'ogg', 'opus', 'flac', 'wav', 'wma'];
protected $id;
protected $fileURI;
protected $filename;
protected $status;
protected $status_obs;
protected $return_vars;
protected $worker_ppid;
protected $worker_pid;
protected $priority;
protected $created;
protected $modified;
protected $formats_id;
protected $title;
protected $videoDownloadedLink;
protected $downloadedFileName;
protected $streamers_id;
protected $override_status;
public static function getSearchFieldsNames()
{
return array('filename');
}
public static function getTableName()
{
global $global;
return $global['tablesPrefix'] . 'encoder_queue';
}
public static function isPorn($string)
{
global $global;
if (empty($string) || !is_string($string) || !empty($global['disableCheck'])) {
return false;
}
$string = strtolower($string);
$array = array(
'xvideos',
'porn',
'xhamster',
'xnxx',
'draftsex',
'beeg',
'spankbang',
'xmovies',
'youjizz',
'motherless',
'redtube',
'4tube',
'3movs',
'tube8',
'cumloud',
'xxx',
'bellesa',
'tnaflix',
'whores',
'paradisehill',
'xfreehd',
'drtuber',
'netfapx',
'jerk',
'xmegadrive',
'brazzers',
'hitprn',
'czechvideo',
'reddit',
'plusone8',
'xleech',
'povaddict',
'freeomovie',
'cliphunter',
'xtape',
'xkeez',
'sextvx',
'pandamovie',
'palimas',
'pussy',
'siska',
'megatube',
'fakings',
'analdin',
'xozilla',
'empflix',
'swallows',
'erotic',
'vidoz8',
'perver',
'swinger',
'secretstash',
'fapme',
'pervs',
'tubeorigin',
'americass',
'sextu',
'sexu',
'dfinebabe',
'palmtube',
'dvdtrailerTube'
);
foreach ($array as $value) {
if (stripos($string, $value) !== false) {
return $value;
}
}
return false;
}
public function save()
{
global $global;
if (empty($this->streamers_id)) {
if (!empty($this->id)) {
_error_log("Encoder::save streamers_id is empty and we will delete");
return $this->delete();
}
_error_log("Encoder::save streamers_id is empty");
return false;
}
if (empty($this->id)) {
$this->setStatus(Encoder::STATUS_QUEUE);
}
if (empty($this->worker_ppid)) {
$this->worker_ppid = 0;
}
if (empty($this->fileURI)) {
$this->fileURI = '';
}
if (empty($this->filename)) {
$this->filename = '';
}
if (function_exists('mb_detect_encoding') && !mb_detect_encoding($this->title, 'UTF-8', true)) {
$this->title = mb_convert_encoding($this->title, 'UTF-8');
}
if (empty($this->id) && (self::isPorn($this->fileURI) || self::isPorn($this->videoDownloadedLink) || self::isPorn($this->filename) || self::isPorn($this->title))) {
if ($what = self::isPorn($this->fileURI)) {
_error_log("Encoder::save deny [$what] " . __LINE__);
}
if ($what = self::isPorn($this->videoDownloadedLink)) {
_error_log("Encoder::save deny [$what] " . __LINE__);
}
if ($what = self::isPorn($this->filename)) {
_error_log("Encoder::save deny [$what] " . __LINE__);
}
if ($what = self::isPorn($this->title)) {
_error_log("Encoder::save deny [$what] " . __LINE__);
}
return false;
}
$this->priority = intval($this->priority);
/**
* @var array $global
* @var object $global['mysqli']
*/
$this->worker_pid = intval($this->worker_pid);
_error_log("Encoder::save id=(" . $this->getId() . ") title=(" . $this->getTitle() . ") streamers_id={$this->streamers_id} status_obs={$this->status_obs} ");
$id = parent::save();
$this->id = $id;
_error_log("Encoder::save id=(" . $this->getId() . ")". ' <=>' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
return $id;
}
public static function getAll($onlyMine = false, $errorOnly = false)
{
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 ";
if ($onlyMine && !Login::isAdmin() && !isCommandLineInterface()) {
if (empty(Login::getStreamerId())) {
return false;
}
$sql .= " AND streamers_id = " . Login::getStreamerId() . " ";
}
if ($errorOnly) {
$sql .= " AND status = '" . Encoder::STATUS_ERROR . "' ";
}
$sql .= self::getSqlFromPost();
/**
* @var array $global
* @var object $global['mysqli']
*/
$global['lastQuery'] = $sql;
$res = $global['mysqli']->query($sql);
$rows = [];
if ($res) {
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
public static function getTotal($onlyMine = false)
{
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 ";
if ($onlyMine && !Login::isAdmin()) {
$sql .= " AND streamers_id = " . Login::getStreamerId() . " ";
}
$sql .= self::getSqlSearchFromPost();
/**
* @var array $global
* @var object $global['mysqli']
*/
$global['lastQuery'] = $sql;
$res = $global['mysqli']->query($sql);
return $res->num_rows;
}
public function getId()
{
return $this->id;
}
public function getFileURI()
{
return $this->fileURI;
}
public function getFilename()
{
return $this->filename;
}
/**
* @return string
*/
public function getStatus()
{
return $this->status;
}
public function getStatus_obs()
{
return $this->status_obs;
}
public function getReturn_vars()
{
_error_log("getReturn_vars " . $this->return_vars);
return $this->return_vars;
}
public function getWorker_ppid()
{
return intval($this->worker_ppid);
}
public function getWorker_pid()
{
return intval($this->worker_pid);
}
public function getPriority()
{
return intval($this->priority);
}
public function getCreated()
{
return $this->created;
}
public function getModified()
{
return $this->modified;
}
/**
* @return int
*/
public function getFormats_id()
{
return $this->formats_id;
}
public function setFileURI($fileURI)
{
$this->fileURI = $fileURI;
}
public function setFilename($filename)
{
$this->filename = $filename;
}
public function setStatus($status, $setStreamerLog = true)
{
_error_log("Encoder::setStatus($status) " . json_encode(debug_backtrace()));
if ($setStreamerLog && !empty($this->id) && $status != $this->status) {
self::setStreamerLog($this->id, "Status changed from {$this->status} to $status", Encoder::LOG_TYPE_StatusChanged);
}
$this->status = $status;
//_error_log('Encoder::setStatus: '.json_encode(debug_backtrace()));
switch ($status) {
case Encoder::STATUS_DONE:
case Encoder::STATUS_ERROR:
case Encoder::STATUS_QUEUE:
$this->setWorker_ppid(null);
$this->setWorker_pid(null);
break;
case Encoder::STATUS_DOWNLOADING:
case Encoder::STATUS_ENCODING:
case Encoder::STATUS_PACKING:
case Encoder::STATUS_TRANSFERRING:
default:
$this->setWorker_ppid(getmypid());
$this->setWorker_pid(null);
break;
}
}
public function setStatus_obs($status_obs)
{
if (empty($status_obs)) {
return false;
}
_error_log("Encoder::setStatus_obs " . json_encode(debug_backtrace()));
$old_status_obs = $this->status_obs;
$this->status_obs = substr($status_obs, 0, 200);
if (!empty($this->id) && $old_status_obs !== $this->status_obs) {
self::setStreamerLog($this->id, $this->status_obs, Encoder::LOG_TYPE_StatusObs);
}
}
public function setReturn_vars($return_vars)
{
$this->return_vars = $return_vars;
}
public function setWorker_ppid($worker_ppid)
{
$this->worker_ppid = $worker_ppid;
}
public function setWorker_pid($worker_pid)
{
$this->worker_pid = $worker_pid;
}
public function setReturn_varsVideos_id($videos_id)
{
$videos_id = intval($videos_id);
if (empty($videos_id)) {
return false;
}
$obj = json_decode($this->return_vars);
if (empty($obj)) {
$obj = new stdClass();
}
$obj->videos_id = $videos_id;
$this->setReturn_vars(json_encode($obj));
$this->id = $this->save();
return $this->id;
}
public function setReturn_varsVideo_id_hash($video_id_hash)
{
if (empty($video_id_hash)) {
return false;
}
$obj = json_decode($this->return_vars);
if (empty($obj)) {
$obj = new stdClass();
}
$obj->video_id_hash = $video_id_hash;
$this->setReturn_vars(json_encode($obj));
$this->id = $this->save();
return $this->id;
}
public function setPriority($priority)
{
$this->priority = intval($priority);
}
public function setCreated($created)
{
$this->created = $created;
}
public function setModified($modified)
{
$this->modified = $modified;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = substr($title, 0, 254);
}
public function getVideoDownloadedLink()
{
return $this->videoDownloadedLink;
}
public function setVideoDownloadedLink($videoDownloadedLink)
{
$this->videoDownloadedLink = substr($videoDownloadedLink, 0, 254);
}
public function getDownloadedFileName()
{
return $this->downloadedFileName;
}
public function setDownloadedFileName($downloadedFileName)
{
_error_log("setDownloadedFileName($downloadedFileName) " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
$this->downloadedFileName = substr($downloadedFileName, 0, 254);
}
/**
* @return int
*/
public function getStreamers_id()
{
return $this->streamers_id;
}
public function setStreamers_id($streamers_id)
{
$this->streamers_id = $streamers_id;
}
public function getOverride_status()
{
return $this->override_status;
}
public function setOverride_status($override_status)
{
$this->override_status = $override_status;
}
public function setFormats_id($formats_id)
{
if (!preg_match('/^\d+$/', $formats_id)) {
$formats_id = Format::createIfNotExists($formats_id);
}
$this->formats_id = $formats_id;
}
public function setFormats_idFromOrder($order)
{
$o = new Format(0);
$o->loadFromOrder($order);
$this->setFormats_id($o->getId());
}
public static function getNext()
{
global $global;
$sql = "SELECT * FROM " . static::getTableName() . " WHERE status = 'queue' OR status = 'downloaded' ";
$sql .= " ORDER BY priority ASC, id ASC LIMIT 1";
/**
* @var array $global
* @var object $global['mysqli']
*/
$res = $global['mysqli']->query($sql);
if ($res) {
return $res->fetch_assoc();
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
static function isPythonAndPytubeInstalled()
{
$pythonCommand = 'python3 --version';
$pytubeCommand = 'python3 -m pip show pytube';
// Check if Python is installed
exec($pythonCommand, $pythonOutput, $pythonReturnCode);
if ($pythonReturnCode !== 0) {
error_log("Python is not installed. Please install Python on Ubuntu using the following commands:");
error_log("sudo apt update && sudo apt install -y python3 python3-pip");
return false;
}
// Check if pytube is installed
exec($pytubeCommand, $pytubeOutput, $pytubeReturnCode);
if ($pytubeReturnCode !== 0) {
error_log("Pytube is not installed. Install it using pip with the following command:");
error_log("python3 -m pip install pytube");
return false;
}
// Both Python and pytube are installed
return true;
}
public static function getTitleFromLinkWithPytube($video_url)
{
global $global;
$downloadWithPytubeFilename = 'video_download_' . md5($video_url);
$metadataFile = "{$global['systemRootPath']}videos/pytube/{$downloadWithPytubeFilename}/metadata.json";
if (!file_exists($metadataFile)) {
$response = self::downloadWithPytube($video_url, $downloadWithPytubeFilename, 'metadata');
}
if (file_exists($metadataFile)) {
$content = file_get_contents($metadataFile);
$json = json_decode($content);
return $json->title;
}
return false;
}
public static function getDescriptionFromLinkWithPytube($video_url)
{
global $global;
$downloadWithPytubeFilename = 'video_download_' . md5($video_url);
$metadataFile = "{$global['systemRootPath']}videos/pytube/{$downloadWithPytubeFilename}/metadata.json";
if (!file_exists($metadataFile)) {
$response = self::downloadWithPytube($video_url, $downloadWithPytubeFilename, 'metadata');
}
if (file_exists($metadataFile)) {
$content = file_get_contents($metadataFile);
$json = json_decode($content);
return $json->description;
}
return false;
}
public static function getDurationFromLinkWithPytube($video_url)
{
global $global;
$downloadWithPytubeFilename = 'video_download_' . md5($video_url);
$metadataFile = "{$global['systemRootPath']}videos/pytube/{$downloadWithPytubeFilename}/metadata.json";
if (!file_exists($metadataFile)) {
$response = self::downloadWithPytube($video_url, $downloadWithPytubeFilename, 'metadata');
}
if (file_exists($metadataFile)) {
$content = file_get_contents($metadataFile);
$json = json_decode($content);
return $json->duration_seconds;
}
return false;
}
public static function getThumbsFromLinkWithPytube($video_url, $returnFileName = false)
{
global $global;
$downloadWithPytubeFilename = 'video_download_' . md5($video_url);
$File = "{$global['systemRootPath']}videos/pytube/{$downloadWithPytubeFilename}/thumbs.jpg";
if (!file_exists($File)) {
$response = self::downloadWithPytube($video_url, $downloadWithPytubeFilename, 'thumbnail');
}
if (file_exists($File)) {
if ($returnFileName) {
return $File;
} else {
$content = url_get_contents($File);
//unlink($returnTmpfname);
return $content;
}
}
return false;
}
public static function downloadWithPytube($video_url, $filename, $action = 'video')
{
global $global;
$video_url = str_replace(array('\\', "'"), array('', ''), $video_url);
$pythonScript = $global['systemRootPath'] . "objects/youtube.py";
$command = escapeshellcmd("python3 $pythonScript " . escapeshellarg($video_url) . " " . escapeshellarg($filename) . " {$action}");
_error_log("downloadWithPytube($video_url, $filename) " . $command);
exec($command, $output, $return_var);
$response = new stdClass();
$response->command = $command;
$response->output = $output;
$response->error = $return_var !== 0;
$response->filename = $filename;
$response->metadata = "{$global['systemRootPath']}videos/pytube/{$response->filename}/metadata.json";
$response->thumbnail = "{$global['systemRootPath']}videos/pytube/{$response->filename}/thumbs.jpg";
$response->video = "{$global['systemRootPath']}videos/pytube/{$response->filename}/video.mp4";
if ($response->error) {
$response->msg = "Error downloading video. Check progress.json for details.";
} else {
$response->msg = "Video downloaded successfully.";
}
return $response;
}
public static function downloadFile($queue_id)
{
global $global;
$obj = new stdClass();
$q = new Encoder($queue_id);
$url = $q->getFileURI();
//$ext = pathinfo($value, PATHINFO_EXTENSION);
$f = new Format($q->getFormats_id());
$ext = $f->getExtension_from();
if (!empty($ext)) {
$ext = ".{$ext}";
}
$dstFilepath = $global['systemRootPath'] . "videos/";
$filename = "{$queue_id}_tmpFile" . $ext;
if (!is_dir($dstFilepath)) {
mkdir($dstFilepath);
}
$obj->error = true;
$obj->filename = $filename;
$obj->pathFileName = $dstFilepath . $filename;
if (!self::canDownloadNow()) {
_error_log("downloadFile: there is a file downloading");
if (self::areDownloaded()) {
$obj->error = false;
}
return $obj;
}
if (file_exists($obj->pathFileName) && filesize($obj->pathFileName) > 20) {
if ($q->getStatus() == 'queue') {
self::setDownloaded($queue_id, $obj->pathFileName);
}
$obj->error = false;
_error_log("downloadFile: file already exists queue_id = {$queue_id} url = {$url} pathFileName = {$obj->pathFileName}");
return $obj;
}
$q->setStatus(Encoder::STATUS_DOWNLOADING);
$q->save();
_error_log("downloadFile: start queue_id = {$queue_id} url = {$url} pathFileName = {$obj->pathFileName}");
$e = Encoder::getFromFileURI($url);
if (!empty($e['downloadedFileName']) && file_exists($e['downloadedFileName'])) {
$obj->pathFileName = $e['downloadedFileName'];
$q->setDownloadedFileName($obj->pathFileName);
$q->save();
$obj->error = false;
_error_log("downloadFile: e['downloadedFileName'] = {$e['downloadedFileName']}");
return $obj;
}
if (!empty($q->getVideoDownloadedLink())) {
$videoURL = $q->getVideoDownloadedLink();
if (isFTPURL($videoURL)) {
require_once __DIR__ . '/FTPDownloader.php';
FTPDownloader::copy($videoURL, $obj->pathFileName);
$obj->error = !file_exists($obj->pathFileName);
} else {
$downloadWithPytubeFilename = '';
if (self::isPythonAndPytubeInstalled() && isYouTubeUrl($videoURL)) {
$downloadWithPytubeFilename = 'video_download_' . $queue_id;
$response = self::downloadWithPytube($videoURL, $downloadWithPytubeFilename);
}
if (empty($downloadWithPytubeFilename) || $response->error) {
//begin youtube-dl downloading and symlink it to the video temp file
$response = static::getYoutubeDl($videoURL, $queue_id, $obj->pathFileName);
if (!empty($response)) {
_error_log("downloadFile:getYoutubeDl SUCCESS queue_id = {$queue_id}");
$obj->pathFileName = $response;
$obj->error = false;
} else {
_error_log("downloadFile:getYoutubeDl ERROR queue_id = {$queue_id}");
$obj->error = false;
}
} else {
$obj->pathFileName = "{$global['systemRootPath']}videos/pytube/{$downloadWithPytubeFilename}/video.mp4";
}
}
} else {
_error_log("downloadFile: not using getYoutubeDl");
//symlink the downloaded file to the video temp file ($obj-pathFileName)
if (strpos($url, "http") !== false) {
//_error_log("downloadFile:strpos global['webSiteRootURL'] = {$global['webSiteRootURL']}");
if (strpos($url, $global['webSiteRootURL']) === false) {
_error_log("downloadFile: keep the same URL");
$downloadedFile = $url;
} else {
_error_log("downloadFile: this file was uploaded from file and thus is in the videos");
//this file was uploaded "from file" and thus is in the videos directory
$downloadedFile = substr($url, strrpos($url, '/') + 1);
$downloadedFile = $dstFilepath . $downloadedFile;
}
} else {
_error_log("downloadFile: this file was a bulk encode and thus is on a local directory");
//this file was a "bulk encode" and thus is on a local directory
$downloadedFile = $url;
}
_error_log("downloadFile: downloadedFile = {$downloadedFile} | url = {$url}");
$response = static::getVideoFile($url, $queue_id, $downloadedFile, $obj->pathFileName);
$obj->error = empty(filesize($obj->pathFileName));
}
if ($obj->error == false && file_exists($obj->pathFileName)) {
//_error_log("downloadFile: success");
$obj->msg = "We downloaded the file with success";
$q->setDownloadedFileName($obj->pathFileName);
$q->save();
} else {
$obj->error = true;
}
if ($obj->error) {
$destination = "{$dstFilepath}{$filename}";
//_error_log("downloadFile: error");
$obj->msg = "Could not save file {$url} in $destination";
// Note: Removed duplicate getYoutubeDl retry here since getYoutubeDl already
// has multiple fallback strategies built-in. Double retry was causing excessive attempts.
}
_error_log("downloadFile: " . json_encode($obj));
if (empty($obj->error)) {
self::setDownloaded($queue_id, $obj->pathFileName);
} else {
self::setStatusError($queue_id, $obj->msg, 1);
}
return $obj;
}
private static function setDownloaded($queue_id, $filePath)
{
$encoder = new Encoder($queue_id);
$msg = "Original filesize is " . humanFileSize(filesize($filePath));
_error_log($msg);
$encoder->setStatus(Encoder::STATUS_DOWNLOADED);
$encoder->setStatus_obs($msg);
$encoder->setDownloadedFileName($filePath);
return $encoder->save();
}
public static function getYoutubeDl($videoURL, $queue_id, $destinationFile, $addOauthFromProvider = '')
{
global $global;
$videoURL = str_replace("'", '', $videoURL);
$videoURL = trim($videoURL);
if (strpos($videoURL, "/") === 0) {
if (!file_exists($videoURL)) {
$videoURL2 = str_replace(' ', '-', $videoURL);
if (file_exists($videoURL2)) {
$videoURL = $videoURL2;
return _rename($videoURL, $destinationFile) ? $destinationFile : $videoURL;
} else {
_error_log("getYoutubeDl: Local file does not exists $videoURL " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
return false;
}
}
}
// Check if JavaScript runtime is available for YouTube downloads
if (isYouTubeUrl($videoURL)) {
$jsRuntime = self::checkJSRuntimeAvailable();
if (!$jsRuntime['available']) {
_error_log("getYoutubeDl: JavaScript runtime not available - " . $jsRuntime['error']);
self::setStreamerLog($queue_id, "ERROR: JavaScript runtime required for YouTube. " . $jsRuntime['error'], Encoder::LOG_TYPE_ERROR);
return false;
}
_error_log("getYoutubeDl: Using JavaScript runtime: {$jsRuntime['runtime']} at {$jsRuntime['path']}");
}
$videoURLEscaped = escapeshellarg($videoURL);
$tmpfname = _get_temp_file('youtubeDl');
$progressFile = "{$global['systemRootPath']}videos/{$queue_id}_tmpFile_downloadProgress.txt";
$e = new Encoder($queue_id);
$streamers_id = $e->getStreamers_id();
// Define fallback strategies with different approaches
$strategies = self::getYoutubeDlStrategies($addOauthFromProvider, $streamers_id, $tmpfname, $videoURLEscaped);
$return_val = 1;
$lastError = '';
foreach ($strategies as $index => $strategy) {
$strategyNum = $index + 1;
$strategyName = $strategy['name'];
$cmd = $strategy['cmd'];
_error_log("getYoutubeDl: Strategy {$strategyNum} ({$strategyName}): {$cmd} progressFile={$progressFile}");
self::setStreamerLog($queue_id, "Trying download strategy {$strategyNum}: {$strategyName}", Encoder::LOG_TYPE_INFO);
exec($cmd . " 1> {$progressFile} 2>&1", $output, $return_val);
if ($return_val === 0) {
_error_log("getYoutubeDl: Strategy {$strategyNum} ({$strategyName}) SUCCESS");
break;
}
$ytdlpError = self::getYtdlpErrorFromFile($progressFile);
$lastError = $ytdlpError;
_error_log("getYoutubeDl ERROR strategy {$strategyNum} ({$strategyName}): return_val={$return_val} error={$ytdlpError}");
self::setStreamerLog($queue_id, "Strategy {$strategyNum} ({$strategyName}) failed: " . substr($ytdlpError, 0, 200), Encoder::LOG_TYPE_ERROR);
// Small delay between attempts to avoid rate limiting
sleep(2);
}
// If all strategies failed, try with OAuth as last resort
if ($return_val !== 0) {
if (empty($addOauthFromProvider) && isYouTubeUrl($videoURL) && Encoder::streamerHasOauth('youtube', $streamers_id)) {
_error_log("getYoutubeDl: All strategies failed, trying with OAuth");
self::setStreamerLog($queue_id, "Trying OAuth authentication as last resort", Encoder::LOG_TYPE_INFO);
return self::getYoutubeDl($videoURL, $queue_id, $destinationFile, 'youtube');
} else {
if (!empty($addOauthFromProvider)) {
_error_log("getYoutubeDl: ERROR OAuth already tried");
}
if (!isYouTubeUrl($videoURL)) {
_error_log("getYoutubeDl: ERROR not a youtube URL $videoURL");
}
if (!Encoder::streamerHasOauth('youtube', $streamers_id)) {
_error_log("getYoutubeDl: ERROR streamers_id does not have oauth streamers_id=$streamers_id");
}
self::setStreamerLog($queue_id, "All download strategies failed. Last error: " . $lastError, Encoder::LOG_TYPE_ERROR);
}
return false;
}
$file = $tmpfname . ".mp4";
if (!file_exists($file)) {
_error_log("getYoutubeDl: ERROR MP4 NOT FOUND {$file} ");
$mkvFile = $tmpfname . ".mkv";
if (file_exists($mkvFile)) {
$file = $mkvFile;
} else {
_error_log("getYoutubeDl: ERROR MKV NOT FOUND {$mkvFile} ");
$dl = static::getYoutubeDlProgress($queue_id);
$file = $dl->filename;
}
}
_error_log("getYoutubeDl: Copying [$file] to [$destinationFile] ");
// instead of loading the whole file into memory to dump it into a new filename
// the file is just symlinked
////// symlink($file, $destinationFile);
////// symlink not allowed without apache configuration
return _rename($file, $destinationFile) ? $destinationFile : $file;
}
public static function getYoutubeDlProgress($queue_id)
{
global $global;
$obj = new stdClass();
$obj->filename = "";
$obj->progress = 0;
$obj->queue_id = $queue_id;
$file = "{$global['systemRootPath']}videos/{$queue_id}_tmpFile_downloadProgress.txt";
if (!file_exists($file) || filesize($file) > 5000000) {
return $obj;
}
try {
$text = url_get_contents($file);
} catch (Exception $exc) {
_error_log($exc->getMessage());
}
if (!empty($text)) {
preg_match('/Merging formats into "([\/a-z0-9._]+)"/i', $text, $matches);
if (!empty($matches[1])) {
$obj->filename = $matches[1];
}
preg_match_all('/\[download\] +([0-9.]+)% of/', $text, $matches, PREG_SET_ORDER);
//$m = end($matches);
//$obj->progress = empty($m[1]) ? 0 : intval($m[1]);
foreach ($matches as $m) {
$obj->progress = empty($m[1]) ? 0 : intval($m[1]);
if ($obj->progress == 100) {
break;
}
}
}
return $obj;
}
public static function getVideoFile($videoURL, $queue_id, $downloadedFile, $destinationFile)
{
// the file has already been downloaded
// all that is needed to do is create a tempfile reference to the original
// symlink($downloadedFile, $destinationFile);
global $global;
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
"allow_self_signed" => true
),
);
$global['queue_id'] = $queue_id;
$ctx = stream_context_create($arrContextOptions);
/////whoops! apache has to be taught to use symlinks so this won't work
/////trying copy instead
_error_log("getVideoFile start($videoURL, $queue_id, $downloadedFile, $destinationFile)");
_rename($downloadedFile, $destinationFile, $ctx);
_error_log("getVideoFile done " . humanFileSize(filesize($destinationFile)));
//copied from stream_contenxt_set_params
// the file is already 100% downloaded by now
$txt = "[download] 100% of all Bytes";
// save this progress file
$myfile = file_put_contents($global['systemRootPath'] . 'videos/' . $global['queue_id'] . '_tmpFile_downloadProgress.txt', $txt . PHP_EOL, FILE_APPEND | LOCK_EX);
return $myfile;
}
public static function areDownloading($status = array())
{
if (empty($status)) {
$status = array(Encoder::STATUS_DOWNLOADED, Encoder::STATUS_DOWNLOADING);
}
return self::getQueue($status);
}
public static function areEncoding()
{
//return self::getQueue($status = array(Encoder::STATUS_ENCODING, Encoder::STATUS_DOWNLOADING));
return self::getQueue($status = array(Encoder::STATUS_ENCODING));
}
public static function areDownloaded()
{
return self::getQueue($status = array(Encoder::STATUS_DOWNLOADED));
}
public static function areTransferring()
{
return self::getQueue($status = array(Encoder::STATUS_TRANSFERRING));
}
public static function getQueue($status = array(), $streamers_id = 0)
{
global $global;
if (empty($status)) {
$status = array(Encoder::STATUS_ENCODING, Encoder::STATUS_DOWNLOADING);