EpisodeController.php 8.33 KB
Newer Older
1
<?php
2

3
4
declare(strict_types=1);

5
6
7
8
9
10
11
12
/**
 * @copyright  2020 Podlibre
 * @license    https://www.gnu.org/licenses/agpl-3.0.en.html AGPL3
 * @link       https://castopod.org/
 */

namespace App\Controllers;

13
14
use ActivityPub\Objects\OrderedCollectionObject;
use ActivityPub\Objects\OrderedCollectionPage;
15
use Analytics\AnalyticsTrait;
16
17
use App\Entities\Episode;
use App\Entities\Podcast;
18
19
use App\Libraries\NoteObject;
use App\Libraries\PodcastEpisode;
20
21
use App\Models\EpisodeModel;
use App\Models\PodcastModel;
22
use CodeIgniter\Database\BaseBuilder;
23
use CodeIgniter\Exceptions\PageNotFoundException;
24
use CodeIgniter\HTTP\Response;
25
26
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
27
use SimpleXMLElement;
28

29
class EpisodeController extends BaseController
30
{
31
32
    use AnalyticsTrait;

33
34
35
    protected Podcast $podcast;

    protected Episode $episode;
36

37
    public function _remap(string $method, string ...$params): mixed
38
    {
39
40
41
42
43
        if (count($params) < 2) {
            throw PageNotFoundException::forPageNotFound();
        }

        if (
44
            ($podcast = (new PodcastModel())->getPodcastByName($params[0])) === null
45
46
47
        ) {
            throw PageNotFoundException::forPageNotFound();
        }
48

49
50
        $this->podcast = $podcast;

51
        if (
52
            ($episode = (new EpisodeModel())->getEpisodeBySlug($params[0], $params[1])) === null
53
        ) {
54
            throw PageNotFoundException::forPageNotFound();
55
        }
56

57
58
59
60
61
62
        $this->episode = $episode;

        unset($params[1]);
        unset($params[0]);

        return $this->{$method}(...$params);
63
64
    }

65
    public function index(): string
66
    {
67
        // Prevent analytics hit when authenticated
68
        if (! can_user_interact()) {
69
70
            $this->registerPodcastWebpageHit($this->episode->podcast_id);
        }
71

72
73
        $locale = service('request')
            ->getLocale();
74
75
76
        $cacheName =
            "page_podcast#{$this->podcast->id}_episode#{$this->episode->id}_{$locale}" .
            (can_user_interact() ? '_authenticated' : '');
77

78
        if (! ($cachedView = cache($cacheName))) {
79
            $data = [
80
                'podcast' => $this->podcast,
81
82
83
                'episode' => $this->episode,
            ];

84
            $secondsToNextUnpublishedEpisode = (new EpisodeModel())->getSecondsToNextUnpublishedEpisode(
85
                $this->podcast->id,
86
87
            );

88
89
            if (can_user_interact()) {
                helper('form');
90
                return view('podcast/episode_authenticated', $data);
91
            }
92
93
94
95
96
97
98
            // The page cache is set to a decade so it is deleted manually upon podcast update
            return view('podcast/episode', $data, [
                'cache' => $secondsToNextUnpublishedEpisode
                    ? $secondsToNextUnpublishedEpisode
                    : DECADE,
                'cache_name' => $cacheName,
            ]);
99
        }
100

101
        return $cachedView;
102
    }
103

104
105
    public function embeddablePlayer(string $theme = 'light-transparent'): string
    {
106
107
        header('Content-Security-Policy: frame-ancestors https://* http://*');

108
        // Prevent analytics hit when authenticated
109
        if (! can_user_interact()) {
110
111
            $this->registerPodcastWebpageHit($this->episode->podcast_id);
        }
112

113
        $session = Services::session();
114
115
        $session->start();
        if (isset($_SERVER['HTTP_REFERER'])) {
116
            $session->set('embeddable_player_domain', parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST));
117
118
        }

119
120
        $locale = service('request')
            ->getLocale();
121

122
        $cacheName = "page_podcast#{$this->podcast->id}_episode#{$this->episode->id}_embeddable_player_{$theme}_{$locale}";
123

124
        if (! ($cachedView = cache($cacheName))) {
125
126
127
128
129
130
131
132
            $theme = EpisodeModel::$themes[$theme];

            $data = [
                'podcast' => $this->podcast,
                'episode' => $this->episode,
                'theme' => $theme,
            ];

133
            $secondsToNextUnpublishedEpisode = (new EpisodeModel())->getSecondsToNextUnpublishedEpisode(
134
                $this->podcast->id,
135
136
137
138
139
140
141
142
143
144
145
146
147
            );

            // The page cache is set to a decade so it is deleted manually upon podcast update
            return view('embeddable_player', $data, [
                'cache' => $secondsToNextUnpublishedEpisode
                    ? $secondsToNextUnpublishedEpisode
                    : DECADE,
                'cache_name' => $cacheName,
            ]);
        }

        return $cachedView;
    }
