From a9989d841a634f8cf6c04df25f40bb1e7d4fcdcc Mon Sep 17 00:00:00 2001
From: Yassine Doghri <yassine@doghri.fr>
Date: Tue, 21 Dec 2021 13:42:31 +0000
Subject: [PATCH] fix(import): save media files during podcast import + set
 missing media fields

---
 .../2020-05-29-120000_add_media.php           |  1 +
 app/Entities/Episode.php                      | 23 ++++++++++++-------
 app/Entities/Media/Audio.php                  |  4 ++--
 app/Entities/Media/BaseMedia.php              |  1 +
 app/Entities/Media/Image.php                  | 15 ++++++++----
 app/Models/EpisodeModel.php                   |  5 ----
 app/Models/MediaModel.php                     | 17 ++++++++++++++
 .../Controllers/PodcastImportController.php   |  2 +-
 8 files changed, 48 insertions(+), 20 deletions(-)

diff --git a/app/Database/Migrations/2020-05-29-120000_add_media.php b/app/Database/Migrations/2020-05-29-120000_add_media.php
index f807837014..b05ef54a46 100644
--- a/app/Database/Migrations/2020-05-29-120000_add_media.php
+++ b/app/Database/Migrations/2020-05-29-120000_add_media.php
@@ -51,6 +51,7 @@ class AddMedia extends Migration
             'language_code' => [
                 'type' => 'VARCHAR',
                 'constraint' => 2,
+                'null' => true,
             ],
             'uploaded_by' => [
                 'type' => 'INT',
diff --git a/app/Entities/Episode.php b/app/Entities/Episode.php
index feeede4d35..ca577f431b 100644
--- a/app/Entities/Episode.php
+++ b/app/Entities/Episode.php
@@ -22,6 +22,7 @@ use App\Models\PersonModel;
 use App\Models\PodcastModel;
 use App\Models\PostModel;
 use CodeIgniter\Entity\Entity;
+use CodeIgniter\Files\File;
 use CodeIgniter\HTTP\Files\UploadedFile;
 use CodeIgniter\I18n\Time;
 use League\CommonMark\CommonMarkConverter;
@@ -165,9 +166,9 @@ class Episode extends Entity
         'updated_by' => 'integer',
     ];
 
