Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17002 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
17002 efrain 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
 
8
use Laminas\Mvc\Controller\AbstractActionController;
9
use Laminas\Log\LoggerInterface;
10
use Laminas\View\Model\ViewModel;
11
use Laminas\View\Model\JsonModel;
12
use LeadersLinked\Library\Functions;
13
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
14
use LeadersLinked\Library\Image;
15
use LeadersLinked\Mapper\MediaFileMapper;
16
use LeadersLinked\Model\MediaFile;
17
use LeadersLinked\Library\Storage;
18
use LeadersLinked\Form\Media\FileForm;
19
use LeadersLinked\Mapper\MediaCategoryMapper;
20
use LeadersLinked\Model\VideoConvert;
21
use LeadersLinked\Mapper\VideoConvertMapper;
22
 
23
 
24
class MediaFileController extends AbstractActionController
25
{
26
    /**
27
     *
28
     * @var \Laminas\Db\Adapter\AdapterInterface
29
     */
30
    private $adapter;
31
 
32
    /**
33
     *
34
     * @var \LeadersLinked\Cache\CacheInterface
35
     */
36
    private $cache;
37
 
38
 
39
    /**
40
     *
41
     * @var \Laminas\Log\LoggerInterface
42
     */
43
    private $logger;
44
 
45
    /**
46
     *
47
     * @var array
48
     */
49
    private $config;
50
 
51
 
52
    /**
53
     *
54
     * @var \Laminas\Mvc\I18n\Translator
55
     */
56
    private $translator;
57
 
58
 
59
    /**
60
     *
61
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
62
     * @param \LeadersLinked\Cache\CacheInterface $cache
63
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
64
     * @param array $config
65
     * @param \Laminas\Mvc\I18n\Translator $translator
66
     */
67
    public function __construct($adapter, $cache, $logger, $config, $translator)
68
    {
69
        $this->adapter      = $adapter;
70
        $this->cache        = $cache;
71
        $this->logger       = $logger;
72
        $this->config       = $config;
73
        $this->translator   = $translator;
74
    }
75
 
76
    /**
77
     *
78
     * Generación del listado de perfiles
79
     * {@inheritDoc}
80
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
81
     */
82
    public function indexAction()
83
    {
84
        $request = $this->getRequest();
85
        $currentUserPlugin = $this->plugin('currentUserPlugin');
86
        $currentCompany = $currentUserPlugin->getCompany();
87
        $currentUser    = $currentUserPlugin->getUser();
88
 
89
 
90
        $request = $this->getRequest();
91
        if($request->isGet()) {
92
 
93
 
94
            $headers  = $request->getHeaders();
95
 
96
            $isJson = false;
97
            if($headers->has('Accept')) {
98
                $accept = $headers->get('Accept');
99
 
100
                $prioritized = $accept->getPrioritized();
101
 
102
                foreach($prioritized as $key => $value) {
103
                    $raw = trim($value->getRaw());
104
 
105
                    if(!$isJson) {
106
                        $isJson = strpos($raw, 'json');
107
                    }
108
 
109
                }
110
            }
111
 
112
           // $isJson = true;
113
            if($isJson) {
114
                $category = null;
115
                $uuid = \LeadersLinked\Library\Functions::sanitizeFilterString($this->params()->fromQuery('category'));
116
                if($uuid) {
117
                    $categoryMapper = \LeadersLinked\Mapper\MediaCategoryMapper::getInstance($this->adapter);
118
                    $category = $categoryMapper->fetchOneByUuid($uuid);
119
                    if(!$category) {
120
 
121
                        if(!$category) {
122
                            return new JsonModel([
123
                                'success'   => false,
124
                                'data'   => 'ERROR_MEDIA_CATEGORY_NOT_FOUND'
125
                            ]);
126
                        }
127
 
128
                        if($category->company_id != $currentCompany->id) {
129
                            return new JsonModel([
130
                                'success'   => false,
131
                                'data'   => 'ERROR_UNAUTHORIZED'
132
                            ]);
133
                        }
134
 
135
 
136
                    }
137
 
138
 
139
                }
140
 
141
                if(!$category) {
142
                    return new JsonModel([
143
                        'success' => true,
144
                        'data' => [
145
                            'items' => [],
146
                            'total' => 0,
147
                        ]
148
                    ]);
149
                }
150
 
151
                $search = $this->params()->fromQuery('search', []);
152
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
153
 
154
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
155
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
156
                $order =  $this->params()->fromQuery('order', []);
157
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
158
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
159
 
160
                $fields =  ['name'];
161
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
162
 
163
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
164
                    $order_direction = 'ASC';
165
                }
166
 
167
 
17018 efrain 168
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 169
                $target_path = $storage->getPathMedia();
170
 
171
 
172
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
173
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'media/files/delete');
174
 
175
 
176
                $mediaFileMapper = MediaFileMapper::getInstance($this->adapter);
177
 
178
                $paginator = $mediaFileMapper->fetchAllDataTableByCategoryId($category->id, $search, $page, $records_x_page, $order_field, $order_direction);
179
 
180
 
181
 
182
                $records = $paginator->getCurrentItems();
183
 
184
                $items = [];
185
                foreach($records as $record)
186
                {
187
 
188
 
189
                    if($record->type == MediaFile::TYPE_IMAGE) {
190
 
191
                        $urlFile = $storage->getGenericImage($target_path, $record->uuid, $record->file);
192
                    } else {
193
                        $urlFile = $storage->getGenericFile($target_path, $record->uuid, $record->file);
194
                    }
195
 
196
                    if($record->preview) {
197
                        $urlPreview = $storage->getGenericImage($target_path, $record->uuid, $record->preview);
198
                    } else {
199
                        $urlPreview = '';
200
                    }
201
 
202
 
203
                    $item = [
204
 
205
                        'name' => $record->name,
206
                        'file' => [
207
                           'filename'   => $record->file,
208
                           'url'        => $urlFile,
209
                            'type'      => $record->type,
210
                        ],
211
                        'preview'       => [
212
                            'filename'   => $record->preview,
213
                            'url'        => $urlPreview,
214
                        ],
215
                        'actions' => [
216
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('media/files/delete', ['id' => $record->uuid ]) : '',
217
                        ]
218
 
219
 
220
                    ];
221
 
222
 
223
                    array_push($items, $item);
224
                }
225
 
226
 
227
 
228
                return new JsonModel([
229
                    'success' => true,
230
                    'data' => [
231
                        'items' => $items,
232
                        'total' => $paginator->getTotalItemCount(),
233
                    ]
234
                ]);
235
 
236
 
237
 
238
            } else {
239
 
240
                $categories = [];
241
 
242
                $categoryMapper = MediaCategoryMapper::getInstance($this->adapter);
243
                $records = $categoryMapper->fetchAllByCompanyId($currentCompany->id);
244
                foreach($records as $record)
245
                {
246
                    $categories[  $record->uuid ] = $record->name;
247
                }
248
 
249
 
250
                $form = new FileForm();
251
                $this->layout()->setTemplate('layout/layout-backend.phtml');
252
                $viewModel = new ViewModel();
253
                $viewModel->setTemplate('leaders-linked/media/files.phtml');
254
                $viewModel->setVariables([
255
                   'categories' => $categories,
256
                   'form' => $form,
257
 
258
 
259
                ]);
260
                return $viewModel ;
261
            }
262
 
263
        } else {
264
            return new JsonModel([
265
                'success' => false,
266
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
267
            ]);
268
        }
