Browse Source

Fixed minor bug
working on user quota

Sergio Brighenti 5 years ago
parent
commit
a5b8db5330

+ 4 - 2
app/Controllers/AdminController.php

@@ -3,6 +3,7 @@
 namespace App\Controllers;
 
 use App\Database\DB;
+use App\Database\Migrator;
 use App\Web\Media;
 use League\Flysystem\FileNotFoundException;
 use League\Flysystem\Filesystem;
@@ -32,7 +33,7 @@ class AdminController extends Controller
         $hideByDefault = $this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'hide_by_default\'')->fetch()->value ?? 'off';
         $copyUrl = $this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'copy_url_behavior\'')->fetch()->value ?? 'off';
         $quotaEnabled = $this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'quota_enabled\'')->fetch()->value ?? 'off';
-        $defaultUserQuota = $this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'default_user_quota\'')->fetch()->value ?? '1G';
+        $defaultUserQuota = $this->database->query('SELECT `value` FROM `settings` WHERE `key` = \'default_user_quota\'')->fetch()->value ?? stringToBytes('1G');
 
         return view()->render($response, 'dashboard/system.twig', [
             'usersCount' => $usersCount,
@@ -105,7 +106,8 @@ class AdminController extends Controller
      */
     public function recalculateUserQuota(Response $response): Response
     {
-        Media::recalculateQuotas($this->database, $this->storage);
+        $migrator = new Migrator($this->database, null);
+        $migrator->reSyncQuotas($this->storage);
         $this->session->alert(lang('quota_recalculated'));
         return redirect($response, route('system'));
     }

+ 1 - 0
app/Controllers/Auth/LoginController.php

@@ -62,6 +62,7 @@ class LoginController extends Controller
         $this->session->set('user_id', $result->id);
         $this->session->set('username', $result->username);
         $this->session->set('admin', $result->is_admin);
+        // TODO: update
         $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($result->id)));
 
         $this->session->alert(lang('welcome', [$result->username]), 'info');

+ 6 - 17
app/Controllers/Controller.php

@@ -48,29 +48,18 @@ abstract class Controller
         if ($this->container->has($name)) {
             return $this->container->get($name);
         }
+
+        return null;
     }
 
     /**
      * @param $id
      *
-     * @return int
+     * @return object
      */
-    protected function getUsedSpaceByUser($id): int
+    protected function getUsedSpaceByUser($id)
     {
-        $medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id);
-
-        $totalSize = 0;
-
-        $filesystem = $this->storage;
-        foreach ($medias as $media) {
-            try {
-                $totalSize += $filesystem->getSize($media->storage_path);
-            } catch (FileNotFoundException $e) {
-                $this->logger->error('Error calculating file size', ['exception' => $e]);
-            }
-        }
-
-        return $totalSize;
+        return $this->database->query('SELECT `current_disk_quota`, `max_disk_quota` FROM `users` WHERE `id` = ?', $id)->fetch();
     }
 
     /**
@@ -99,7 +88,7 @@ abstract class Controller
 
         $this->database->query('UPDATE `users` SET `current_disk_quota`=? WHERE `id` = ?', [
             $tot,
-            $user->id
+            $user->id,
         ]);
 
         return true;

+ 1 - 0
app/Controllers/MediaController.php

@@ -203,6 +203,7 @@ class MediaController extends Controller
             $size = $this->deleteMedia($request, $media->storage_path, $id);
             $this->updateUserQuota($request, $media->user_id, $size, true);
             $this->logger->info('User '.$this->session->get('username').' deleted a media.', [$id]);
+            //TODO update
             $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($this->session->get('user_id'))));
         } else {
             throw new HttpUnauthorizedException($request);

+ 31 - 1
app/Database/Migrator.php

@@ -2,6 +2,8 @@
 
 namespace App\Database;
 
+use League\Flysystem\FileNotFoundException;
+use League\Flysystem\Filesystem;
 use PDOException;
 
 class Migrator
@@ -26,7 +28,7 @@ class Migrator
      * @param string $schemaPath
      * @param bool   $firstMigrate
      */
-    public function __construct(DB $db, string $schemaPath, bool $firstMigrate = false)
+    public function __construct(DB $db, ?string $schemaPath, bool $firstMigrate = false)
     {
         $this->db = $db;
         $this->schemaPath = $schemaPath;
@@ -92,4 +94,32 @@ class Migrator
             }
         }
     }
