Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: rank images #117

Merged
merged 5 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
run:
uses: flarum/framework/.github/workflows/[email protected]
with:
enable_backend_testing: false
enable_backend_testing: true
enable_phpstan: true

backend_directory: .
10 changes: 2 additions & 8 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
/vendor
composer.phar
.DS_Store
Thumbs.db
vendor
node_modules
bower_components
.idea
.floo*
js/dist
composer.lock
.phpunit.result.cache
26 changes: 22 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,37 @@
},
"flarum-cli": {
"modules": {
"githubActions": true
"githubActions": true,
"backendTesting": true
}
}
},
"scripts": {
"analyse:phpstan": "phpstan analyse",
"clear-cache:phpstan": "phpstan clear-result-cache"
"clear-cache:phpstan": "phpstan clear-result-cache",
"test": [
"@test:unit",
"@test:integration"
],
"test:unit": "phpunit -c tests/phpunit.unit.xml",
"test:integration": "phpunit -c tests/phpunit.integration.xml",
"test:setup": "@php tests/integration/setup.php"
},
"scripts-descriptions": {
"analyse:phpstan": "Run static analysis"
"analyse:phpstan": "Run static analysis",
"test": "Runs all tests.",
"test:unit": "Runs all unit tests.",
"test:integration": "Runs all integration tests.",
"test:setup": "Sets up a database for use with integration tests. Execute this only once."
},
"require-dev": {
"flarum/phpstan": "*",
"flarum/pusher": "*"
"flarum/pusher": "*",
"flarum/testing": "^1.0.0"
},
"autoload-dev": {
"psr-4": {
"FoF\\Gamification\\Tests\\": "tests/"
}
}
}
18 changes: 2 additions & 16 deletions extend.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,7 @@

(new Extend\ApiSerializer(Serializer\ForumSerializer::class))
->hasMany('ranks', Serializers\RankSerializer::class)
->attributes(function (Serializer\ForumSerializer $serializer, $forum, $attributes) {
$attributes['canViewRankingPage'] = $serializer->getActor()->can('fof.gamification.viewRankingPage');

return $attributes;
}),
->attributes(Api\AddForumAttributes::class),