269
    }
270
 
271
    public function uploadAction()
272
    {
273
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
274
        $currentCompany     = $currentUserPlugin->getCompany();
275
        $currentUser        = $currentUserPlugin->getUser();
276
 
277
        $request    = $this->getRequest();
278
 
279
        if($request->isPost()) {
280
 
281
            $category = null;
282
            $uuid = \LeadersLinked\Library\Functions::sanitizeFilterString($this->params()->fromPost('category'));
283
            if($uuid) {
284
                $categoryMapper = \LeadersLinked\Mapper\MediaCategoryMapper::getInstance($this->adapter);
285
                $category = $categoryMapper->fetchOneByUuid($uuid);
286
                if(!$category) {
287
 
288
                    if(!$category) {
289
                        return new JsonModel([
290
                            'success'   => false,
291
                            'data'   => 'ERROR_MEDIA_CATEGORY_NOT_FOUND'
292
                        ]);
293
                    }
294
 
295
                    if($category->company_id != $currentCompany->id) {
296
                        return new JsonModel([
297
                            'success'   => false,
298
                            'data'   => 'ERROR_UNAUTHORIZED'
299
                        ]);
300
                    }
301
 
302
 
303
                }
304
 
305
 
306
            }
307
 
308
            if(!$category) {
309
                return new JsonModel([
310
                    'success'   => false,
311
                    'data'   => 'ERROR_MEDIA_CATEGORY_NOT_FOUND'
312
                ]);
313
            }
314
 
315
 
316
            $form = new FileForm();
317
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
318
 
319
            $form->setData($dataPost);
320
 
321
            if($form->isValid()) {
322
                $dataPost = (array) $form->getData();
323
 
324
                $hydrator = new ObjectPropertyHydrator();
325
                $mediaFile = new MediaFile();
326
                $hydrator->hydrate($dataPost, $mediaFile);
327
 
328
                $mediaFile->category_id = $category->id;
329
                $mediaFile->company_id  = $category->company_id;
330
                $mediaFile->file        = 'tmp';
331
                $mediaFile->type        = 'tmp';
332
 
333
                $files = $this->getRequest()->getFiles()->toArray();
334
                $media_type = '';
335
                $media_tmp_filename = '';
336
                $media_filename = '';
337
 
338
                if (isset($files['file']) && empty($files['file']['error'])) {
339
                    $media_tmp_filename  = $files['file']['tmp_name'];
17018 efrain 340
                    $media_filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
17002 efrain 341
 
342
                    $mime_type = mime_content_type($media_tmp_filename);
343
 
344
 
345
                    if ($mime_type == 'image/jpg' || $mime_type == 'image/jpeg' || $mime_type == 'image/png') {
346
                        $media_type = MediaFile::TYPE_IMAGE;
347
                    } else if ($mime_type ==  'video/quicktime' ||  $mime_type == 'video/webm' || $mime_type == 'video/mpeg' || $mime_type == 'video/mpg' || $mime_type == 'video/mp4') {
348
                        $media_type = MediaFile::TYPE_VIDEO;
349
                    } else if ($mime_type == 'audio/wav' || $mime_type == 'audio/mpeg') {
350
                        $media_type =  MediaFile::TYPE_AUDIO;
351
                    }
352
                }
353
 
354
 
355
 
356
 
357
                if(empty($media_type)) {
358
                   return new JsonModel([
359
                        'success'   => false,
360
                        'data'   => 'ERROR_MEDIA_CATEGORY_NOT_FOUND'
361
                    ]);
362
 
363
                }
364
 
365
 
366
 
367
                $fileMapper = MediaFileMapper::getInstance($this->adapter);
368
                if($fileMapper->insert($mediaFile)) {
369
                    $mediaFile = $fileMapper->fetchOne($mediaFile->id);
370
 
17018 efrain 371
                    $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 372
                    $target_path = $storage->getPathMedia();
373
                    $interal_path = 'data' . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'tmp';
374
                    if(!file_exists($interal_path)) {
375
                        mkdir($interal_path, 0775);
376
                    }
377
 
378
                    if ($media_type == MediaFile::TYPE_AUDIO) {
379
                        if($storage->moveAndPutFile($target_path, $mediaFile->uuid, $media_tmp_filename, $media_filename)) {
380
 
381
                            $mediaFile->type    = $media_type;
382
                            $mediaFile->file    = $media_filename;
383
 
384
                            $fileMapper->update($mediaFile);
385
                        }
386
 
387
                    } else if ($media_type == MediaFile::TYPE_IMAGE) {
17018 efrain 388
 
17002 efrain 389
 
17018 efrain 390
                        $filename = substr($media_filename, 0, strrpos($media_filename, '.')).  '.png';
17002 efrain 391
 
17018 efrain 392
                        $image = Image::getInstance($this->config);
393
                        $full_tmp_filename = $image->uploadProcessWithOutChangeSize($media_tmp_filename, $filename);
394
 
395
                        if($full_tmp_filename) {
396
                            if($storage->putFile($target_path, $mediaFile->uuid,  $full_tmp_filename)) {
397
                                $mediaFile->type    = $media_type;
398
                                $mediaFile->file    = $media_filename;
399
 
400
 
401
                                $fileMapper->update($mediaFile);
402
                            }
17002 efrain 403
                        }
17018 efrain 404
 
405
 
17002 efrain 406
                    } else if ($media_type == MediaFile::TYPE_VIDEO) {
407
                        try {
408
                            $full_filename          = $interal_path . DIRECTORY_SEPARATOR. $media_filename;
409
                            $poster_filename        = substr($media_filename, 0, strrpos($media_filename, '.')).  '.jpg';
410
                            $poster_full_filename   = $interal_path . DIRECTORY_SEPARATOR . $poster_filename;
411
 
412
                            move_uploaded_file($media_tmp_filename, $full_filename);
413
 
414
                            $cmd        = "/usr/bin/ffprobe -v error -of flat=s=_ -select_streams v:0 -show_entries stream=height,width,duration  $full_filename";
415
                            $response   = trim(shell_exec($cmd));
416
 
417
                            $source_duration = 0;
418
                            $lines = explode("\n", $response);
419
                            foreach ($lines as $line) {
420
                                $line = trim(strtolower($line));
421
                                if (strpos($line, 'duration') !== false) {
422
                                    $values = explode('=', $line);
423
                                    $source_duration = intval(str_replace($values[1], '#', ''), 10);
424
                                }
425
                            }
426
 
427
 
428
                            if ($source_duration == 0) {
429
                                $second_extract = '00:00:02';
430
                            } else {
431
                                if ($source_duration > 10) {
432
                                    $second_extract = '00:00:10';
433
                                } else {
434
                                    $second_extract = '00:00:02';
435
                                }
436
                            }
437
 
438
                            //$imageSize = $this->config['leaderslinked.image_sizes.feed_image_size'];
439
 
440
                            //$cmd = "/usr/bin/ffmpeg -y -i $full_filename  -pix_fmt yuvj422p -deinterlace -an -ss $second_extract -f mjpeg -t 1 -r 1 -y -s $imageSize $generateFile";
441
                            // $cmd = "/usr/bin/ffmpeg -y -i $full_filename  -pix_fmt yuvj422p -an -ss $second_extract -f mjpeg -t 1 -r 1 -y -s $imageSize $generateFile";
442
                            $cmd = "/usr/bin/ffmpeg -y -i $full_filename  -pix_fmt yuvj422p -an -ss $second_extract -f mjpeg -t 1 -r 1 -y  $poster_full_filename";
443
                            exec($cmd);
444
 
445
 
446
                            $ok = $storage->putFile($target_path, $mediaFile->uuid, $poster_full_filename);
447
                            $ok = $ok && $storage->putFile($target_path, $mediaFile->uuid, $full_filename);
448
 
449
                            if( $ok ) {
450
 
451
 
452
                                $mediaFile->type    = $media_type;
453
                                $mediaFile->file    = basename($media_filename);
454
                                $mediaFile->preview = basename($poster_filename);
455
 
456
                                if($fileMapper->update($mediaFile)) {
457
 
458
                                    $videoConvert = new VideoConvert();
459
                                    $videoConvert->uuid     = $mediaFile->uuid;
460
                                    $videoConvert->filename = basename($media_filename);
461
                                    $videoConvert->type     = VideoConvert::TYPE_MEDIA;
462
 
463
                                    $videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);
464
                                    $videoConvertMapper->insert($videoConvert);
465
                                }
466
                            }
467
 
468
                           // @unlink($full_filename);
469
                            //@unlink($generate_full_filename);
470
 
471
 
472
 
473
                        } catch (\Throwable $e) {
474
 
475
                            $fileMapper->delete($mediaFile);
476
 
477
 
478
                            return new JsonModel([
479
                                'success'   => false,
480
                                'data'   => 'ERROR_UPLOAD_FILE'
481
                            ]);
482
 
483
                        }
484
                    }
485
 
486
                    $this->logger->info('Se agrego el archivo a la media library ' . $mediaFile->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
487
 
488
                    return new JsonModel([
489
                        'success'   => true,
490
                        'data'   => 'LABEL_RECORD_ADDED'
491
                    ]);
492
 
493
 
494
 
495
                } else {
496
                    $data = [
497
                        'success'   => false,
498
                        'data'      => $fileMapper->getError()
499
                    ];
500
 
501
                }
502
 
503
                return new JsonModel($data);
504
 
505
            } else {
506
                $messages = [];
507
                $form_messages = (array) $form->getMessages();
508
                foreach($form_messages  as $fieldname => $field_messages)
509
                {
510
 
511
                    $messages[$fieldname] = array_values($field_messages);
512
                }
513
 
514
                return new JsonModel([
515
                    'success'   => false,
516
                    'data'   => $messages
517
                ]);
518
            }
519
 
520
        } else {
521
            $data = [
522
                'success' => false,
523
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
524
            ];
525
 
526
            return new JsonModel($data);
527
        }
528
 
529
        return new JsonModel($data);
530
    }