148

149
    public function oembedJSON(): ResponseInterface
150
151
152
153
154
155
156
157
158
159
160
    {
        return $this->response->setJSON([
            'type' => 'rich',
            'version' => '1.0',
            'title' => $this->episode->title,
            'provider_name' => $this->podcast->title,
            'provider_url' => $this->podcast->link,
            'author_name' => $this->podcast->title,
            'author_url' => $this->podcast->link,
            'html' =>
                '<iframe src="' .
161
                $this->episode->embeddable_player_url .
162
163
164
165
                '" width="100%" height="200" frameborder="0" scrolling="no"></iframe>',
            'width' => 600,
            'height' => 200,
            'thumbnail_url' => $this->episode->image->large_url,
166
167
168
169
            'thumbnail_width' => config('Images')
                ->largeSize,
            'thumbnail_height' => config('Images')
                ->largeSize,
170
171
172
        ]);
    }

173
    public function oembedXML(): ResponseInterface
174
    {
175
        $oembed = new SimpleXMLElement("<?xml version='1.0' encoding='utf-8' standalone='yes'?><oembed></oembed>");
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

        $oembed->addChild('type', 'rich');
        $oembed->addChild('version', '1.0');
        $oembed->addChild('title', $this->episode->title);
        $oembed->addChild('provider_name', $this->podcast->title);
        $oembed->addChild('provider_url', $this->podcast->link);
        $oembed->addChild('author_name', $this->podcast->title);
        $oembed->addChild('author_url', $this->podcast->link);
        $oembed->addChild('thumbnail', $this->episode->image->large_url);
        $oembed->addChild('thumbnail_width', config('Images')->largeSize);
        $oembed->addChild('thumbnail_height', config('Images')->largeSize);
        $oembed->addChild(
            'html',
            htmlentities(
                '<iframe src="' .
191
                    $this->episode->embeddable_player_url .
192
193
194
                    '" width="100%" height="200" frameborder="0" scrolling="no"></iframe>',
            ),
        );
195
196
        $oembed->addChild('width', '600');
        $oembed->addChild('height', '200');
197

198
        return $this->response->setXML((string) $oembed);
199
    }
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

    /**
     * @noRector ReturnTypeDeclarationRector
     */
    public function episodeObject(): Response
    {
        $podcastObject = new PodcastEpisode($this->episode);

        return $this->response
            ->setContentType('application/json')
            ->setBody($podcastObject->toJSON());
    }

    /**
     * @noRector ReturnTypeDeclarationRector
     */
    public function comments(): Response
    {
        /**
         * get comments: aggregated replies from posts referring to the episode
         */
        $episodeComments = model('StatusModel')
            ->whereIn('in_reply_to_id', function (BaseBuilder $builder): BaseBuilder {
                return $builder->select('id')
                    ->from('activitypub_statuses')
                    ->where('episode_id', $this->episode->id);
            })
            ->where('`published_at` <= NOW()', null, false)
            ->orderBy('published_at', 'ASC');

        $pageNumber = (int) $this->request->getGet('page');

        if ($pageNumber < 1) {
            $episodeComments->paginate(12);
            $pager = $episodeComments->pager;
            $collection = new OrderedCollectionObject(null, $pager);
        } else {
            $paginatedComments = $episodeComments->paginate(12, 'default', $pageNumber);
            $pager = $episodeComments->pager;

            $orderedItems = [];
            if ($paginatedComments !== null) {
                foreach ($paginatedComments as $comment) {
                    $orderedItems[] = (new NoteObject($comment))->toArray();
                }
            }

            // @phpstan-ignore-next-line
            $collection = new OrderedCollectionPage($pager, $orderedItems);
        }

        return $this->response
            ->setContentType('application/activity+json')
            ->setBody($collection->toJSON());
    }
255
}