Merge pull request #160 from j122j/custom-notifications

Custom notifications
This commit is contained in:
AVMG 2021-08-08 16:05:40 +02:00 committed by GitHub
commit 55ae15be60
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 629 additions and 13 deletions

View file

@ -5,6 +5,8 @@ namespace App\Http\Controllers\Admin;
use App\Classes\Pterodactyl;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Notifications\DynamicNotification;
use Spatie\QueryBuilder\QueryBuilder;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
@ -12,8 +14,11 @@ use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\HtmlString;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
@ -50,6 +55,30 @@ class UserController extends Controller
]);
}
/**
* Get a JSON response of users.
*
* @return \Illuminate\Support\Collection|\App\models\User
*/
public function json(Request $request)
{
$users = QueryBuilder::for(User::query())
->allowedFilters(['id', 'name', 'pterodactyl_id', 'email'])
->paginate(25);
if ($request->query('user_id')) {
$user = User::query()->findOrFail($request->input('user_id'));
$user->avatarUrl = $user->getAvatar();
return $user;
}
return $users->map(function ($item) {
$item->avatarUrl = $item->getAvatar();
return $item;
});
}
/**
* Show the form for editing the specified resource.
*
@ -103,7 +132,6 @@ class UserController extends Controller
$user->update($request->all());
return redirect()->route('admin.users.index')->with('success', 'User updated!');
}
/**
@ -141,6 +169,56 @@ class UserController extends Controller
return redirect()->route('admin.users.index');
}
/**
* Show the form for seding notifications to the specified resource.
*
* @param User $user
* @return Application|Factory|View|Response
*/
public function notifications(User $user)
{
return view('admin.users.notifications');
}
/**
* Notify the specified resource.
*
* @param Request $request
* @param User $user
* @return RedirectResponse
* @throws Exception
*/
public function notify(Request $request)
{
$data = $request->validate([
"via" => "required|min:1|array",
"via.*" => "required|string|in:mail,database",
"all" => "required_without:users|boolean",
"users" => "required_without:all|min:1|array",
"users.*" => "exists:users,id",
"title" => "required|string|min:1",
"content" => "required|string|min:1"
]);
$mail = null;
$database = null;
if (in_array('database', $data["via"])) {
$database = [
"title" => $data["title"],
"content" => $data["content"]
];
}
if (in_array('mail', $data["via"])) {
$mail = (new MailMessage)
->subject($data["title"])
->line(new HtmlString($data["content"]));
}
$all = $data["all"] ?? false;
$users = $all ? User::all() : User::whereIn("id", $data["users"])->get();
Notification::send($users, new DynamicNotification($data["via"], $database, $mail));
return redirect()->route('admin.users.notifications')->with('success', 'Notification sent!');
}
/**
*
* @throws Exception
@ -185,16 +263,16 @@ class UserController extends Controller
})
->editColumn('role', function (User $user) {
switch ($user->role) {
case 'admin' :
case 'admin':
$badgeColor = 'badge-danger';
break;
case 'mod' :
case 'mod':
$badgeColor = 'badge-info';
break;
case 'client' :
case 'client':
$badgeColor = 'badge-success';
break;
default :
default:
$badgeColor = 'badge-secondary';
break;
}

View file

@ -0,0 +1,127 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\DiscordUser;
use App\Models\User;
use App\Notifications\DynamicNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\HtmlString;
use Spatie\ValidationRules\Rules\Delimited;
class NotificationController extends Controller
{
/**
* Display all notifications of an user.
* @param Request $request
* @param int $userId
* @return Response
*/
public function index(Request $request, int $userId)
{
$discordUser = DiscordUser::find($userId);
$user = $discordUser ? $discordUser->user : User::findOrFail($userId);
return $user->notifications()->paginate($request->query("per_page", 50));
}
/**
* Display a specific notification
*
* @param int $userId
* @param int $notificationId
* @return JsonResponse
*/
public function view(int $userId, $notificationId)
{
$discordUser = DiscordUser::find($userId);
$user = $discordUser ? $discordUser->user : User::findOrFail($userId);
$notification = $user->notifications()->where("id", $notificationId)->get()->first();
if (!$notification) {
return response()->json(["message" => "Notification not found."], 404);
}
return $notification;
}
/**
* Send a notification to an user.
*
* @param Request $request
* @param int $userId
* @return JsonResponse
*/
public function send(Request $request)
{
$data = $request->validate([
"via" => ["required", new Delimited("in:mail,database")],
"all" => "required_without:users|boolean",
"users" => ["required_without:all", new Delimited("exists:users,id")],
"title" => "required|string|min:1",
"content" => "required|string|min:1"
]);
$via = explode(",", $data["via"]);
$mail = null;
$database = null;
if (in_array("database", $via)) {
$database = [
"title" => $data["title"],
"content" => $data["content"]
];
}
if (in_array("mail", $via)) {
$mail = (new MailMessage)
->subject($data["title"])
->line(new HtmlString($data["content"]));
}
$all = $data["all"] ?? false;
$users = $all ? User::all() : User::whereIn("id", explode(",", $data["users"]))->get();
Notification::send($users, new DynamicNotification($via, $database, $mail));
return response()->json(["message" => "Notification successfully sent."]);
}
/**
* Delete all notifications from an user
*
* @param int $userId
* @return JsonResponse
*/
public function delete(int $userId)
{
$discordUser = DiscordUser::find($userId);
$user = $discordUser ? $discordUser->user : User::findOrFail($userId);
$count = $user->notifications()->delete();
return response()->json(["message" => "All notifications have been successfully deleted.", "count" => $count]);
}
/**
* Delete a specific notification
*
* @param int $userId
* @param int $notificationId
* @return JsonResponse
*/
public function deleteOne(int $userId, $notificationid)
{
$discordUser = DiscordUser::find($userId);
$user = $discordUser ? $discordUser->user : User::findOrFail($userId);
$notification = $user->notifications()->where("id", $notificationid)->get()->first();
if (!$notification) {
return response()->json(["message" => "Notification not found."], 404);
}
$notification->delete();
return response()->json($notification);
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class DynamicNotification extends Notification
{
use Queueable;
/**
* @var array
*/
private $via;
/**
* @var array
*/
private $database;
/**
* @var MailMessage
*/
private $mail;
/**
* Create a new notification instance.
*
* @param array $via
* @param array $database
* @param MailMessage $mail
*/
public function __construct($via, $database, $mail)
{
$this->via = $via;
$this->database = $database;
$this->mail = $mail;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via()
{
return $this->via;
}
public function toMail()
{
return $this->mail;
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray()
{
return $this->database;
}
}

View file

@ -6,6 +6,7 @@ use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Spatie\QueryBuilder\QueryBuilderRequest;
class AppServiceProvider extends ServiceProvider
{
@ -28,6 +29,7 @@ class AppServiceProvider extends ServiceProvider
{
Paginator::useBootstrap();
Schema::defaultStringLength(191);
QueryBuilderRequest::setArrayValueDelimiter('|');
Validator::extend('multiple_date_format', function ($attribute, $value, $parameters, $validator) {

View file

@ -9,6 +9,7 @@
"license": "MIT",
"require": {
"php": "^8.0|^7.4",
"ext-intl": "*",
"biscolab/laravel-recaptcha": "^5.0",
"doctrine/dbal": "^3.1",
"fideloper/proxy": "^4.4",
@ -22,8 +23,9 @@
"paypal/rest-api-sdk-php": "^1.14",
"socialiteproviders/discord": "^4.1",
"spatie/laravel-activitylog": "^3.16",
"yajra/laravel-datatables-oracle": "~9.0",
"ext-intl": "*"
"spatie/laravel-query-builder": "^3.5",
"spatie/laravel-validation-rules": "^3.0",
"yajra/laravel-datatables-oracle": "~9.0"
},
"require-dev": {
"facade/ignition": "^2.5",

143
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "dda32482531d11fdf6adc74fcba74715",
"content-hash": "b3b61a46d5d4d6560d052cfda863d12c",
"packages": [
{
"name": "asm89/stack-cors",
@ -3460,6 +3460,147 @@
],
"time": "2021-03-02T16:49:06+00:00"
},
{
"name": "spatie/laravel-query-builder",
"version": "3.5.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-query-builder.git",
"reference": "4e5257be24139836dc092f618d7c73bcb1c00302"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-query-builder/zipball/4e5257be24139836dc092f618d7c73bcb1c00302",
"reference": "4e5257be24139836dc092f618d7c73bcb1c00302",
"shasum": ""
},
"require": {
"illuminate/database": "^6.20.13|^7.30.4|^8.22.2",
"illuminate/http": "^6.20.13|7.30.4|^8.22.2",
"illuminate/support": "^6.20.13|7.30.4|^8.22.2",
"php": "^7.3|^8.0"
},
"require-dev": {
"ext-json": "*",
"laravel/legacy-factories": "^1.0.4",
"mockery/mockery": "^1.4",
"orchestra/testbench": "^4.9|^5.8|^6.3",
"phpunit/phpunit": "^9.0"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Spatie\\QueryBuilder\\QueryBuilderServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Spatie\\QueryBuilder\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Alex Vanderbist",
"email": "alex@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Easily build Eloquent queries from API requests",
"homepage": "https://github.com/spatie/laravel-query-builder",
"keywords": [
"laravel-query-builder",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-query-builder/issues",
"source": "https://github.com/spatie/laravel-query-builder"
},
"funding": [
{
"url": "https://spatie.be/open-source/support-us",
"type": "custom"
}
],
"time": "2021-07-05T14:17:44+00:00"
},
{
"name": "spatie/laravel-validation-rules",
"version": "3.0.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/laravel-validation-rules.git",
"reference": "43e15a70fb6148b0128d7981b0c0f3e99463b9fb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/laravel-validation-rules/zipball/43e15a70fb6148b0128d7981b0c0f3e99463b9fb",
"reference": "43e15a70fb6148b0128d7981b0c0f3e99463b9fb",
"shasum": ""
},
"require": {
"illuminate/support": "^6.0|^7.0|^8.0",
"php": "^7.3|^8.0"
},
"require-dev": {
"laravel/legacy-factories": "^1.0.4",
"myclabs/php-enum": "^1.6",
"orchestra/testbench": "^4.5|^5.0|^6.0",
"phpunit/phpunit": "^9.3",
"spatie/enum": "^2.2|^3.0"
},
"suggest": {
"league/iso3166": "Needed for the CountryCode rule"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Spatie\\ValidationRules\\ValidationRulesServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Spatie\\ValidationRules\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Freek Van der Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "A set of useful Laravel validation rules",
"homepage": "https://github.com/spatie/laravel-validation-rules",
"keywords": [
"laravel-validation-rules",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/laravel-validation-rules/issues",
"source": "https://github.com/spatie/laravel-validation-rules/tree/3.0.0"
},
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2020-11-30T15:23:31+00:00"
},
{
"name": "swiftmailer/swiftmailer",
"version": "v6.2.7",

View file

@ -28,6 +28,8 @@
<div class="card-header">
<div class="d-flex justify-content-between">
<h5 class="card-title"><i class="fas fa-users mr-2"></i>Users</h5>
<a href="{{route('admin.users.notifications')}}" class="btn btn-sm btn-primary"><i
class="fas fa-paper-plane mr-1"></i>Notify</a>
</div>
</div>

View file

@ -0,0 +1,188 @@
@extends('layouts.main')
@section('content')
<!-- CONTENT HEADER -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Users</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="{{route('home')}}">Dashboard</a></li>
<li class="breadcrumb-item"><a href="{{route('admin.users.index')}}">Users</a></li>
<li class="breadcrumb-item"><a class="text-muted"
href="{{route('admin.users.notifications')}}">Notifications</a></li>
</ol>
</div>
</div>
</div>
</section>
<!-- END CONTENT HEADER -->
<!-- MAIN CONTENT -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<form action="{{route('admin.users.notifications')}}" method="POST">
@csrf
@method('POST')
<div class="form-group">
<label>Users</label><br>
<input id="all" name="all"
type="checkbox" value="1"
onchange="toggleClass('users-form', 'd-none')">
<label for="all">All</label>
<div id="users-form">
<select id="users" name="users[]" class="form-control" multiple></select>
</div>
@error('all')
<div class="invalid-feedback d-block">
{{$message}}
</div>
@enderror
@error('users')
<div class="invalid-feedback d-block">
{{$message}}
</div>
@enderror
</div>
<div class="form-group">
<label>Send via</label><br>
<input value="database" id="database" name="via[]"
type="checkbox">
<label for="database">Database</label>
<br>
<input value="mail" id="mail" name="via[]"
type="checkbox">
<label for="mail">Mail</label>
@error('via')
<div class="invalid-feedback d-block">
{{$message}}
</div>
@enderror
</div>
<div class="form-group" >
<label for="title">Title</label>
<input value="{{old('title')}}" id="title" name="title"
type="text"
class="form-control @error('title') is-invalid @enderror">
@error('title')
<div class="invalid-feedback">
{{$message}}
</div>
@enderror
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea id="content"
name="content"
type="content"
class="form-control @error('content') is-invalid @enderror">
{{old('content')}}
</textarea>
@error('content')
<div class="text-danger">
{{$message}}
</div>
@enderror
</div>
<div class="form-group text-right">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- END CONTENT -->
<script>
document.addEventListener('DOMContentLoaded', (event) => {
// Summernote
$('#content').summernote({
height: 100,
toolbar: [
[ 'style', [ 'style' ] ],
[ 'font', [ 'bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear'] ],
[ 'fontname', [ 'fontname' ] ],
[ 'fontsize', [ 'fontsize' ] ],
[ 'color', [ 'color' ] ],
[ 'para', [ 'ol', 'ul', 'paragraph', 'height' ] ],
[ 'table', [ 'table' ] ],
[ 'insert', [ 'link'] ],
[ 'view', [ 'undo', 'redo', 'fullscreen', 'codeview', 'help' ] ]
]
})
function initUserSelect(data) {
$('#users').select2({
ajax: {
url: '/admin/users.json',
dataType: 'json',
delay: 250,
data: function (params) {
return {
filter: { email: params.term },
page: params.page,
};
},
processResults: function (data, params) {
return { results: data };
},
cache: true,
},
data: data,
minimumInputLength: 2,
templateResult: function (data) {
if (data.loading) return data.text;
const $container = $(
"<div class='select2-result-users clearfix' style='display:flex;'>" +
"<div class='select2-result-users__avatar' style='display:flex;align-items:center;'><img class='img-circle img-bordered-s' src='" + data.avatarUrl + "?s=40' /></div>" +
"<div class='select2-result-users__meta' style='margin-left:10px'>" +
"<div class='select2-result-users__username' style='font-size:16px;'></div>" +
"<div class='select2-result-users__email' style='font-size=13px;'></div>" +
"</div>" +
"</div>"
);
$container.find(".select2-result-users__username").text(data.name);
$container.find(".select2-result-users__email").text(data.email);
return $container;
},
templateSelection: function (data) {
$container = $('<div> \
<span> \
<img class="img-rounded img-bordered-xs" src="' + data.avatarUrl + '?s=120" style="height:24px;margin-top:-4px;" alt="User Image"> \
</span> \
<span class="select2-selection-users__username" style="padding-left:10px;padding-right:10px;"></span> \
</div>');
$container.find(".select2-selection-users__username").text(data.name);
return $container;
}
})
}
initUserSelect()
})
function toggleClass(id, className) {
document.getElementById(id).classList.toggle(className)
}
</script>
@endsection

View file

@ -19,6 +19,9 @@
{{-- datetimepicker --}}
<link rel="stylesheet" href="{{asset('plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css')}}">
{{-- select2 --}}
<link rel="stylesheet" href="{{asset('plugins/select2/css/select2.min.css')}}">
<link rel="stylesheet" href="{{asset('css/app.css')}}">
<link rel="preload" href="{{asset('plugins/fontawesome-free/css/all.min.css')}}" as="style"
onload="this.onload=null;this.rel='stylesheet'">
@ -344,6 +347,9 @@
<!-- Datetimepicker -->
<script src="{{asset('plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js')}}"></script>
<!-- Select2 -->
<script src={{asset('plugins/select2/js/select2.min.js')}}>
<script>
$(document).ready(function () {
$('[data-toggle="popover"]').popover();

View file

@ -1,5 +1,6 @@
<?php
use App\Http\Controllers\Api\NotificationController;
use App\Http\Controllers\Api\ServerController;
use App\Http\Controllers\Api\UserController;
use App\Http\Controllers\Api\VoucherController;
@ -25,9 +26,12 @@ Route::middleware('api.token')->group(function () {
Route::patch('/servers/{server}/unsuspend', [ServerController::class, 'unSuspend']);
Route::resource('servers', ServerController::class)->except(['store', 'create', 'edit', 'update']);
// Route::get('/vouchers/{voucher}/users' , [VoucherController::class , 'users']);
Route::resource('vouchers', VoucherController::class)->except('create' , 'edit');
// Route::get('/vouchers/{voucher}/users' , [VoucherController::class , 'users']);
Route::resource('vouchers', VoucherController::class)->except('create', 'edit');
Route::get('/notifications/{user}', [NotificationController::class, 'index']);
Route::get('/notifications/{user}/{notification}', [NotificationController::class, 'view']);
Route::post('/notifications', [NotificationController::class, 'send']);
Route::delete('/notifications/{user}', [NotificationController::class, 'delete']);
Route::delete('/notifications/{user}/{notification}', [NotificationController::class, 'deleteOne']);
});

View file

@ -74,8 +74,11 @@ Route::middleware('auth')->group(function () {
Route::resource('activitylogs', ActivityLogController::class);
Route::get("users.json", [UserController::class, "json"])->name('users.json');
Route::get('users/loginas/{user}', [UserController::class, 'loginAs'])->name('users.loginas');
Route::get('users/datatable', [UserController::class, 'datatable'])->name('users.datatable');
Route::get('users/notifications', [UserController::class, 'notifications'])->name('users.notifications');
Route::post('users/notifications', [UserController::class, 'notify'])->name('users.notifications');
Route::resource('users', UserController::class);
Route::get('servers/datatable', [AdminServerController::class, 'datatable'])->name('servers.datatable');