531
 
532
    /**
533
     *
534
     * Borrar un perfil excepto el público
535
     * @return \Laminas\View\Model\JsonModel
536
     */
537
    public function deleteAction()
538
    {
539
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
540
        $currentCompany     = $currentUserPlugin->getCompany();
541
        $currentUser        = $currentUserPlugin->getUser();
542
 
543
        $request    = $this->getRequest();
544
        $id   = $this->params()->fromRoute('id');
545
 
546
 
547
        $fileMapper = MediaFileMapper::getInstance($this->adapter);
548
        $file = $fileMapper->fetchOneByUuid($id);
549
        if(!$file) {
550
            return new JsonModel([
551
                'success'   => false,
552
                'data'   => 'ERROR_MEDIA_FILE_NOT_FOUND'
553
            ]);
554
        }
555
 
556
        if($file->company_id != $currentCompany->id) {
557
            return new JsonModel([
558
                'success'   => false,
559
                'data'   => 'ERROR_UNAUTHORIZED'
560
            ]);
561
        }
562
 
563
 
564
 
565
        if($request->isPost()) {
566
 
567
 
568
 
569
            $result = $fileMapper->delete($file);
570
            if($result) {
571
                $this->logger->info('Se borro el el archivo de la media query : ' .  $file->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
572
 
17018 efrain 573
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 574
                $target_path = $storage->getPathMedia();
575
 
576
                $storage->deleteFile($target_path, $file->uuid, $file->file);
577
 
578
 
579
                if($file->type == MediaFile::TYPE_VIDEO) {
580
                    $videoConvertMapper = VideoConvertMapper::getInstance($this->adapter);
581
                    $videoConvertMapper->deleteByUuidAndType($file->uuid, $file->type);
582
                }
583
 
584
 
585
                $data = [
586
                    'success' => true,
587
                    'data' => 'LABEL_RECORD_DELETED'
588
                ];
589
            } else {
590
 
591
                $data = [
592
                    'success'   => false,
593
                    'data'      => $fileMapper->getError()
594
                ];
595
 
596
                return new JsonModel($data);
597
            }
598
 
599
        } else {
600
            $data = [
601
                'success' => false,
602
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
603
            ];
604
 
605
            return new JsonModel($data);
606
        }
607
 
608
        return new JsonModel($data);
609
    }
610
 
611
 
17018 efrain 612
 
17002 efrain 613
 
614
}