-    public function setCover(?UploadedFile $file): self
+    public function setCover(UploadedFile | File $file = null): self
     {
-        if ($file === null || ! $file->isValid()) {
+        if ($file === null || ($file instanceof UploadedFile && ! $file->isValid())) {
             return $this;
         }
 
@@ -212,9 +213,9 @@ class Episode extends Entity
         return $this->cover;
     }
 
-    public function setAudio(?UploadedFile $file): self
+    public function setAudio(UploadedFile | File $file = null): self
     {
-        if ($file === null || ! $file->isValid()) {
+        if ($file === null || ($file instanceof UploadedFile && ! $file->isValid())) {
             return $this;
         }
 
@@ -228,6 +229,8 @@ class Episode extends Entity
             $audio = new Audio([
                 'file_name' => $this->attributes['slug'],
                 'file_directory' => 'podcasts/' . $this->getPodcast()->handle,
+                'language_code' => $this->getPodcast()
+                    ->language_code,
                 'uploaded_by' => user_id(),
                 'updated_by' => user_id(),
             ]);
@@ -248,9 +251,9 @@ class Episode extends Entity
         return $this->audio;
     }
 
-    public function setTranscript(?UploadedFile $file): self
+    public function setTranscript(UploadedFile | File $file = null): self
     {
-        if ($file === null || ! $file->isValid()) {
+        if ($file === null || ($file instanceof UploadedFile && ! $file->isValid())) {
             return $this;
         }
 
@@ -264,6 +267,8 @@ class Episode extends Entity
             $transcript = new Transcript([
                 'file_name' => $this->attributes['slug'] . '-transcript',
                 'file_directory' => 'podcasts/' . $this->getPodcast()->handle,
+                'language_code' => $this->getPodcast()
+                    ->language_code,
                 'uploaded_by' => user_id(),
                 'updated_by' => user_id(),
             ]);
@@ -284,9 +289,9 @@ class Episode extends Entity
         return $this->transcript;
     }
 
-    public function setChapters(?UploadedFile $file): self
+    public function setChapters(UploadedFile | File $file = null): self
     {
-        if ($file === null || ! $file->isValid()) {
+        if ($file === null || ($file instanceof UploadedFile && ! $file->isValid())) {
             return $this;
         }
 
@@ -300,6 +305,8 @@ class Episode extends Entity
             $chapters = new Chapters([
                 'file_name' => $this->attributes['slug'] . '-chapters',
                 'file_directory' => 'podcasts/' . $this->getPodcast()->handle,
+                'language_code' => $this->getPodcast()
+                    ->language_code,
                 'uploaded_by' => user_id(),
                 'updated_by' => user_id(),
             ]);
diff --git a/app/Entities/Media/Audio.php b/app/Entities/Media/Audio.php
index de71409fb8..6cb2c20b02 100644
--- a/app/Entities/Media/Audio.php
+++ b/app/Entities/Media/Audio.php
@@ -44,8 +44,8 @@ class Audio extends BaseMedia
         $this->attributes['file_mimetype'] = $audioMetadata['mime_type'];
         $this->attributes['file_size'] = $audioMetadata['filesize'];
         // @phpstan-ignore-next-line
-        $this->attributes['description'] = @$audioMetadata['id3v2']['comments']['comment'];
-        $this->attributes['file_metadata'] = json_encode($audioMetadata);
+        $this->attributes['description'] = @$audioMetadata['id3v2']['comments']['comment'][0];
+        $this->attributes['file_metadata'] = json_encode($audioMetadata, JSON_INVALID_UTF8_SUBSTITUTE);
 
         return $this;
     }
diff --git a/app/Entities/Media/BaseMedia.php b/app/Entities/Media/BaseMedia.php
index f71781f80c..5dbed8799d 100644
--- a/app/Entities/Media/BaseMedia.php
+++ b/app/Entities/Media/BaseMedia.php
@@ -88,6 +88,7 @@ class BaseMedia extends Entity
     {
         helper('media');
 
+        $this->attributes['type'] = $this->type;
         $this->attributes['file_mimetype'] = $file->getMimeType();
         $this->attributes['file_metadata'] = json_encode(lstat((string) $file));
         $this->attributes['file_path'] = save_media(
diff --git a/app/Entities/Media/Image.php b/app/Entities/Media/Image.php
index 7d48b0f4d0..fa137f67cc 100644
--- a/app/Entities/Media/Image.php
+++ b/app/Entities/Media/Image.php
@@ -54,14 +54,21 @@ class Image extends BaseMedia
     {
         parent::setFile($file);
 
-        $metadata = exif_read_data(media_path($this->file_path), null, true);
-
-        if ($metadata) {
+        if ($this->file_mimetype === 'image/jpeg' && $metadata = exif_read_data(
+            media_path($this->file_path),
+            null,
+            true
+        )) {
             $metadata['sizes'] = $this->sizes;
             $this->attributes['file_size'] = $metadata['FILE']['FileSize'];
-            $this->attributes['file_metadata'] = json_encode($metadata);
+        } else {
+            $metadata = [
+                'sizes' => $this->sizes,
+            ];
         }
 
+        $this->attributes['file_metadata'] = json_encode($metadata);
+
         $this->initFileProperties();
         $this->saveSizes();
 
diff --git a/app/Models/EpisodeModel.php b/app/Models/EpisodeModel.php
index 1152adeef9..b5a9c8d13d 100644
--- a/app/Models/EpisodeModel.php
+++ b/app/Models/EpisodeModel.php
@@ -54,11 +54,6 @@ class EpisodeModel extends Model
      */
     protected $table = 'episodes';
 
-    /**
-     * @var string
-     */
-    protected $primaryKey = 'id';
-
     /**
      * @var string[]
      */
diff --git a/app/Models/MediaModel.php b/app/Models/MediaModel.php
index f0fd5b8389..85695c410b 100644
--- a/app/Models/MediaModel.php
+++ b/app/Models/MediaModel.php
@@ -32,6 +32,23 @@ class MediaModel extends Model
      */
     protected $returnType = Document::class;
 
+    /**
+     * @var bool
+     */
+    protected $useSoftDeletes = true;
+
+    /**
+     * @var bool
+     */
+    protected $useTimestamps = true;
+
+    /**
+     * The column used for insert timestamps
+     *
+     * @var string
+     */
+    protected $createdField = 'uploaded_at';
+
     /**
      * @var string[]
      */
diff --git a/modules/Admin/Controllers/PodcastImportController.php b/modules/Admin/Controllers/PodcastImportController.php
index 9af473052f..a74296eace 100644
--- a/modules/Admin/Controllers/PodcastImportController.php
+++ b/modules/Admin/Controllers/PodcastImportController.php
@@ -345,7 +345,7 @@ class PodcastImportController extends BaseController
                 'title' => $item->title,
                 'slug' => $slug,
                 'guid' => $item->guid ?? null,
-                'audio_file' => download_file(
+                'audio' => download_file(
                     (string) $item->enclosure->attributes()['url'],
                     (string) $item->enclosure->attributes()['type']
                 ),
-- 
GitLab