+
+    /**
+     * @param  Filesystem  $filesystem
+     */
+    public function reSyncQuotas(Filesystem $filesystem)
+    {
+        $uploads = $this->db->query('SELECT `id`,`user_id`, `storage_path` FROM `uploads`')->fetchAll();
+
+        $usersQuotas = [];
+
+        foreach ($uploads as $upload) {
+            if (!array_key_exists($upload->user_id, $usersQuotas)) {
+                $usersQuotas[$upload->user_id] = 0;
+            }
+            try {
+                $usersQuotas[$upload->user_id] += $filesystem->getSize($upload->storage_path);
+            } catch (FileNotFoundException $e) {
+                $this->db->query('DELETE FROM `uploads` WHERE `id` = ?', $upload->id);
+            }
+        }
+
+        foreach ($usersQuotas as $userId => $quota) {
+            $this->db->query('UPDATE `users` SET `current_disk_quota`=? WHERE `id` = ?', [
+                $quota,
+                $userId,
+            ]);
+        }
+    }
 }

+ 1 - 0
app/Factories/ViewFactory.php

@@ -40,6 +40,7 @@ class ViewFactory
         $twig->addFunction(new TwigFunction('queryParams', 'queryParams'));
         $twig->addFunction(new TwigFunction('isDisplayableImage', 'isDisplayableImage'));
         $twig->addFunction(new TwigFunction('inPath', 'inPath'));
+        $twig->addFunction(new TwigFunction('humanFileSize', 'humanFileSize'));
 
         return new View($twig);
     }

+ 1 - 0
app/Middleware/RememberMiddleware.php

@@ -29,6 +29,7 @@ class RememberMiddleware extends Middleware
                 $this->session->set('user_id', $result->id);
                 $this->session->set('username', $result->username);
                 $this->session->set('admin', $result->is_admin);
+                // TODO: update
                 $this->session->set('used_space', humanFileSize($this->getUsedSpaceByUser($result->id)));
             }
 

+ 0 - 37
app/Web/Media.php

@@ -1,37 +0,0 @@
-<?php
-
-
-namespace App\Web;
-
-
-use App\Database\DB;
-use League\Flysystem\FileNotFoundException;
-use League\Flysystem\Filesystem;
-
-class Media
-{
-    public static function recalculateQuotas(DB $db, Filesystem $filesystem)
-    {
-        $uploads = $db->query('SELECT `id`,`user_id`, `storage_path` FROM `uploads`')->fetchAll();
-
-        $usersQuotas = [];
-
-        foreach ($uploads as $upload) {
-            if (!array_key_exists($upload->user_id, $usersQuotas)) {
-                $usersQuotas[$upload->user_id] = 0;
-            }
-            try {
-                $usersQuotas[$upload->user_id] += $filesystem->getSize($upload->storage_path);
-            } catch (FileNotFoundException $e) {
-                $db->query('DELETE FROM `uploads` WHERE `id` = ?', $upload->id);
-            }
-        }
-
-        foreach ($usersQuotas as $userId => $quota) {
-            $db->query('UPDATE `users` SET `current_disk_quota`=? WHERE `id` = ?', [
-                $quota,
-                $userId,
-            ]);
-        }
-    }
-}

+ 1 - 3
install/index.php

@@ -188,6 +188,7 @@ $app->post('/', function (Request $request, Response $response, Filesystem $stor
 
         $migrator = new Migrator($db, __DIR__.'/../resources/schemas', $firstMigrate);
         $migrator->migrate();
+        $migrator->reSyncQuotas($storage);
     } catch (PDOException $e) {
         $session->alert("Cannot connect to the database: {$e->getMessage()} [{$e->getCode()}]", 'danger');
 
@@ -208,9 +209,6 @@ $app->post('/', function (Request $request, Response $response, Filesystem $stor
         }
     }
 
-    // recalculate user quota
-    Media::recalculateQuotas($db, $storage);
-
     // if is upgrading and existing installation, put it out maintenance
     if ($installed) {
         unset($config['maintenance']);

+ 1 - 0
resources/lang/en.lang.php

@@ -133,4 +133,5 @@ return [
     'password_restored' => 'Password has been reset.',
     'recalculate_user_quota' => 'Recalculate user quota from disk',
     'quota_recalculated' => 'User quota recalculated from the disk successfully.',
+    'used_space' => 'Used Space',
 ];

+ 2 - 0
resources/templates/user/index.twig

@@ -19,6 +19,7 @@
                             <th>Email</th>
                             <th>{{ lang('username') }}</th>
                             <th>{{ lang('user_code') }}</th>
+                            <th>{{ lang('used_space') }}</th>
                             <th>{{ lang('active') }}</th>
                             <th>{{ lang('admin') }}</th>
                             <th>{{ lang('reg_date') }}</th>
@@ -34,6 +35,7 @@
                                 <td>
                                     <pre>{{ user.user_code|default(lang('none')) }}</pre>
                                 </td>
+                                <td>{{ humanFileSize(user.current_disk_quota) }}</td>
                                 <td>
                                     {% if user.active %}
                                         <span class="badge badge-success"><i class="fas fa-check"></i></span>