From 0a4410b1e836cb0ddd4cf58441823705a2f8f503 Mon Sep 17 00:00:00 2001
From: Camille Simiand <camille.simiand@tetras-libre.fr>
Date: Tue, 11 Jan 2022 09:46:55 +0100
Subject: [PATCH] Display capsule content on homepage + display edit capsule

---
 migrations/Version20211215152200.php       |  31 -------
 src/Controller/CapsuleController.php       |   1 +
 src/Controller/FallbackController.php      |   2 +-
 src/Controller/ProjectController.php       |  11 ++-
 src/Helper/LegacyHelper.php                | 101 +++++++++++----------
 templates/capsule/index.html.twig          |   4 +-
 templates/project/edit.html.twig           |  14 +++
 tests/functional/ProjectControllerTest.php |  25 +++--
 8 files changed, 94 insertions(+), 95 deletions(-)
 delete mode 100644 migrations/Version20211215152200.php
 create mode 100644 templates/project/edit.html.twig

diff --git a/migrations/Version20211215152200.php b/migrations/Version20211215152200.php
deleted file mode 100644
index be6f5e4..0000000
--- a/migrations/Version20211215152200.php
+++ /dev/null
@@ -1,31 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace DoctrineMigrations;
-
-use Doctrine\DBAL\Schema\Schema;
-use Doctrine\Migrations\AbstractMigration;
-
-/**
- * Auto-generated Migration: Please modify to your needs!
- */
-final class Version20211215152200 extends AbstractMigration
-{
-    public function getDescription(): string
-    {
-        return '';
-    }
-
-    public function up(Schema $schema): void
-    {
-        // this up() migration is auto-generated, please modify it to your needs
-        $this->addSql('CREATE TABLE capsule (id INT AUTO_INCREMENT NOT NULL, nom VARCHAR(255) NOT NULL, aut_crea VARCHAR(255) NOT NULL, dt_crea DATETIME NOT NULL, aut_maj INT DEFAULT NULL, dt_maj DATETIME DEFAULT NULL, link VARCHAR(255) NOT NULL, edition_link VARCHAR(255) NOT NULL, UNIQUE INDEX index_capsule_nom (nom), UNIQUE INDEX index_capsule_link (link), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB');
-    }
-
-    public function down(Schema $schema): void
-    {
-        // this down() migration is auto-generated, please modify it to your needs
-        $this->addSql('DROP TABLE capsule');
-    }
-}
diff --git a/src/Controller/CapsuleController.php b/src/Controller/CapsuleController.php
index 6e6db48..fc19bcc 100644
--- a/src/Controller/CapsuleController.php
+++ b/src/Controller/CapsuleController.php
@@ -30,6 +30,7 @@ class CapsuleController extends AbstractController
 
         return $this->render('capsule/index.html.twig', [
             'capsules' => $capsules,
+            'legacy_url' => $this->getParameter('app.legacy_external_prefix')
         ]);
     }
 
diff --git a/src/Controller/FallbackController.php b/src/Controller/FallbackController.php
index 181aca6..a7ba67f 100644
--- a/src/Controller/FallbackController.php
+++ b/src/Controller/FallbackController.php
@@ -102,7 +102,7 @@ class FallbackController extends AbstractController
                 "{$originalController}{$separator}?{$originalQueryString}";
             $url = preg_replace('(^https?:\/\/[^/]+(:\d+)?)', '', $url);
 
-            $pattern = '/\/\//i';
+            $pattern = '/\/+/i';
             /** @phpstan-ignore-next-line */
             $url = preg_replace($pattern, '/', $url);
 
diff --git a/src/Controller/ProjectController.php b/src/Controller/ProjectController.php
index c6b514d..731385b 100644
--- a/src/Controller/ProjectController.php
+++ b/src/Controller/ProjectController.php
@@ -26,8 +26,9 @@ class ProjectController extends AbstractController
         chdir('../legacy/');
 
         $capsule_name = $capsule->getName();
+        $capsule_directory = $capsule->getPreviewLink();
 
