This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Block\Adminhtml\Product;
use Esun\Video\Model\Config;
use Esun\Video\Model\ResourceModel\Video\CollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Catalog\Model\Product\Media\Config as ProductMediaConfig;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class Upload extends Template
{
private ?array $libraryItems = null;
public function __construct(
Context $context,
private readonly Config $config,
private readonly Json $json,
private readonly CollectionFactory $collectionFactory,
private readonly StoreManagerInterface $storeManager,
private readonly Filesystem $filesystem,
private readonly ProductMediaConfig $productMediaConfig,
array $data = []
) {
parent::__construct($context, $data);
}
public function getOptionsJson(): string
{
return $this->json->serialize([
'enabled' => $this->config->isEnabled(),
'uploadUrl' => $this->getUrl('esun_video/upload/chunk'),
'libraryUrl' => $this->getUrl('esun_video/video/library'),
'chunkSize' => $this->config->getChunkSizeBytes(),
'libraryItems' => $this->getLibraryItems(),
]);
}
public function getLibraryItems(): array
{
if ($this->libraryItems !== null) {
return $this->libraryItems;
}
$baseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$items = [];
foreach ($this->collectionFactory->create()
->addFieldToFilter('status', 1)
->setOrder('video_id', 'DESC') as $video) {
$coverPath = (string)$video->getData('cover_path');
$extension = strtolower(pathinfo($coverPath, PATHINFO_EXTENSION)) ?: 'jpg';
$galleryFile = '/e/s/esun-library-' . (int)$video->getId() . '.' . $extension;
$tmpPath = $this->productMediaConfig->getTmpMediaPath($galleryFile);
if ($coverPath !== '' && $media->isExist($coverPath) && !$media->isExist($tmpPath)) {
$media->create(dirname($tmpPath));
$media->writeFile($tmpPath, $media->readFile($coverPath));
}
$items[] = [
'id' => (int)$video->getId(),
'title' => (string)$video->getData('title'),
'description' => (string)$video->getData('description'),
'video_url' => $baseUrl . ltrim((string)$video->getData('video_path'), '/'),
'cover_url' => $this->productMediaConfig->getTmpMediaUrl($galleryFile),
'gallery_file' => $galleryFile . '.tmp',
'duration' => (float)$video->getData('duration'),
'size' => (int)$video->getData('size'),
'width' => (int)$video->getData('width'),
'height' => (int)$video->getData('height'),
'resolution' => (string)$video->getData('resolution'),
];
}
return $this->libraryItems = $items;
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Block\Adminhtml\Video;
use Esun\Video\Model\Video;
use Esun\Video\Model\VideoFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class EditBlock extends Template
{
private ?Video $video = null;
public function __construct(
Context $context,
private readonly VideoFactory $videoFactory,
private readonly StoreManagerInterface $storeManager,
array $data = []
) {
parent::__construct($context, $data);
}
public function getVideo(): Video
{
if ($this->video === null) {
$this->video = $this->videoFactory->create()
->load((int)$this->getRequest()->getParam('id'));
if (!$this->video->getId()) {
throw new NoSuchEntityException(__('The video no longer exists.'));
}
}
return $this->video;
}
public function getSaveUrl(): string
{
return $this->getUrl('esun_video/video/save');
}
public function getBackUrl(): string
{
return $this->getUrl('esun_video/video/index');
}
public function getMediaUrl(string $path): string
{
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
}
}
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Block\Adminhtml\Video;
use Esun\Video\Model\Config;
use Esun\Video\Model\MediaBinaryStatus;
use Esun\Video\Model\ResourceModel\Video\CollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class ListBlock extends Template
{
private ?\Esun\Video\Model\ResourceModel\Video\Collection $videos = null;
public function __construct(
Context $context,
private readonly CollectionFactory $collectionFactory,
private readonly StoreManagerInterface $storeManager,
private readonly Config $config,
private readonly MediaBinaryStatus $mediaBinaryStatus,
private readonly Json $json,
array $data = []
) {
parent::__construct($context, $data);
}
public function getVideos()
{
if ($this->videos === null) {
$this->videos = $this->collectionFactory->create()->setOrder('video_id', 'DESC');
$title = $this->getTitleFilter();
$status = $this->getStatusFilter();
if ($title !== '') {
$this->videos->addFieldToFilter('title', ['like' => '%' . $title . '%']);
}
if ($status !== '') {
$this->videos->addFieldToFilter('status', (int)$status);
}
}
return $this->videos;
}
public function getTitleFilter(): string
{
return trim((string)$this->getRequest()->getParam('title'));
}
public function getStatusFilter(): string
{
$status = (string)$this->getRequest()->getParam('status');
return in_array($status, ['0', '1'], true) ? $status : '';
}
public function getFilterUrl(): string
{
return $this->getUrl('esun_video/video/index');
}
public function getMissingBinaries(): array
{
return $this->mediaBinaryStatus->getMissingBinaries();
}
public function getMediaUrl(string $path): string
{
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
}
public function getDeleteUrl(int $id): string
{
return $this->getUrl('esun_video/video/delete', ['id' => $id]);
}
public function getEditUrl(int $id): string
{
return $this->getUrl('esun_video/video/edit', ['id' => $id]);
}
public function getUploadOptionsJson(): string
{
return $this->json->serialize([
'enabled' => $this->config->isEnabled(),
'uploadUrl' => $this->getUrl('esun_video/upload/chunk'),
'indexUrl' => $this->getUrl('esun_video/video/index'),
'chunkSize' => $this->config->getChunkSizeBytes(),
]);
}
public function isUploadEnabled(): bool
{
return $this->config->isEnabled();
}
}
@@ -0,0 +1,179 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Controller\Adminhtml\Upload;
use Esun\Video\Model\Config;
use Esun\Video\Model\Ffmpeg;
use Esun\Video\Model\Ffprobe;
use Esun\Video\Model\VideoFactory;
use Magento\Backend\App\Action;
use Magento\Catalog\Model\Product\Media\Config as ProductMediaConfig;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\UrlInterface;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Store\Model\StoreManagerInterface;
class Chunk extends Action
{
public const ADMIN_RESOURCE = 'Esun_Video::upload';
public function __construct(
Action\Context $context,
private readonly JsonFactory $jsonFactory,
private readonly Filesystem $filesystem,
private readonly Config $config,
private readonly Ffprobe $ffprobe,
private readonly Ffmpeg $ffmpeg,
private readonly VideoFactory $videoFactory,
private readonly UploaderFactory $uploaderFactory,
private readonly ProductMediaConfig $productMediaConfig,
private readonly StoreManagerInterface $storeManager
) {
parent::__construct($context);
}
public function execute()
{
$result = $this->jsonFactory->create();
try {
if (!$this->config->isEnabled()) {
throw new LocalizedException(__('Video upload is disabled.'));
}
$title = trim((string)$this->getRequest()->getParam('title'));
if ($title === '') {
throw new LocalizedException(__('Title is required.'));
}
$uploadId = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)$this->getRequest()->getParam('upload_id'));
$index = (int)$this->getRequest()->getParam('index');
$total = (int)$this->getRequest()->getParam('total');
$name = basename((string)$this->getRequest()->getParam('name'));
if ($uploadId === '' || $index < 0 || $total < 1 || $index >= $total || strtolower(pathinfo($name, PATHINFO_EXTENSION)) !== 'mp4') {
throw new LocalizedException(__('Invalid MP4 upload request.'));
}
if (!isset($_FILES['chunk']) || (int)$_FILES['chunk']['error'] !== UPLOAD_ERR_OK) {
throw new LocalizedException(__('The video chunk was not uploaded.'));
}
$var = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$chunkDir = 'esun_video/chunks/' . $uploadId;
$var->create($chunkDir);
$var->writeFile($chunkDir . '/' . $index . '.part', (string)file_get_contents($_FILES['chunk']['tmp_name']));
if ($index + 1 < $total) {
return $result->setData(['success' => true, 'completed' => false, 'next' => $index + 1]);
}
$assembled = 'esun_video/assembled/' . $uploadId . '.mp4';
$var->create(dirname($assembled));
$absolute = $var->getAbsolutePath($assembled);
$handle = fopen($absolute, 'wb');
if ($handle === false) {
throw new LocalizedException(__('Unable to assemble the uploaded video.'));
}
try {
for ($part = 0; $part < $total; $part++) {
$partPath = $chunkDir . '/' . $part . '.part';
if (!$var->isExist($partPath)) {
throw new LocalizedException(__('Video chunk %1 is missing.', $part));
}
$input = fopen($var->getAbsolutePath($partPath), 'rb');
if ($input === false) {
throw new LocalizedException(__('Unable to read video chunk %1.', $part));
}
stream_copy_to_stream($input, $handle);
fclose($input);
}
} finally {
fclose($handle);
}
$metadata = $this->ffprobe->inspect($absolute);
$cover = $this->saveCover($uploadId, $absolute);
$safeName = preg_replace('/[^a-zA-Z0-9_-]+/', '-', pathinfo($name, PATHINFO_FILENAME));
$videoPath = $this->config->getMediaPath() . '/videos/' . date('Y/m') . '/'
. trim((string)$safeName, '-') . '-' . substr($uploadId, 0, 12) . '.mp4';
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$media->create(dirname($videoPath));
$var->renameFile($assembled, $videoPath, $media);
$video = $this->videoFactory->create();
$video->setData([
'title' => $title,
'description' => trim((string)$this->getRequest()->getParam('description')),
'video_path' => $videoPath,
'cover_path' => $cover['permanent_path'],
'status' => $this->getRequest()->getParam('status', '1') === '0' ? 0 : 1,
'duration' => $metadata['duration'],
'size' => $metadata['size'],
'width' => $metadata['width'],
'height' => $metadata['height'],
'resolution' => $metadata['resolution'],
'original_name' => $name,
])->save();
$var->delete($chunkDir);
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
return $result->setData([
'success' => true,
'completed' => true,
'video' => [
'id' => (int)$video->getId(),
'title' => $title,
'description' => (string)$video->getData('description'),
'video_url' => $mediaUrl . ltrim($videoPath, '/'),
'cover_url' => $cover['url'],
'gallery_file' => $cover['gallery_file'],
'metadata' => $metadata,
'disabled' => (int)!$video->getData('status'),
],
]);
} catch (\Throwable $e) {
return $result->setHttpResponseCode(400)->setData(['success' => false, 'message' => $e->getMessage()]);
}
}
private function saveCover(string $uploadId, string $absoluteVideo): array
{
if (isset($_FILES['cover']) && (int)$_FILES['cover']['error'] === UPLOAD_ERR_OK) {
$uploader = $this->uploaderFactory->create(['fileId' => 'cover']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$media = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
$saved = $uploader->save($media->getAbsolutePath($this->productMediaConfig->getBaseTmpMediaPath()));
if (!is_array($saved) || empty($saved['file'])) {
throw new LocalizedException(__('Unable to save the cover image.'));
}
$galleryFile = (string)$saved['file'];
} else {
$galleryFile = '/e/s/esun-video-' . substr($uploadId, 0, 12) . '.jpg';
$tmpPath = $this->productMediaConfig->getTmpMediaPath($galleryFile);
$var = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$generated = 'esun_video/generated_covers/' . $uploadId . '.jpg';
$var->create(dirname($generated));
$this->ffmpeg->createCover($absoluteVideo, $var->getAbsolutePath($generated));
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$media->create(dirname($tmpPath));
$media->writeFile($tmpPath, $var->readFile($generated));
$var->delete($generated);
}
$source = $this->productMediaConfig->getTmpMediaPath($galleryFile);
$extension = strtolower(pathinfo($galleryFile, PATHINFO_EXTENSION)) ?: 'jpg';
$permanent = $this->config->getMediaPath() . '/covers/' . date('Y/m') . '/'
. substr($uploadId, 0, 20) . '.' . $extension;
$mediaWrite = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaWrite->create(dirname($permanent));
$mediaWrite->writeFile($permanent, $mediaWrite->readFile($source));
return [
'gallery_file' => $galleryFile . '.tmp',
'permanent_path' => $permanent,
'url' => $this->productMediaConfig->getTmpMediaUrl($galleryFile),
];
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Controller\Adminhtml\Video;
use Esun\Video\Model\VideoFactory;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Video::delete';
public function __construct(
Action\Context $context,
private readonly VideoFactory $videoFactory,
private readonly Filesystem $filesystem
) {
parent::__construct($context);
}
public function execute()
{
$video = $this->videoFactory->create()->load((int)$this->getRequest()->getParam('id'));
if ($video->getId()) {
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
foreach (['video_path', 'cover_path'] as $field) {
$path = (string)$video->getData($field);
if ($path !== '' && $media->isExist($path)) {
$media->delete($path);
}
}
$video->delete();
$this->messageManager->addSuccessMessage(__('The video has been deleted.'));
}
return $this->resultRedirectFactory->create()->setPath('esun_video/video/index');
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Controller\Adminhtml\Video;
use Esun\Video\Model\VideoFactory;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_Video::edit';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly VideoFactory $videoFactory
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('id');
$video = $this->videoFactory->create()->load($id);
if (!$video->getId()) {
$this->messageManager->addErrorMessage(__('The video no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('esun_video/video/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_Video::videos');
$page->getConfig()->getTitle()->prepend(__('Edit Video: %1', $video->getData('title')));
return $page;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Controller\Adminhtml\Video;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_Video::videos';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_Video::videos');
$page->getConfig()->getTitle()->prepend(__('Video Management'));
return $page;
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Controller\Adminhtml\Video;
use Esun\Video\Model\ResourceModel\Video\CollectionFactory;
use Magento\Backend\App\Action;
use Magento\Catalog\Model\Product\Media\Config as ProductMediaConfig;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class Library extends Action
{
public const ADMIN_RESOURCE = 'Esun_Video::videos';
public function __construct(
Action\Context $context,
private readonly JsonFactory $jsonFactory,
private readonly CollectionFactory $collectionFactory,
private readonly StoreManagerInterface $storeManager,
private readonly Filesystem $filesystem,
private readonly ProductMediaConfig $productMediaConfig
) {
parent::__construct($context);
}
public function execute()
{
$baseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
$items = [];
foreach ($this->collectionFactory->create()->addFieldToFilter('status', 1)->setOrder('video_id', 'DESC') as $video) {
$coverPath = (string)$video->getData('cover_path');
$extension = strtolower(pathinfo($coverPath, PATHINFO_EXTENSION)) ?: 'jpg';
$galleryFile = '/e/s/esun-library-' . (int)$video->getId() . '.' . $extension;
$tmpPath = $this->productMediaConfig->getTmpMediaPath($galleryFile);
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
if ($coverPath !== '' && $media->isExist($coverPath) && !$media->isExist($tmpPath)) {
$media->create(dirname($tmpPath));
$media->writeFile($tmpPath, $media->readFile($coverPath));
}
$items[] = [
'id' => (int)$video->getId(),
'title' => (string)$video->getData('title'),
'description' => (string)$video->getData('description'),
'video_url' => $baseUrl . ltrim((string)$video->getData('video_path'), '/'),
'cover_url' => $this->productMediaConfig->getTmpMediaUrl($galleryFile),
'gallery_file' => $galleryFile . '.tmp',
'duration' => (float)$video->getData('duration'),
'size' => (int)$video->getData('size'),
'width' => (int)$video->getData('width'),
'height' => (int)$video->getData('height'),
'resolution' => (string)$video->getData('resolution'),
];
}
return $this->jsonFactory->create()->setData(['items' => $items]);
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Controller\Adminhtml\Video;
use Esun\Video\Model\Config;
use Esun\Video\Model\VideoFactory;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_Video::edit';
public function __construct(
Action\Context $context,
private readonly VideoFactory $videoFactory,
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem,
private readonly Config $config
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('video_id');
$redirect = $this->resultRedirectFactory->create();
try {
$video = $this->videoFactory->create()->load($id);
if (!$video->getId()) {
throw new LocalizedException(__('The video no longer exists.'));
}
$title = trim((string)$this->getRequest()->getParam('title'));
if ($title === '') {
throw new LocalizedException(__('Title is required.'));
}
$oldCover = (string)$video->getData('cover_path');
$newCover = $this->saveCover();
$video->addData([
'title' => $title,
'description' => trim((string)$this->getRequest()->getParam('description')),
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
]);
if ($newCover !== null) {
$video->setData('cover_path', $newCover);
}
$video->save();
if ($newCover !== null && $oldCover !== '' && $oldCover !== $newCover) {
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
if ($media->isExist($oldCover)) {
$media->delete($oldCover);
}
}
$this->messageManager->addSuccessMessage(__('The video has been saved.'));
return $redirect->setPath('esun_video/video/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath('esun_video/video/edit', ['id' => $id]);
}
}
private function saveCover(): ?string
{
if (!isset($_FILES['cover']) || (int)$_FILES['cover']['error'] === UPLOAD_ERR_NO_FILE) {
return null;
}
if ((int)$_FILES['cover']['error'] !== UPLOAD_ERR_OK) {
throw new LocalizedException(__('The cover image could not be uploaded.'));
}
$relativeDirectory = $this->config->getMediaPath() . '/covers/' . date('Y/m');
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$media->create($relativeDirectory);
$uploader = $this->uploaderFactory->create(['fileId' => 'cover']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif', 'webp']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$saved = $uploader->save($media->getAbsolutePath($relativeDirectory));
if (!is_array($saved) || empty($saved['file'])) {
throw new LocalizedException(__('Unable to save the cover image.'));
}
return trim($relativeDirectory . '/' . ltrim((string)$saved['file'], '/'), '/');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
private const PREFIX = 'esun_video/general/';
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
{
}
public function isEnabled(): bool
{
return $this->scopeConfig->isSetFlag(self::PREFIX . 'enabled', ScopeInterface::SCOPE_WEBSITE);
}
public function getMediaPath(): string
{
$path = trim((string)$this->scopeConfig->getValue(self::PREFIX . 'media_path'), '/ ');
return $path !== '' ? $path : 'esun/video';
}
public function getChunkSizeBytes(): int
{
return max(1, (int)$this->scopeConfig->getValue(self::PREFIX . 'chunk_size')) * 1024 * 1024;
}
public function getFfprobeBinary(): string
{
return trim((string)$this->scopeConfig->getValue(self::PREFIX . 'ffprobe_binary')) ?: 'ffprobe';
}
public function getFfmpegBinary(): string
{
return trim((string)$this->scopeConfig->getValue(self::PREFIX . 'ffmpeg_binary')) ?: 'ffmpeg';
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model\Config\Backend;
use Esun\Video\Model\RemoteStorage\ConfigSynchronizer;
use Magento\Framework\App\Config\Value;
class RemoteStorage extends Value
{
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
private readonly ConfigSynchronizer $configSynchronizer,
?\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
?\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
public function beforeSave()
{
if ($this->getScope() !== 'default') {
throw new \Magento\Framework\Exception\LocalizedException(
__('Media storage can only be configured at Default Config scope.')
);
}
return parent::beforeSave();
}
public function afterSave()
{
$result = parent::afterSave();
$this->configSynchronizer->synchronize($this);
return $result;
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model\Config\Backend;
use Esun\Video\Model\RemoteStorage\ConfigSynchronizer;
use Magento\Config\Model\Config\Backend\Encrypted;
class RemoteStorageEncrypted extends Encrypted
{
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Framework\Encryption\EncryptorInterface $encryptor,
private readonly ConfigSynchronizer $configSynchronizer,
?\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
?\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct(
$context,
$registry,
$config,
$cacheTypeList,
$encryptor,
$resource,
$resourceCollection,
$data
);
}
public function beforeSave()
{
if ($this->getScope() !== 'default') {
throw new \Magento\Framework\Exception\LocalizedException(
__('Media storage can only be configured at Default Config scope.')
);
}
return parent::beforeSave();
}
public function afterSave()
{
$result = parent::afterSave();
$this->configSynchronizer->synchronize($this);
return $result;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class StorageDriver implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'file', 'label' => __('Local (pub/media)')],
['value' => 'aws-s3', 'label' => __('AWS S3')],
];
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Process\Process;
class Ffmpeg
{
public function __construct(private readonly Config $config)
{
}
public function createCover(string $videoFile, string $coverFile): void
{
$process = new Process([
$this->config->getFfmpegBinary(),
'-hide_banner',
'-loglevel', 'error',
'-ss', '1',
'-i', $videoFile,
'-frames:v', '1',
'-q:v', '2',
'-y',
$coverFile,
]);
$process->setTimeout(60);
try {
$process->run();
} catch (\Throwable $e) {
throw new LocalizedException(__('Unable to run ffmpeg: %1', $e->getMessage()));
}
if (!$process->isSuccessful() || !is_file($coverFile) || filesize($coverFile) === 0) {
throw new LocalizedException(
__('ffmpeg failed to create the cover image: %1', trim($process->getErrorOutput()) ?: __('unknown error'))
);
}
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Process\Process;
class Ffprobe
{
public function __construct(private readonly Config $config)
{
}
public function inspect(string $absoluteFile): array
{
$process = new Process([
$this->config->getFfprobeBinary(),
'-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'format=format_name,duration,size:stream=width,height,codec_name',
'-of', 'json',
$absoluteFile,
]);
$process->setTimeout(60);
try {
$process->run();
} catch (\Throwable $e) {
throw new LocalizedException(__('Unable to run ffprobe: %1', $e->getMessage()));
}
if (!$process->isSuccessful()) {
throw new LocalizedException(
__('ffprobe failed: %1', trim($process->getErrorOutput()) ?: __('unknown error'))
);
}
$data = json_decode($process->getOutput(), true);
$stream = $data['streams'][0] ?? [];
$format = $data['format'] ?? [];
$formatName = strtolower((string)($format['format_name'] ?? ''));
if (!str_contains($formatName, 'mp4') && !str_contains($formatName, 'mov')) {
throw new LocalizedException(__('Only MP4 container files are supported.'));
}
$width = (int)($stream['width'] ?? 0);
$height = (int)($stream['height'] ?? 0);
if ($width <= 0 || $height <= 0) {
throw new LocalizedException(__('The MP4 file does not contain a readable video stream.'));
}
return [
'duration' => round((float)($format['duration'] ?? 0), 3),
'size' => (int)($format['size'] ?? filesize($absoluteFile)),
'width' => $width,
'height' => $height,
'resolution' => $this->getResolution($width, $height),
];
}
private function getResolution(int $width, int $height): string
{
$longEdge = max($width, $height);
$shortEdge = min($width, $height);
if ($longEdge >= 3840 || $shortEdge >= 2160) {
return '4K';
}
if ($longEdge >= 1920 || $shortEdge >= 1080) {
return '1080p';
}
return $shortEdge . 'p';
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model;
use Symfony\Component\Process\Process;
class MediaBinaryStatus
{
public function __construct(private readonly Config $config)
{
}
public function getMissingBinaries(): array
{
$binaries = [
'ffmpeg' => $this->config->getFfmpegBinary(),
'ffprobe' => $this->config->getFfprobeBinary(),
];
$missing = [];
foreach ($binaries as $name => $binary) {
if (!$this->isAvailable($binary)) {
$missing[$name] = $binary;
}
}
return $missing;
}
private function isAvailable(string $binary): bool
{
$process = new Process([$binary, '-version']);
$process->setTimeout(5);
try {
$process->run();
return $process->isSuccessful();
} catch (\Throwable) {
return false;
}
}
}
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model\RemoteStorage;
use Magento\Framework\App\Cache\Type\Config as ConfigCache;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\Value;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\DeploymentConfig\Writer;
use Magento\Framework\Config\File\ConfigFilePool;
use Magento\Framework\Exception\LocalizedException;
class ConfigSynchronizer
{
private bool $synchronized = false;
public function __construct(
private readonly DeploymentConfig $deploymentConfig,
private readonly Writer $deploymentConfigWriter,
private readonly TypeListInterface $cacheTypeList
) {
}
public function synchronize(Value $backend): void
{
if ($this->synchronized) {
return;
}
$driver = (string)$backend->getFieldsetDataValue('driver');
if (!in_array($driver, ['file', 'aws-s3'], true)) {
throw new LocalizedException(__('Unsupported media storage driver.'));
}
if (!$this->deploymentConfigWriter->checkIfWritable()) {
throw new LocalizedException(__('app/etc/env.php is not writable by the PHP process.'));
}
$remoteStorage = ['driver' => $driver];
if ($driver === 'aws-s3') {
$bucket = trim((string)$backend->getFieldsetDataValue('bucket'));
$region = trim((string)$backend->getFieldsetDataValue('region'));
if ($bucket === '' || $region === '') {
throw new LocalizedException(__('S3 Bucket and AWS Region are required.'));
}
$current = (array)$this->deploymentConfig->get('remote_storage', []);
$currentCredentials = (array)($current['config']['credentials'] ?? []);
$accessKey = $this->resolveSecret(
(string)$backend->getFieldsetDataValue('access_key'),
(string)($currentCredentials['key'] ?? '')
);
$secretKey = $this->resolveSecret(
(string)$backend->getFieldsetDataValue('secret_key'),
(string)($currentCredentials['secret'] ?? '')
);
$remoteStorage['prefix'] = trim((string)$backend->getFieldsetDataValue('prefix'), '/ ');
$remoteStorage['config'] = [
'bucket' => $bucket,
'region' => $region,
'path_style' => (int)$backend->getFieldsetDataValue('path_style'),
'credentials' => [
'key' => $accessKey,
'secret' => $secretKey,
],
];
$endpoint = trim((string)$backend->getFieldsetDataValue('endpoint'));
if ($endpoint !== '') {
$remoteStorage['config']['endpoint'] = $endpoint;
}
}
$this->deploymentConfigWriter->saveConfig(
[ConfigFilePool::APP_ENV => ['remote_storage' => $remoteStorage]],
true,
null,
[],
true
);
$this->cacheTypeList->cleanType(ConfigCache::TYPE_IDENTIFIER);
$this->synchronized = true;
}
private function resolveSecret(string $postedValue, string $currentValue): string
{
if (preg_match('/^\*+$/', $postedValue)) {
return $currentValue;
}
if ($postedValue === '') {
return '';
}
return $postedValue;
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Video extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_video', 'video_id');
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model\ResourceModel\Video;
use Esun\Video\Model\Video as VideoModel;
use Esun\Video\Model\ResourceModel\Video as VideoResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(VideoModel::class, VideoResource::class);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\Video\Model;
use Magento\Framework\Model\AbstractModel;
class Video extends AbstractModel
{
public const STATUS_DISABLED = 0;
public const STATUS_ENABLED = 1;
protected function _construct(): void
{
$this->_init(\Esun\Video\Model\ResourceModel\Video::class);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Magento_Catalog::catalog">
<resource id="Esun_Video::videos" title="Esun Video Management" sortOrder="85">
<resource id="Esun_Video::upload" title="Upload Videos" sortOrder="10"/>
<resource id="Esun_Video::edit" title="Edit Videos" sortOrder="20"/>
<resource id="Esun_Video::delete" title="Delete Videos" sortOrder="30"/>
</resource>
</resource>
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="Esun_Video::config" title="Esun Video Configuration" sortOrder="85"/>
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add id="Esun_Video::videos" title="Video Management" module="Esun_Video"
sortOrder="20" parent="Esun_ImageManager::esun"
action="esun_video/video/index" resource="Esun_Video::videos"/>
</menu>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="esun_video" frontName="esun_video">
<module name="Esun_Video" before="Magento_Backend"/>
</route>
</router>
</config>
@@ -0,0 +1,112 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="esun" translate="label" sortOrder="300">
<label>Esun</label>
</tab>
<section id="esun_video" translate="label" type="text" sortOrder="920"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Video Management</label>
<tab>esun</tab>
<resource>Esun_Video::config</resource>
<group id="general" translate="label" type="text" sortOrder="10"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Upload Configuration</label>
<field id="enabled" translate="label" type="select" sortOrder="10"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Enable Video Upload</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="media_path" translate="label comment" type="text" sortOrder="30"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Media Base Path</label>
<comment>Relative to pub/media. Example: esun/video</comment>
<validate>required-entry</validate>
</field>
<field id="chunk_size" translate="label comment" type="text" sortOrder="40"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Chunk Size (MB)</label>
<comment>Browser upload chunk size. Recommended: 5-50 MB.</comment>
<validate>required-entry validate-number validate-greater-than-zero</validate>
</field>
<field id="ffmpeg_binary" translate="label comment" type="text" sortOrder="50"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>ffmpeg Binary</label>
<comment>Used to generate a cover image from the video at the 1-second mark.</comment>
<validate>required-entry</validate>
</field>
<field id="ffprobe_binary" translate="label comment" type="text" sortOrder="60"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>ffprobe Binary</label>
<comment>Binary name or absolute path available to the PHP process.</comment>
<validate>required-entry</validate>
</field>
</group>
<group id="storage" translate="label" type="text" sortOrder="20"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Media Storage</label>
<comment>Changes are written to app/etc/env.php and take effect on the next request.</comment>
<field id="driver" translate="label comment" type="select" sortOrder="10"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Storage Driver</label>
<comment>Local stores files in pub/media. AWS S3 uses Magento RemoteStorage.</comment>
<source_model>Esun\Video\Model\Config\Source\StorageDriver</source_model>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorage</backend_model>
</field>
<field id="bucket" translate="label" type="text" sortOrder="20"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>S3 Bucket</label>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorage</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="region" translate="label" type="text" sortOrder="30"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>AWS Region</label>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorage</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="prefix" translate="label comment" type="text" sortOrder="40"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>S3 Prefix</label>
<comment>Optional directory prefix inside the bucket, for example production/media.</comment>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorage</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="endpoint" translate="label comment" type="text" sortOrder="50"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>S3 Endpoint</label>
<comment>Leave empty for AWS. Set this for an S3-compatible service.</comment>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorage</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="access_key" translate="label comment" type="obscure" sortOrder="60"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Access Key</label>
<comment>Leave both credentials empty to use an IAM role or the AWS credential provider chain.</comment>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorageEncrypted</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="secret_key" translate="label" type="obscure" sortOrder="70"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Secret Key</label>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorageEncrypted</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="path_style" translate="label comment" type="select" sortOrder="80"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Use Path-Style Endpoint</label>
<comment>Usually disabled for AWS. Some S3-compatible services require it.</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<backend_model>Esun\Video\Model\Config\Backend\RemoteStorage</backend_model>
<depends><field id="driver">aws-s3</field></depends>
</field>
<field id="sync_note" translate="label comment" type="label" sortOrder="90"
showInDefault="1" showInWebsite="0" showInStore="0">
<label>Existing Media</label>
<comment>After switching to AWS S3, run: php bin/magento remote-storage:sync. Before switching back to local, restore the S3 files into pub/media.</comment>
</field>
</group>
</section>
</system>
</config>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<esun_video>
<general>
<enabled>1</enabled>
<media_path>esun/video</media_path>
<chunk_size>10</chunk_size>
<ffmpeg_binary>ffmpeg</ffmpeg_binary>
<ffprobe_binary>ffprobe</ffprobe_binary>
</general>
<storage>
<driver>file</driver>
<prefix></prefix>
<endpoint></endpoint>
<bucket></bucket>
<region></region>
<access_key></access_key>
<secret_key></secret_key>
<path_style>0</path_style>
</storage>
</esun_video>
</default>
</config>
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="esun_video" resource="default" engine="innodb" comment="Esun Uploaded Videos">
<column xsi:type="int" name="video_id" unsigned="true" nullable="false" identity="true" comment="Video ID"/>
<column xsi:type="varchar" name="title" nullable="false" length="255" comment="Title"/>
<column xsi:type="text" name="description" nullable="true" comment="Description"/>
<column xsi:type="varchar" name="video_path" nullable="false" length="1024" comment="Media Relative Video Path"/>
<column xsi:type="varchar" name="cover_path" nullable="true" length="1024" comment="Media Relative Cover Path"/>
<column xsi:type="smallint" name="status" unsigned="true" nullable="false" default="1" comment="Status"/>
<column xsi:type="decimal" name="duration" scale="3" precision="12" nullable="false" default="0" comment="Duration Seconds"/>
<column xsi:type="bigint" name="size" unsigned="true" nullable="false" default="0" comment="File Size Bytes"/>
<column xsi:type="int" name="width" unsigned="true" nullable="false" default="0" comment="Width"/>
<column xsi:type="int" name="height" unsigned="true" nullable="false" default="0" comment="Height"/>
<column xsi:type="varchar" name="resolution" nullable="false" length="32" default="" comment="Resolution Label"/>
<column xsi:type="varchar" name="original_name" nullable="false" length="255" comment="Original File Name"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP"
on_update="true" comment="Updated At"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="video_id"/>
</constraint>
<index referenceId="ESUN_VIDEO_STATUS" indexType="btree">
<column name="status"/>
</index>
</table>
</schema>
@@ -0,0 +1,26 @@
{
"esun_video": {
"column": {
"video_id": true,
"title": true,
"description": true,
"video_path": true,
"cover_path": true,
"status": true,
"duration": true,
"size": true,
"width": true,
"height": true,
"resolution": true,
"original_name": true,
"created_at": true,
"updated_at": true
},
"constraint": {
"PRIMARY": true
},
"index": {
"ESUN_VIDEO_STATUS": true
}
}
}
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Esun_Video">
<sequence>
<module name="Magento_Catalog"/>
<module name="Magento_ProductVideo"/>
<module name="Magento_RemoteStorage"/>
<module name="Esun_ImageManager"/>
</sequence>
</module>
</config>
+6
View File
@@ -0,0 +1,6 @@
<?php
declare(strict_types=1);
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_Video', __DIR__);
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Esun\Video\Block\Adminhtml\Video\EditBlock"
name="esun.video.edit"
template="Esun_Video::video/edit.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Esun\Video\Block\Adminhtml\Video\ListBlock"
name="esun.video.list"
template="Esun_Video::video/list.phtml"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,9 @@
var config = {
config: {
mixins: {
'Magento_ProductVideo/js/new-video-dialog': {
'Esun_Video/js/new-video-dialog-mixin': true
}
}
}
};
@@ -0,0 +1,32 @@
<?php
/**
* Extends the native Magento Add Video dialog with Esun managed-video controls.
*
* @var \Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo $block
* @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer
*/
?>
<div id="<?= $block->escapeHtmlAttr($block->getNameInLayout()) ?>"
data-modal-info='<?= /* @noEscape */ $block->getWidgetOptions() ?>'>
<?= $block->getFormHtml() ?>
<?= $block->getChildHtml('esun-video-upload') ?>
<div id="video-player-preview-location" class="video-player-sidebar">
<div class="video-player-container"></div>
<div class="video-information title">
<label><?= $block->escapeHtml(__('Title:')) ?> </label><span></span>
</div>
<div class="video-information uploaded">
<label><?= $block->escapeHtml(__('Uploaded:')) ?> </label><span></span>
</div>
<div class="video-information uploader">
<label><?= $block->escapeHtml(__('Uploader:')) ?> </label><span></span>
</div>
<div class="video-information duration">
<label><?= $block->escapeHtml(__('Duration:')) ?> </label><span></span>
</div>
</div>
</div>
<?= /* @noEscape */ $secureRenderer->renderStyleAsTag(
'display:none',
'div#' . $block->escapeJs($block->getNameInLayout())
) ?>
@@ -0,0 +1,83 @@
<?php
/** @var \Esun\Video\Block\Adminhtml\Product\Upload $block */
?>
<div id="esun-product-video-integration"
data-mage-init='{"Esun_Video/js/product-video-id-upload":{}}'
data-options="<?= $block->escapeHtmlAttr($block->getOptionsJson()) ?>">
<fieldset class="admin__fieldset">
<legend class="admin__legend"><span><?= $block->escapeHtml(__('Video Management')) ?></span></legend>
<div class="admin__field">
<label class="admin__field-label">
<span><?= $block->escapeHtml(__('Video ID')) ?></span>
</label>
<div class="admin__field-control">
<div class="esun-video-library-actions"
style="display:flex;align-items:center;gap:1rem;width:100%">
<input type="number"
min="1"
step="1"
class="admin__control-text"
data-role="esun-video-id-input-v2"
placeholder="<?= $block->escapeHtmlAttr(__('Enter video ID')) ?>"
style="flex:0 0 55%;width:55%;min-width:20rem">
<button type="button"
class="action-secondary"
data-role="esun-add-video-by-id-v2"
style="flex:0 0 auto">
<span><?= $block->escapeHtml(__('Add Video')) ?></span>
</button>
</div>
<div style="margin-top:1rem">
<button type="button" class="action-secondary" data-role="open-mp4-upload">
<span><?= $block->escapeHtml(__('Upload New MP4')) ?></span>
</button>
</div>
</div>
</div>
</fieldset>
<div data-role="mp4-upload-dialog" hidden>
<form class="admin__fieldset" data-role="esun-video-form">
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Title')) ?></span></label>
<div class="admin__field-control">
<input class="admin__control-text" name="title" required>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Description')) ?></span></label>
<div class="admin__field-control">
<textarea class="admin__control-textarea" name="description"></textarea>
</div>
</div>
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('MP4 Video')) ?></span></label>
<div class="admin__field-control">
<input type="file" name="video" accept="video/mp4,.mp4" required>
<progress data-role="progress" max="100" value="0" hidden style="width:100%;margin-top:1rem"></progress>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Cover Image')) ?></span></label>
<div class="admin__field-control">
<input type="file"
name="cover"
accept="image/jpeg,image/png,image/gif"
data-role="cover-image-input">
<p class="note" data-role="cover-image-empty-note">
<?= $block->escapeHtml(__('The system will use the video frame at the 1-second mark if left empty.')) ?>
</p>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Status')) ?></span></label>
<div class="admin__field-control">
<select class="admin__control-select" name="status">
<option value="1"><?= $block->escapeHtml(__('Enabled')) ?></option>
<option value="0"><?= $block->escapeHtml(__('Disabled')) ?></option>
</select>
</div>
</div>
</form>
</div>
</div>
@@ -0,0 +1,102 @@
<?php
/** @var \Esun\Video\Block\Adminhtml\Video\EditBlock $block */
$video = $block->getVideo();
?>
<form method="post"
action="<?= $block->escapeUrl($block->getSaveUrl()) ?>"
enctype="multipart/form-data">
<?= $block->getBlockHtml('formkey') ?>
<input type="hidden" name="video_id" value="<?= (int)$video->getId() ?>">
<div class="page-main-actions">
<div class="page-actions">
<a class="action-secondary" href="<?= $block->escapeUrl($block->getBackUrl()) ?>">
<span><?= $block->escapeHtml(__('Back')) ?></span>
</a>
<button type="submit" class="action-primary">
<span><?= $block->escapeHtml(__('Save Video')) ?></span>
</button>
</div>
</div>
<fieldset class="admin__fieldset">
<div class="admin__field _required">
<label class="admin__field-label" for="esun-video-title">
<span><?= $block->escapeHtml(__('Title')) ?></span>
</label>
<div class="admin__field-control">
<input id="esun-video-title"
type="text"
name="title"
class="admin__control-text"
required
value="<?= $block->escapeHtmlAttr((string)$video->getData('title')) ?>">
</div>
</div>
<div class="admin__field">
<label class="admin__field-label" for="esun-video-description">
<span><?= $block->escapeHtml(__('Description')) ?></span>
</label>
<div class="admin__field-control">
<textarea id="esun-video-description"
name="description"
class="admin__control-textarea"
rows="6"><?= $block->escapeHtml((string)$video->getData('description')) ?></textarea>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label" for="esun-video-status">
<span><?= $block->escapeHtml(__('Status')) ?></span>
</label>
<div class="admin__field-control">
<select id="esun-video-status" name="status" class="admin__control-select">
<option value="1" <?= (int)$video->getData('status') === 1 ? 'selected' : '' ?>>
<?= $block->escapeHtml(__('Enabled')) ?>
</option>
<option value="0" <?= (int)$video->getData('status') === 0 ? 'selected' : '' ?>>
<?= $block->escapeHtml(__('Disabled')) ?>
</option>
</select>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label">
<span><?= $block->escapeHtml(__('Current Cover')) ?></span>
</label>
<div class="admin__field-control">
<?php if ($video->getData('cover_path')): ?>
<img src="<?= $block->escapeUrl($block->getMediaUrl((string)$video->getData('cover_path'))) ?>"
alt=""
style="display:block;max-width:32rem;max-height:20rem;margin-bottom:1rem">
<?php else: ?>
<span><?= $block->escapeHtml(__('No cover image')) ?></span>
<?php endif; ?>
<input type="file" name="cover" accept="image/jpeg,image/png,image/gif,image/webp">
<p class="note">
<?= $block->escapeHtml(__('Leave empty to keep the current cover image.')) ?>
</p>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label">
<span><?= $block->escapeHtml(__('Video Metadata')) ?></span>
</label>
<div class="admin__field-control">
<p>
<?= $block->escapeHtml(__(
'%1 × %2, %3, %4 seconds, %5 MB',
(int)$video->getData('width'),
(int)$video->getData('height'),
(string)$video->getData('resolution'),
number_format((float)$video->getData('duration'), 2),
number_format((int)$video->getData('size') / 1048576, 2)
)) ?>
</p>
</div>
</div>
</fieldset>
</form>
@@ -0,0 +1,196 @@
<?php
/** @var \Esun\Video\Block\Adminhtml\Video\ListBlock $block */
$missingBinaries = $block->getMissingBinaries();
?>
<?php if ($missingBinaries): ?>
<div class="messages">
<div class="message message-error error"
style="font-size:1.5rem;font-weight:600;border-left-width:5px">
<div>
<?= $block->escapeHtml(__(
'Video processing tools are unavailable: %1. Install them or correct their binary paths under Stores → Configuration → Esun → Video Management.',
implode(', ', array_map(
static fn(string $name, string $binary): string => $name . ' (' . $binary . ')',
array_keys($missingBinaries),
array_values($missingBinaries)
))
)) ?>
</div>
</div>
</div>
<?php endif; ?>
<div class="page-main-actions">
<div class="page-actions">
<button type="button"
class="action-primary"
data-role="open-video-upload"
<?= $block->isUploadEnabled() ? '' : 'disabled' ?>>
<span><?= $block->escapeHtml(__('Upload Video')) ?></span>
</button>
</div>
</div>
<div class="admin__data-grid-header" style="margin-bottom:2rem">
<form method="get"
action="<?= $block->escapeUrl($block->getFilterUrl()) ?>"
style="display:flex;align-items:flex-end;gap:1.5rem;flex-wrap:wrap">
<div class="admin__field" style="margin:0;min-width:28rem">
<label class="admin__field-label" for="esun-video-filter-title" style="float:none;width:auto;text-align:left">
<span><?= $block->escapeHtml(__('Title')) ?></span>
</label>
<div class="admin__field-control" style="float:none;width:auto">
<input id="esun-video-filter-title"
type="text"
name="title"
class="admin__control-text"
value="<?= $block->escapeHtmlAttr($block->getTitleFilter()) ?>"
placeholder="<?= $block->escapeHtmlAttr(__('Filter by title')) ?>">
</div>
</div>
<div class="admin__field" style="margin:0;min-width:18rem">
<label class="admin__field-label" for="esun-video-filter-status" style="float:none;width:auto;text-align:left">
<span><?= $block->escapeHtml(__('Status')) ?></span>
</label>
<div class="admin__field-control" style="float:none;width:auto">
<select id="esun-video-filter-status" name="status" class="admin__control-select">
<option value=""><?= $block->escapeHtml(__('All Statuses')) ?></option>
<option value="1" <?= $block->getStatusFilter() === '1' ? 'selected' : '' ?>>
<?= $block->escapeHtml(__('Enabled')) ?>
</option>
<option value="0" <?= $block->getStatusFilter() === '0' ? 'selected' : '' ?>>
<?= $block->escapeHtml(__('Disabled')) ?>
</option>
</select>
</div>
</div>
<div style="display:flex;gap:1rem">
<button type="submit" class="action-secondary">
<span><?= $block->escapeHtml(__('Filter')) ?></span>
</button>
<a class="action-secondary" href="<?= $block->escapeUrl($block->getFilterUrl()) ?>">
<span><?= $block->escapeHtml(__('Reset')) ?></span>
</a>
</div>
</form>
</div>
<div id="esun-video-management-upload"
data-options="<?= $block->escapeHtmlAttr($block->getUploadOptionsJson()) ?>"
hidden>
<form class="admin__fieldset" data-role="video-upload-form">
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Title')) ?></span></label>
<div class="admin__field-control">
<input type="text" class="admin__control-text" name="title" required>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Description')) ?></span></label>
<div class="admin__field-control">
<textarea class="admin__control-textarea" name="description"></textarea>
</div>
</div>
<div class="admin__field _required">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('MP4 Video')) ?></span></label>
<div class="admin__field-control">
<input type="file" name="video" accept="video/mp4,.mp4" required>
<div style="margin-top: 1rem;">
<progress data-role="upload-progress" max="100" value="0" hidden
style="width: 100%;"></progress>
<div data-role="upload-status"></div>
</div>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Cover Image')) ?></span></label>
<div class="admin__field-control">
<input type="file"
name="cover"
accept="image/jpeg,image/png,image/gif"
data-role="cover-image-input">
<p class="note" data-role="cover-image-empty-note">
<?= $block->escapeHtml(__('The system will use the video frame at the 1-second mark if left empty.')) ?>
</p>
</div>
</div>
<div class="admin__field">
<label class="admin__field-label"><span><?= $block->escapeHtml(__('Status')) ?></span></label>
<div class="admin__field-control">
<select class="admin__control-select" name="status">
<option value="1"><?= $block->escapeHtml(__('Enabled')) ?></option>
<option value="0"><?= $block->escapeHtml(__('Disabled')) ?></option>
</select>
</div>
</div>
</form>
</div>
<div class="admin__data-grid-wrap">
<table class="data-grid">
<thead>
<tr>
<th class="data-grid-th"><?= $block->escapeHtml(__('ID')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Cover')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Title')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Description')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Status')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Duration')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Size')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Dimensions')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Resolution')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Created')) ?></th>
<th class="data-grid-th"><?= $block->escapeHtml(__('Action')) ?></th>
</tr>
</thead>
<tbody>
<?php $videos = $block->getVideos(); ?>
<?php if ($videos->getSize() === 0): ?>
<tr>
<td colspan="11" class="empty-text">
<?= $block->escapeHtml(__('No videos have been uploaded yet.')) ?>
</td>
</tr>
<?php endif; ?>
<?php foreach ($videos as $video): ?>
<tr>
<td><?= (int)$video->getId() ?></td>
<td><img src="<?= $block->escapeUrl($block->getMediaUrl((string)$video->getData('cover_path'))) ?>"
alt="" width="100"></td>
<td>
<a href="<?= $block->escapeUrl($block->getMediaUrl((string)$video->getData('video_path'))) ?>"
target="_blank" rel="noopener"><?= $block->escapeHtml($video->getData('title')) ?></a>
</td>
<td style="max-width:32rem;white-space:normal;overflow-wrap:anywhere"
title="<?= $block->escapeHtmlAttr((string)$video->getData('description')) ?>">
<?= $block->escapeHtml((string)$video->getData('description')) ?>
</td>
<td><?= $video->getData('status') ? $block->escapeHtml(__('Enabled')) : $block->escapeHtml(__('Disabled')) ?></td>
<td><?= $block->escapeHtml(number_format((float)$video->getData('duration'), 2)) ?>s</td>
<td><?= $block->escapeHtml(number_format((int)$video->getData('size') / 1048576, 2)) ?> MB</td>
<td><?= (int)$video->getData('width') ?> × <?= (int)$video->getData('height') ?></td>
<td><?= $block->escapeHtml($video->getData('resolution')) ?></td>
<td><?= $block->escapeHtml($video->getData('created_at')) ?></td>
<td>
<a href="<?= $block->escapeUrl($block->getEditUrl((int)$video->getId())) ?>">
<?= $block->escapeHtml(__('Edit')) ?>
</a>
<span aria-hidden="true"> | </span>
<a href="<?= $block->escapeUrl($block->getDeleteUrl((int)$video->getId())) ?>"
onclick="return confirm('<?= $block->escapeJs(__('Delete this video?')) ?>')">
<?= $block->escapeHtml(__('Delete')) ?>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/x-magento-init">
{
"#esun-video-management-upload": {
"Esun_Video/js/video-management-upload": {}
}
}
</script>
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<htmlContent name="gallery" sortOrder="22">
<argument name="data" xsi:type="array">
<item name="wrapper" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Images And Videos</item>
<item name="collapsible" xsi:type="boolean">true</item>
<item name="opened" xsi:type="boolean">false</item>
</item>
</argument>
<settings>
<wrapper>
<canShow>true</canShow>
<componentType>fieldset</componentType>
</wrapper>
</settings>
<block name="gallery" class="Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery">
<arguments>
<argument name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Images And Videos</item>
<item name="collapsible" xsi:type="boolean">true</item>
<item name="opened" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="string">22</item>
<item name="canShow" xsi:type="boolean">true</item>
<item name="componentType" xsi:type="string">fieldset</item>
</argument>
</arguments>
<block class="Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery\Content" as="content">
<arguments>
<argument name="config" xsi:type="array">
<item name="parentComponent" xsi:type="string">product_form.product_form.block_gallery.block_gallery</item>
</argument>
</arguments>
<block class="Magento\ProductVideo\Block\Adminhtml\Product\Edit\NewVideo"
name="new-video"
template="Esun_Video::product/edit/slideout/form.phtml">
<block class="Esun\Video\Block\Adminhtml\Product\Upload"
name="esun-video-upload"
as="esun-video-upload"
template="Esun_Video::product/upload.phtml"/>
</block>
</block>
</block>
</htmlContent>
</form>
@@ -0,0 +1,122 @@
define([
'jquery',
'Esun_Video/js/product-video-id-upload'
], function ($, initProductVideoUpload) {
'use strict';
return function (Widget) {
return $.widget('mage.newVideoDialog', Widget, {
/**
* HtmlContent can be inserted after Magento's data-mage-init scan,
* so initialize managed-video controls when the native dialog exists.
*/
_create: function () {
var integration;
this._super();
integration = this.element.find('#esun-product-video-integration');
if (integration.length) {
initProductVideoUpload({}, integration.get(0));
}
},
/**
* Managed MP4 videos do not require YouTube/Vimeo metadata lookup.
*/
_onGetVideoInformationEditClick: function () {
if (this._isHtml5Video()) {
this._videoRequestComplete = true;
this._renderHtml5Preview();
return;
}
this._super();
},
/**
* Prevent focus-out validation of an existing managed MP4 URL.
*/
_onGetVideoInformationFocusOut: function () {
if (this._isHtml5Video()) {
this._videoRequestComplete = true;
return;
}
this._super();
},
/**
* Keep native form validation, but skip provider URL validation for MP4.
*
* @param {Function} callback
*/
isValid: function (callback) {
var videoForm;
if (!this._isHtml5Video()) {
this._super(callback);
return;
}
videoForm = this.element.find(this._videoFormSelector);
this._blockActionButtons(true);
videoForm.mage('validation', {
errorPlacement: function (error, input) {
error.insertAfter(input);
}
});
videoForm.validation();
this._videoRequestComplete = true;
callback(videoForm.valid());
this._blockActionButtons(false);
},
/**
* Render an HTML5 preview when opening a managed MP4 gallery item.
*/
_onOpenDialog: function (event, imageData) {
this._super(event, imageData);
if (imageData && (
imageData.video_provider === 'html5' ||
/\.mp4(?:$|\?)/i.test(imageData.video_url || '')
)) {
this._videoRequestComplete = true;
this._renderHtml5Preview(imageData.video_url);
}
},
_isHtml5Video: function () {
var provider = this.element.find('[name="video_provider"]').val(),
url = this.element.find(this._videoUrlSelector).val();
return provider === 'html5' || /\.mp4(?:$|\?)/i.test(url || '');
},
_renderHtml5Preview: function (url) {
var container = this.element.find('.video-player-container'),
metadata;
url = url || this.element.find(this._videoUrlSelector).val();
container.empty();
if (!url) {
return;
}
$('<video controls preload="metadata" playsinline></video>')
.attr('src', url)
.css({width: '100%', maxHeight: '360px'})
.appendTo(container);
try {
metadata = JSON.parse(this.element.find('[name="video_metadata"]').val() || '{}');
} catch (error) {
metadata = {};
}
this.element.find('.video-information.title span')
.text(this.element.find('[name="video_title"]').val());
this.element.find('.video-information.duration span')
.text(metadata.duration ? metadata.duration + 's' : '');
this.element.find('.video-information.uploaded, .video-information.uploader').hide();
this.element.find('.video-information.title, .video-information.duration').show();
}
});
};
});
@@ -0,0 +1,210 @@
define([
'jquery',
'Magento_Ui/js/modal/modal',
'mage/translate'
], function ($, modal) {
'use strict';
return function (config, element) {
var $element = $(element),
options = $element.data('options'),
$dialog = $element.find('[data-role="mp4-upload-dialog"]'),
$form = $element.find('[data-role="esun-video-form"]'),
$progress = $element.find('[data-role="progress"]'),
$openUpload = $element.find('[data-role="open-mp4-upload"]'),
$coverInput = $element.find('[data-role="cover-image-input"]'),
$coverNote = $element.find('[data-role="cover-image-empty-note"]'),
$libraryId = $element.find('[data-role="esun-video-id-input-v2"]'),
$addLibraryVideo = $element.find('[data-role="esun-add-video-by-id-v2"]'),
libraryItems = {},
modalOptions;
if ($element.data('esunVideoInitialized')) {
return;
}
$element.data('esunVideoInitialized', true);
if (!options.enabled) {
$openUpload.prop('disabled', true)
.attr('title', $.mage.__('Video upload is disabled in configuration.'));
}
setLibraryItems(options.libraryItems || []);
$coverInput.on('change', function () {
$coverNote.toggle(!(this.files && this.files.length));
});
$libraryId.on('keydown', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
addLibraryVideo();
}
});
modalOptions = {
type: 'slide',
title: $.mage.__('Upload MP4 Video'),
buttons: [{
text: $.mage.__('Upload and Add'),
class: 'action-primary',
click: upload
}, {
text: $.mage.__('Cancel'),
click: function () {
$dialog.modal('closeModal');
}
}]
};
modal(modalOptions, $dialog);
$openUpload.on('click', function () {
if (!options.enabled) {
return;
}
$dialog.modal('openModal');
});
$addLibraryVideo.on('click', addLibraryVideo);
function addLibraryVideo() {
var selectedId = $.trim($libraryId.val()),
item;
if (!/^[1-9]\d*$/.test(selectedId)) {
alert($.mage.__('Please enter a valid video ID.'));
return;
}
item = libraryItems[selectedId];
if (!item) {
$.getJSON(options.libraryUrl).done(function (response) {
setLibraryItems(response.items || []);
addLibraryItem(selectedId);
}).fail(function () {
alert($.mage.__('Unable to load the video library.'));
});
return;
}
addLibraryItem(selectedId);
}
function addLibraryItem(selectedId) {
var item = libraryItems[selectedId];
if (!item) {
alert($.mage.__('No enabled video was found for this ID.'));
return;
}
item.metadata = {
duration: item.duration,
size: item.size,
width: item.width,
height: item.height,
resolution: item.resolution
};
item.disabled = 0;
addToGallery(item);
closeDialogs();
$libraryId.val('');
}
function setLibraryItems(items) {
libraryItems = {};
$.each(items, function (index, item) {
libraryItems[String(item.id)] = item;
});
}
function upload() {
var title = $.trim($form.find('[name="title"]').val()),
file = $form.find('[name="video"]')[0].files[0],
cover = $form.find('[name="cover"]')[0].files[0],
uploadId = Date.now().toString(36) + Math.random().toString(36).slice(2),
total,
index = 0;
if (!title || !file) {
alert($.mage.__('Title and MP4 video are required.'));
return;
}
if (!/\.mp4$/i.test(file.name) || (file.type && file.type !== 'video/mp4')) {
alert($.mage.__('Only MP4 video files are supported.'));
return;
}
total = Math.ceil(file.size / options.chunkSize);
$progress.attr('hidden', false).val(0);
sendNext();
function sendNext() {
var start = index * options.chunkSize,
data = new FormData();
data.append('form_key', window.FORM_KEY);
data.append('upload_id', uploadId);
data.append('index', index);
data.append('total', total);
data.append('name', file.name);
data.append('title', title);
data.append('description', $form.find('[name="description"]').val());
data.append('status', $form.find('[name="status"]').val());
data.append('chunk', file.slice(start, Math.min(start + options.chunkSize, file.size)), file.name);
if (cover && index + 1 === total) {
data.append('cover', cover, cover.name);
}
$.ajax({
url: options.uploadUrl,
method: 'POST',
data: data,
processData: false,
contentType: false
}).done(function (response) {
index++;
$progress.val(Math.round(index / total * 100));
if (!response.completed) {
sendNext();
return;
}
addToGallery(response.video);
closeDialogs();
$form[0].reset();
$progress.attr('hidden', true).val(0);
}).fail(function (xhr) {
var response = xhr.responseJSON || {};
alert(response.message || $.mage.__('Video upload failed.'));
});
}
}
function addToGallery(video) {
var widget = $('#new-video').data('mageNewVideoDialog'),
metadata = $.extend({esun_video_id: video.id}, video.metadata),
imageData = {
file: video.gallery_file,
file_id: 'esun_video_' + video.id,
value_id: '',
label: video.title,
position: 0,
disabled: video.disabled,
removed: '',
url: video.cover_url,
media_type: 'external-video',
video_provider: 'html5',
video_url: video.video_url,
video_title: video.title,
video_description: video.description,
video_metadata: JSON.stringify(metadata),
sizeLabel: ''
};
if (!widget || typeof widget._setImage !== 'function') {
alert($.mage.__('The video was uploaded, but the product gallery could not be updated. Reload the page and select it from Video Management.'));
return;
}
widget._setImage(imageData.file, imageData);
}
function closeDialogs() {
$dialog.modal('closeModal');
$('#new-video').modal('closeModal');
}
};
});
@@ -0,0 +1,120 @@
define([
'jquery',
'Magento_Ui/js/modal/modal',
'mage/translate'
], function ($, modal) {
'use strict';
return function (config, element) {
var $element = $(element),
options = $element.data('options'),
$form = $element.find('[data-role="video-upload-form"]'),
$progress = $element.find('[data-role="upload-progress"]'),
$status = $element.find('[data-role="upload-status"]'),
$coverInput = $element.find('[data-role="cover-image-input"]'),
$coverNote = $element.find('[data-role="cover-image-empty-note"]'),
uploading = false;
$coverInput.on('change', function () {
$coverNote.toggle(!(this.files && this.files.length));
});
modal({
type: 'slide',
title: $.mage.__('Upload Video'),
buttons: [{
text: $.mage.__('Upload'),
class: 'action-primary',
click: upload
}, {
text: $.mage.__('Cancel'),
click: function () {
if (!uploading) {
$element.modal('closeModal');
}
}
}]
}, $element);
$('[data-role="open-video-upload"]').on('click', function () {
if (!options.enabled) {
alert($.mage.__('Video upload is disabled in configuration.'));
return;
}
$element.modal('openModal');
});
function upload() {
var title = $.trim($form.find('[name="title"]').val()),
fileInput = $form.find('[name="video"]')[0],
coverInput = $form.find('[name="cover"]')[0],
file = fileInput.files[0],
cover = coverInput.files[0],
uploadId,
total,
index = 0;
if (uploading) {
return;
}
if (!title || !file) {
alert($.mage.__('Title and MP4 video are required.'));
return;
}
if (!/\.mp4$/i.test(file.name) || (file.type && file.type !== 'video/mp4')) {
alert($.mage.__('Only MP4 video files are supported.'));
return;
}
uploading = true;
uploadId = Date.now().toString(36) + Math.random().toString(36).slice(2);
total = Math.ceil(file.size / options.chunkSize);
$progress.attr('hidden', false).val(0);
$status.text($.mage.__('Uploading...'));
sendNext();
function sendNext() {
var start = index * options.chunkSize,
data = new FormData();
data.append('form_key', window.FORM_KEY);
data.append('upload_id', uploadId);
data.append('index', index);
data.append('total', total);
data.append('name', file.name);
data.append('title', title);
data.append('description', $form.find('[name="description"]').val());
data.append('status', $form.find('[name="status"]').val());
data.append(
'chunk',
file.slice(start, Math.min(start + options.chunkSize, file.size)),
file.name
);
if (cover && index + 1 === total) {
data.append('cover', cover, cover.name);
}
$.ajax({
url: options.uploadUrl,
method: 'POST',
data: data,
processData: false,
contentType: false
}).done(function (response) {
index++;
$progress.val(Math.round(index / total * 100));
if (!response.completed) {
sendNext();
return;
}
$status.text($.mage.__('Upload completed. Refreshing...'));
window.location.replace(options.indexUrl);
}).fail(function (xhr) {
var response = xhr.responseJSON || {};
uploading = false;
$status.text(response.message || $.mage.__('Video upload failed.'));
});
}
}
};
});
@@ -0,0 +1,12 @@
var config = {
config: {
mixins: {
'Magento_ProductVideo/js/fotorama-add-video-events': {
'Esun_Video/js/fotorama-html5-mixin': true
},
'Magento_ProductVideo/js/load-player': {
'Esun_Video/js/load-player-html5-mixin': true
}
}
}
};
@@ -0,0 +1,34 @@
define([], function () {
'use strict';
return function (Widget) {
var originalCreateVideoData = Widget.prototype._createVideoData;
Widget.prototype._createVideoData = function (inputData, isJSON) {
var videoData = [], item, url, i;
if (isJSON) {
inputData = JSON.parse(inputData);
}
for (i = 0; i < inputData.length; i++) {
item = inputData[i];
url = item.videoUrl || '';
if (item.mediaType !== 'external-video') {
videoData.push({mediaType: item.mediaType, isBase: item.isBase, id: '', provider: ''});
} else if (/\.mp4(?:$|\?)/i.test(url) || item.provider === 'html5') {
videoData.push({
mediaType: 'video',
isBase: item.isBase,
id: url,
provider: 'html5',
videoUrl: url,
useYoutubeNocookie: false
});
} else {
videoData.push(originalCreateVideoData.call(this, [item], false)[0]);
}
}
return videoData;
};
return Widget;
};
});
@@ -0,0 +1,34 @@
define(['jquery'], function ($) {
'use strict';
return function (Widget) {
Widget = Widget || ($.mage && $.mage.productVideoLoader);
if (!Widget || !Widget.prototype || Widget.prototype._esunHtml5VideoPatched) {
return Widget;
}
var originalCreate = Widget.prototype._create;
Widget.prototype._esunHtml5VideoPatched = true;
Widget.prototype._create = function () {
var video;
if (this.element.data('type') !== 'html5') {
return originalCreate.apply(this, arguments);
}
video = $('<video controls autoplay playsinline></video>').attr('src', this.element.data('code'));
if (this.element.data('loop')) {
video.attr('loop', 'loop');
}
this.element.empty().append(video).addClass('responsive');
this.element.closest('.fotorama__stage__frame').addClass('fotorama__product-video--loaded');
this._player = {
play: function () { video.get(0).play(); },
pause: function () { video.get(0).pause(); },
stop: function () { video.get(0).pause(); video.get(0).currentTime = 0; },
playing: function () { return !video.get(0).paused; }
};
};
return Widget;
};
});