(new Extend\ApiController(Controller\ShowForumController::class))
->prepareDataForSerialization(function (Controller\ShowForumController $controller, &$data) {
Expand All @@ -122,17 +118,7 @@
->default('fof-gamification.blockedUsers', '')
->default('fof-gamification.rankAmt', 2)
->default('fof-gamification.firstPostOnly', false)
->default('fof-gamification.allowSelfVotes', true)
->serializeToForum('fof-gamification.topimage1Url', 'fof-gamification.topimage1_path', function ($value) {
return $value ? "/assets/$value" : null;
})
->serializeToForum('fof-gamification.topimage2Url', 'fof-gamification.topimage2_path', function ($value) {
return $value ? "/assets/$value" : null;
})
->serializeToForum('fof-gamification.topimage3Url', 'fof-gamification.topimage3_path', function ($value) {
return $value ? "/assets/$value" : null;
})
->serializeToForum('fof-gamification-op-votes-only', 'fof-gamification.firstPostOnly', 'boolVal'),
->default('fof-gamification.allowSelfVotes', true),

(new Extend\ApiSerializer(Serializer\UserSerializer::class))
->attributes(AddUserAttributes::class),
Expand Down
21 changes: 21 additions & 0 deletions js/src/forum/components/RankingImage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import app from 'flarum/forum/app';
import Component, { ComponentAttrs } from 'flarum/common/Component';
import type Mithril from 'mithril';
import icon from 'flarum/common/helpers/icon';

interface RankingImageAttrs extends ComponentAttrs {
place: number;
}

export default class RankingImage extends Component<RankingImageAttrs> {
view() {
const imgUrl = app.forum.attribute(`fof-gamification.topimage${this.attrs.place}Url`);
const place = this.attrs.place;

return imgUrl ? (
<img className={`rankings-mobile rankings-image rankings-${place}`} src={imgUrl} alt="" />
) : (
<td className={`rankings-mobile rankings-${place}`}>{icon('fas fa-trophy')}</td>
);
}
}
16 changes: 2 additions & 14 deletions js/src/forum/components/RankingsPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import Button from 'flarum/common/components/Button';
import LoadingIndicator from 'flarum/common/components/LoadingIndicator';
import listItems from 'flarum/common/helpers/listItems';
import username from 'flarum/common/helpers/username';
import icon from 'flarum/common/helpers/icon';
import setting from '../helpers/setting';
import Link from 'flarum/common/components/Link';
import RankingImage from './RankingImage';

/**
* This page re-uses Flarum's IndexPage CSS classes
Expand Down Expand Up @@ -60,18 +59,7 @@ export default class RankingsPage extends Page {
++i;
return [
<tr className={'ranking-' + i}>
{i < 4 ? (
setting('customRankingImages', true) ? (
<img
className="rankings-mobile rankings-image"
src={app.forum.attribute('baseUrl') + app.forum.attribute(`fof-gamification.topimage${i}Url`)}
/>
) : (
<td className={'rankings-mobile rankings-' + i}>{icon('fas fa-trophy')}</td>
)
) : (
<td className="rankings-4 rankings-mobile">{this.addOrdinalSuffix(i)}</td>
)}
{i < 4 ? <RankingImage place={i} /> : <td className="rankings-4 rankings-mobile">{this.addOrdinalSuffix(i)}</td>}
<td>
<div className="PostUser">
<h3 className="rankings-info">
Expand Down
4 changes: 0 additions & 4 deletions resources/less/forum/extension.less
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,6 @@
}
}

.rankings-mobile {
width: 215px;
}

.CommentPost-votes {
.Post-points {
background-color: transparent;
Expand Down
59 changes: 59 additions & 0 deletions src/Api/AddForumAttributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

/*
* This file is part of fof/gamification.
*
* Copyright (c) FriendsOfFlarum.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace FoF\Gamification\Api;

use Flarum\Api\Serializer\ForumSerializer;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Filesystem\Cloud;
use Illuminate\Contracts\Filesystem\Factory;

class AddForumAttributes
{
/**
* @var SettingsRepositoryInterface
*/
protected $settings;

/**
* @var Cloud
*/
protected $uploadDir;

public function __construct(SettingsRepositoryInterface $settings, Factory $factory)
{
$this->settings = $settings;
$this->uploadDir = $factory->disk('flarum-assets');
}

public function __invoke(ForumSerializer $serializer, $model, array $attributes): array
{
$attributes['canViewRankingPage'] = $serializer->getActor()->can('fof.gamification.viewRankingPage');
$attributes['fof-gamification-op-votes-only'] = (bool) $this->settings->get('fof-gamification.firstPostOnly');

$attributes['fof-gamification.topimage1Url'] = $this->urlForKey('fof-gamification.topimage1_path');
$attributes['fof-gamification.topimage2Url'] = $this->urlForKey('fof-gamification.topimage2_path');
$attributes['fof-gamification.topimage3Url'] = $this->urlForKey('fof-gamification.topimage3_path');

return $attributes;
}

protected function urlForKey(string $key): ?string
{
$value = $this->settings->get($key);

if ($value === null) {
return null;
}

return $this->uploadDir->url($value);
}
}
19 changes: 8 additions & 11 deletions src/Api/Controllers/DeleteTopImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@
namespace FoF\Gamification\Api\Controllers;

use Flarum\Api\Controller\AbstractDeleteController;
use Flarum\Foundation\Paths;
use Flarum\Http\RequestUtil;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Filesystem\Cloud;
use Illuminate\Contracts\Filesystem\Factory;
use Illuminate\Support\Arr;
use Laminas\Diactoros\Response\EmptyResponse;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use Psr\Http\Message\ServerRequestInterface;

class DeleteTopImageController extends AbstractDeleteController
Expand All @@ -29,14 +28,14 @@ class DeleteTopImageController extends AbstractDeleteController
protected $settings;

/**
* @var Paths
* @var Cloud
*/
protected $paths;
protected $uploadDir;

public function __construct(SettingsRepositoryInterface $settings, Paths $paths)
public function __construct(SettingsRepositoryInterface $settings, Factory $factory)
{
$this->settings = $settings;
$this->paths = $paths;
$this->uploadDir = $factory->disk('flarum-assets');
}

protected function delete(ServerRequestInterface $request)
Expand All @@ -49,10 +48,8 @@ protected function delete(ServerRequestInterface $request)

$this->settings->set($key, null);

$uploadDir = new Filesystem(new Local($this->paths->public.'/assets'));

if ($uploadDir->has($path)) {
$uploadDir->delete($path);
if ($this->uploadDir->exists($path)) {
$this->uploadDir->delete($path);
}

return new EmptyResponse(204);
Expand Down
67 changes: 43 additions & 24 deletions src/Api/Controllers/UploadTopImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@

use Flarum\Api\Controller\ShowForumController;
use Flarum\Foundation\Paths;
use Flarum\Foundation\ValidationException;
use Flarum\Http\RequestUtil;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Filesystem\Cloud;
use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Intervention\Image\ImageManager;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\MountManager;
use Laminas\Diactoros\UploadedFile;
use Psr\Http\Message\ServerRequestInterface;
use Tobscure\JsonApi\Document;

Expand All @@ -41,52 +42,70 @@ class UploadTopImageController extends ShowForumController
*/
protected $imageManager;

public function __construct(SettingsRepositoryInterface $settings, Paths $paths, ImageManager $imageManager)
/**
* @var Cloud
*/
protected $uploadDir;

public function __construct(SettingsRepositoryInterface $settings, Paths $paths, ImageManager $imageManager, FilesystemFactory $factory)
{
$this->settings = $settings;
$this->paths = $paths;
$this->imageManager = $imageManager;
$this->uploadDir = $factory->disk('flarum-assets');
}

public function data(ServerRequestInterface $request, Document $document)
{
RequestUtil::getActor($request)->assertAdmin();

$id = Arr::get($request->getQueryParams(), 'id');
$id = (int) Arr::get($request->getQueryParams(), 'id', 0);

/** @var UploadedFile | null */
$file = Arr::first($request->getUploadedFiles());

$tmpFile = tempnam($this->paths->storage.'/tmp', 'topimage.'.$id);
$file->moveTo($tmpFile);
if (!$file) {
throw new ValidationException(['file' => 'No file was uploaded']);
}

if ('1' == $id) {
$size = 125;
} elseif ('2' == $id) {
$size = 75;
} else {
$size = 50;
if (!$file instanceof UploadedFile) {
if (is_array($file)) {
$file = Arr::first($file);
}
}

$encodedImage = $this->imageManager->make($tmpFile)->resize($size, $size)->encode('png');
file_put_contents($tmpFile, $encodedImage);
$tmpFile = @tempnam($this->paths->storage.'/tmp', 'topimage.'.$id);
$file->moveTo($tmpFile);

$extension = 'png';
switch ($id) {
case 1:
$size = 150;
break;
case 2:
$size = 125;
break;
default:
$size = 100;
break;
}

$mount = new MountManager([
'source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))),
'target' => new Filesystem(new Local($this->paths->public.'/assets')),
]);
$image = $this->imageManager->make($tmpFile);

if (($path = $this->settings->get($key = "fof-gamification.topimage{$id}_path")) && $mount->has($file = "target://$path")) {
$mount->delete($file);
if (extension_loaded('exif')) {
$image->orientate();
}

$uploadName = 'topimage-'.Str::lower(Str::random(8)).'.'.$extension;
$encodedImage = $image->fit($size, $size)->encode('png');

$mount->move('source://'.pathinfo($tmpFile, PATHINFO_BASENAME), "target://$uploadName");
$key = "fof-gamification.topimage{$id}_path";
$uploadName = 'topimage-'.Str::lower(Str::random(8)).'.png';

$this->uploadDir->put($uploadName, $encodedImage);

$this->settings->set($key, $uploadName);

unlink($tmpFile);

return parent::data($request, $document);
}
}
Loading
Loading