-        if (file_exists($capsule_name)) {
+        if (file_exists($capsule_directory)) {
             $this->addFlash(
                 'project_already_exists',
                 $translator->trans(
@@ -41,9 +42,9 @@ class ProjectController extends AbstractController
             return $this->redirectToRoute('capsule_list');
         }
 
-        $this->extractZipArchiveInNewCapsuleDirectory($capsule_name);
+        $this->extractZipArchiveInNewCapsuleDirectory($capsule_directory);
 
-        $this->addProjectVideoUrlInXMLProjectFile($capsule_name, $video_url);
+        $this->addProjectVideoUrlInXMLProjectFile($capsule_directory, $video_url);
 
         $this->addFlash(
             'capsule_created_success',
@@ -71,9 +72,9 @@ class ProjectController extends AbstractController
         $zip->close();
     }
 
-    private function addProjectVideoUrlInXMLProjectFile(string $capsule_name, string $video_url): void
+    private function addProjectVideoUrlInXMLProjectFile(string $capsule_directory, string $video_url): void
     {
-        $project_xml_file = $capsule_name . "/file/project.xml";
+        $project_xml_file = $capsule_directory . "/file/project.xml";
         $xml_file_content = file_get_contents($project_xml_file);
 
         if (false === $xml_file_content) {
diff --git a/src/Helper/LegacyHelper.php b/src/Helper/LegacyHelper.php
index f1fec45..5e96409 100644
--- a/src/Helper/LegacyHelper.php
+++ b/src/Helper/LegacyHelper.php
@@ -115,62 +115,65 @@ class LegacyHelper
 
         $curl_handler = new CurlHandle();
 
-        $options_array = [
-            CURLOPT_URL => $url,
-            CURLOPT_HEADER => false,
-            CURLOPT_VERBOSE => true,
-            CURLOPT_RETURNTRANSFER => true,
-            CURLOPT_FOLLOWLOCATION => true,
-            CURLOPT_COOKIESESSION => false,
-            CURLOPT_COOKIEFILE => 'cookies.txt',
-            CURLOPT_COOKIEJAR => 'cookies.txt'
-        ];
-
-        $curl_handler->setOptions($options_array);
-
-        if ($request->getMethod() == 'POST') {
-            $postParameters = $request->request->all()['create_capsule_form'];
-
-            if (! is_array($postParameters)) {
-                throw new Exception();
+        try {
+            $options_array = [
+                CURLOPT_URL => $url,
+                CURLOPT_HEADER => false,
+                CURLOPT_VERBOSE => true,
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_FOLLOWLOCATION => true,
+                CURLOPT_COOKIESESSION => false,
+                CURLOPT_COOKIEFILE => 'cookies.txt',
+                CURLOPT_COOKIEJAR => 'cookies.txt'
+            ];
+
+            $curl_handler->setOptions($options_array);
+
+            if ($request->getMethod() == 'POST') {
+                $postParameters = $request->request->all();
+
+                if (!is_array($postParameters)) {
+                    throw new Exception();
+                }
+
+                // upload file to transfer
+                if (isset($_FILES['fileToUpload'])) {
+                    $data = [
+                        'fileToUpload' => curl_file_create(
+                            $_FILES['fileToUpload']['tmp_name'],
+                            $_FILES['fileToUpload']['type'],
+                            $_FILES['fileToUpload']['name']
+                        )
+                    ];
+
+                    $postParameters = array_merge($postParameters, $data);
+                    $curl_handler->setOptions([CURLOPT_HEADER => true]);
+                }
+
+                $curl_handler->setOptions([
+                    CURLOPT_POST => true,
+                    CURLOPT_POSTFIELDS => $postParameters
+                ]);
             }
 
-            // upload file to transfer
-            if (isset($_FILES['fileToUpload'])) {
-                $data = [
-                    'fileToUpload' => curl_file_create(
-                        $_FILES['fileToUpload']['tmp_name'],
-                        $_FILES['fileToUpload']['type'],
-                        $_FILES['fileToUpload']['name']
-                    )
-                ];
-
-                $postParameters = array_merge($postParameters, $data);
-                $curl_handler->setOptions([CURLOPT_HEADER => true]);
+            $result = $curl_handler->execute();
+
+            if (!is_string($result)) {
+                throw new NotFoundHttpException(
+                    (int)$curl_handler->getInfo(CURLINFO_HTTP_CODE) .
+                    $curl_handler->getErrorMessage()
+                );
             }
 
-            $curl_handler->setOptions([
-                CURLOPT_POST => true,
-                CURLOPT_POSTFIELDS => $postParameters
-            ]);
-        }
+            $response = new Response($result);
+            $contentType = $curl_handler->getInfo(CURLINFO_CONTENT_TYPE);
 
-        $result = $curl_handler->execute();
+            $response->headers->set('Content-Type', $contentType);
 
-        if (! is_string($result)) {
-            throw new NotFoundHttpException(
-                (int) $curl_handler->getInfo(CURLINFO_HTTP_CODE) .
-                $curl_handler->getErrorMessage()
-            );
+            return $response;
+        } finally {
+            $curl_handler->close();
         }
-
-        $curl_handler->close();
-
-        $response = new Response($result);
-        $contentType = $curl_handler->getInfo(CURLINFO_CONTENT_TYPE);
-        $response->headers->set('Content-Type', $contentType);
-
-        return $response;
     }
 
     public static function getMime(?string $filepath, string $extension): ?string
diff --git a/templates/capsule/index.html.twig b/templates/capsule/index.html.twig
index 643b952..42ef71e 100644
--- a/templates/capsule/index.html.twig
+++ b/templates/capsule/index.html.twig
@@ -51,7 +51,7 @@
                 <div class="d-flex flex-column flex-md-row justify-content-center align-items-center">
                     <div class="m-4 ratio ratio-16x9">
                         <iframe
-                                src="{{ capsule.getEditionLink() }}"
+                                src="{{ legacy_url }}/{{ capsule.getEditionLink() }}"
                                 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                 allowfullscreen>
                         </iframe>
@@ -74,7 +74,7 @@
                             Delete capsule
                         </a>
                     </div>
-                    <a href="/" class="list-item lh-md">
+                    <a href="{{ capsule.getEditionLink() }}" class="list-item lh-md">
                         <button class="standard-button p-2">
                             Edit capsule
                         </button>
diff --git a/templates/project/edit.html.twig b/templates/project/edit.html.twig
new file mode 100644
index 0000000..4eb523f
--- /dev/null
+++ b/templates/project/edit.html.twig
@@ -0,0 +1,14 @@
+{% extends 'layout.html.twig' %}
+
+{% block body %}
+
+  <iframe src="{{ url }}"
+          class="w-100 h-100 top-0 start-0 position-absolute border-0"
+{#          style="width:100%;height:100%;top:0;left:0;position:absolute"#}
+{#          frameborder="0"#}
+          webkitallowfullscreen
+          mozallowfullscreen
+          allowfullscreen>
+  </iframe>
+
+{% endblock %}
\ No newline at end of file
diff --git a/tests/functional/ProjectControllerTest.php b/tests/functional/ProjectControllerTest.php
index efc7891..4803c99 100644
--- a/tests/functional/ProjectControllerTest.php
+++ b/tests/functional/ProjectControllerTest.php
@@ -9,6 +9,7 @@ use Symfony\Bundle\FrameworkBundle\KernelBrowser;
 use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
 use Symfony\Component\DomCrawler\Form;
 use Symfony\Component\Filesystem\Filesystem;
+use Symfony\Config\TwigExtra\StringConfig;
 
 class ProjectControllerTest extends WebTestCase
 {
@@ -69,15 +70,25 @@ class ProjectControllerTest extends WebTestCase
     }
 
     /** @phpstan-ignore-next-line */
-    private function getDOMDocument(): \DOMDocument
+    private function getDOMDocument(string $capsule_directory): \DOMDocument
     {
         $dom_xml = new \DOMDocument();
         $dom_xml->preserveWhiteSpace = false;
-        $dom_xml->load(self::XML_FILE_PATH);
+        $dom_xml->load($this->createXmlFilePath($capsule_directory));
 
         return $dom_xml;
     }
 
+    private function createCapsuleDirPath(string $capsule_directory): string
+    {
+        return self::TEST_DIR_PATH . $capsule_directory;
+    }
+
+    private function createXmlFilePath(string $capsule_directory): string
+    {
+        return $this->createCapsuleDirPath($capsule_directory) . '/file/project.xml';
+    }
+
     public function testProjectDirectoryWithCorrespondingXMLFileIsCreatedWhenCapsuleCreationIsSuccessful(): void
     {
         $video_url = "https://TestUrl";
@@ -93,6 +104,7 @@ class ProjectControllerTest extends WebTestCase
         );
 
         $this->client->followRedirect();
+        $this->assertResponseIsSuccessful('/my_capsules');
 
         $capsule_repository = $this->object_manager->getRepository(Capsule::class);
         $capsule_in_db = $capsule_repository->findOneBy(['name' => self::CAPSULE_NAME]);
@@ -101,11 +113,13 @@ class ProjectControllerTest extends WebTestCase
             throw new \Exception("Capsule does not exist.");
         }
 
-        self::assertInstanceOf(Capsule::class, $capsule_in_db);
         $capsule_name_in_db = $capsule_in_db->getName();
+        $capsule_directory = $capsule_in_db->getPreviewLink();
 
-        $dom_xml = $this->getDomDocument();
+        $this->assertDirectoryExists($capsule_directory);
+        $this->assertDirectoryIsReadable($capsule_directory);
 
+        $dom_xml = self::getDomDocument($capsule_directory);
         $video_node = $dom_xml->getElementsByTagName('video')->item(0);
 
         if ($video_node === null) {
@@ -114,10 +128,7 @@ class ProjectControllerTest extends WebTestCase
 
         $video_url_in_xml_file = $video_node->getAttribute('url');
 
-        $this->assertResponseIsSuccessful('/my_capsules');
         $this->assertEquals($video_url, $video_url_in_xml_file);
-        $this->assertDirectoryExists(self::CAPSULE_NAME);
-        $this->assertDirectoryIsReadable(self::CAPSULE_NAME);
         $this->assertSame(self::CAPSULE_NAME, $capsule_name_in_db);
     }
 }
-- 
GitLab