1
0
Fork 1
mirror of https://github.com/pixelfed/pixelfed.git synced 2024-12-23 16:24:29 +00:00
pixelfed/app/Http/Controllers/AvatarController.php

96 lines
2.9 KiB
PHP
Raw Normal View History

2018-06-01 02:36:58 +00:00
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
2018-08-13 03:51:05 +00:00
use Auth, Cache, Log, Storage;
2018-08-10 09:10:05 +00:00
use App\Avatar;
use App\Jobs\AvatarPipeline\AvatarOptimize;
2018-06-01 02:36:58 +00:00
class AvatarController extends Controller
{
2018-08-10 09:10:05 +00:00
public function __construct()
{
return $this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, [
'avatar' => 'required|mimes:jpeg,png|max:2000'
2018-08-10 09:10:05 +00:00
]);
try {
$user = Auth::user();
2018-08-13 03:51:05 +00:00
$profile = $user->profile;
2018-08-10 09:10:05 +00:00
$file = $request->file('avatar');
$path = $this->getPath($user, $file);
$dir = $path['root'];
$name = $path['name'];
$public = $path['storage'];
2018-08-13 03:51:05 +00:00
$currentAvatar = storage_path('app/'.$profile->avatar->media_path);
2018-08-10 09:10:05 +00:00
$loc = $request->file('avatar')->storeAs($public, $name);
2018-08-13 03:51:05 +00:00
$avatar = Avatar::whereProfileId($profile->id)->firstOrFail();
2018-08-10 09:10:05 +00:00
$opath = $avatar->media_path;
$avatar->media_path = "$public/$name";
$avatar->thumb_path = null;
$avatar->change_count = ++$avatar->change_count;
$avatar->last_processed_at = null;
$avatar->save();
2018-08-13 03:51:05 +00:00
Cache::forget("avatar:{$profile->id}");
2018-08-10 09:10:05 +00:00
AvatarOptimize::dispatch($user->profile, $currentAvatar);
} catch (Exception $e) {
}
return redirect()->back()->with('status', 'Avatar updated successfully. It may take a few minutes to update across the site.');
}
public function getPath($user, $file)
{
$basePath = storage_path('app/public/avatars');
$this->checkDir($basePath);
$id = $user->profile->id;
$path = $this->buildPath($id);
$dir = storage_path('app/'.$path);
$this->checkDir($dir);
$name = 'avatar.' . $file->guessExtension();
$res = ['root' => 'storage/app/' . $path, 'name' => $name, 'storage' => $path];
return $res;
}
public function checkDir($path)
{
if(!is_dir($path)) {
mkdir($path);
}
}
public function buildPath($id)
{
$padded = str_pad($id, 12, 0, STR_PAD_LEFT);
$parts = str_split($padded, 3);
foreach($parts as $k => $part) {
if($k == 0) {
$prefix = storage_path('app/public/avatars/'.$parts[0]);
$this->checkDir($prefix);
}
if($k == 1) {
$prefix = storage_path('app/public/avatars/'.$parts[0].'/'.$parts[1]);
$this->checkDir($prefix);
}
if($k == 2) {
$prefix = storage_path('app/public/avatars/'.$parts[0].'/'.$parts[1].'/'.$parts[2]);
$this->checkDir($prefix);
}
if($k == 3) {
$avatarpath = 'public/avatars/'.$parts[0].'/'.$parts[1].'/'.$parts[2].'/'.$parts[3];
$prefix = storage_path('app/'.$avatarpath);
$this->checkDir($prefix);
}
}
return $avatarpath;
}
2018-06-01 02:36:58 +00:00
}