Skip to content

Commit

Permalink
Deprecate unused classes and add new Notifier functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
ewilan-riviere committed Jan 26, 2024
1 parent 808fbb7 commit 1f39ce1
Show file tree
Hide file tree
Showing 8 changed files with 510 additions and 5 deletions.
79 changes: 79 additions & 0 deletions src/Commands/NotifierCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace Kiwilan\Steward\Commands;

use App\Utils\Notifier;
use Illuminate\Console\Command;

class NotifierCommand extends Commandable
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'notifier
{message : Message to send.}
{--t|type= : `mail`, `slack` or `discord`.}
{--w|webhook : Webhook URL for Slack or Discord.}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Send notifications with mail, Discord or Slack.';

public function __construct(
protected ?string $message = null,
protected ?string $type = 'discord',
protected ?string $webhook = null,
) {
parent::__construct();
}

/**
* Execute the console command.
*/
public function handle(): int
{
$this->title();

$this->message = (string) $this->argument('message');
$this->type = (string) $this->option('type');
$this->webhook = (string) $this->option('webhook');

$this->info("Sending notification to {$this->type}...");

if ($this->type === 'mail') {
Notifier::mail()
->auto()
->message($this->message)
->send();

return Command::SUCCESS;
}

if ($this->type === 'discord') {
$this->info("Webhook: {$this->webhook}");
Notifier::discord($this->webhook)
->message($this->message)
->send();

return Command::SUCCESS;
}

if ($this->type === 'slack') {
$this->info("Webhook: {$this->webhook}");
Notifier::slack($this->webhook)
->message($this->message)
->send();

return Command::SUCCESS;
}

$this->error('Type not found.');

return Command::FAILURE;
}
}
6 changes: 3 additions & 3 deletions src/Services/MailService.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
namespace Kiwilan\Steward\Services;

use Kiwilan\Steward\Services\Mail\MailServer;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;

/**
* @deprecated
*/
class MailService implements MailServer
{
public function __construct(
Expand Down
3 changes: 3 additions & 0 deletions src/Services/Notify/Notifying.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
use Kiwilan\Steward\StewardConfig;
use Psr\Http\Message\ResponseInterface;

/**
* @deprecated
*/
abstract class Notifying
{
protected function __construct(
Expand Down
3 changes: 3 additions & 0 deletions src/Services/NotifyService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
use Kiwilan\Steward\Services\Notify\SlackNotify;
use Kiwilan\Steward\StewardConfig;

/**
* @deprecated
*/
class NotifyService
{
protected function __construct(
Expand Down
1 change: 1 addition & 0 deletions src/StewardServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function configurePackage(Package $package): void
\Kiwilan\Steward\Commands\Log\LogClearCommand::class,
\Kiwilan\Steward\Commands\MediaCleanCommand::class,
\Kiwilan\Steward\Commands\NotifyCommand::class,
\Kiwilan\Steward\Commands\NotifierCommand::class,
\Kiwilan\Steward\Commands\Publish\PublishCommand::class,
\Kiwilan\Steward\Commands\Publish\PublishScheduledCommand::class,
\Kiwilan\Steward\Commands\RoutePrintCommand::class,
Expand Down
74 changes: 74 additions & 0 deletions src/Utils/Journal.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace App\Utils;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class Journal
{
protected function __construct(
protected ?string $message = null,
protected string $level = 'info',
protected array $data = [],
protected ?Collection $users = null,
) {
$this->log();
}

public static function info(string $message, array $data = []): self
{

return new self($message, 'info', $data);
}

public static function debug(string $message, array $data = []): self
{
return new self($message, 'debug', $data);
}

public static function warning(string $message, array $data = []): self
{
return new self($message, 'warning', $data);
}

public static function error(string $message, array $data = []): self
{
return new self($message, 'error', $data);
}

private function log(): void
{
Log::log($this->level, $this->message, $this->data);
}

/**
* Send notification to database for Users with access to Filament admin panel with `filament/notifications` package.
*
* @param Model|Authenticatable|Collection|array|null $users To send notification to.
*/
public function toDatabase(Model|Authenticatable|Collection|array|null $users): void
{
if (! class_exists('\Filament\Notifications\Notification')) {
throw new \Exception('Filament notifications is not installed, check https://filamentphp.com/docs/3.x/notifications/installation');
}

if (! class_exists('\App\Models\User')) {
throw new \Exception('User model not found');
}

$filamentUsers = $this->users;

if (! $filamentUsers) {
$users = '\App\Models\User';
$filamentUsers = $users::all()->map(fn ($user) => $user->canAccessPanel());
}

\Filament\Notifications\Notification::make()
->title($this->level)
->body($this->message)
->sendToDatabase($filamentUsers);
}
}
141 changes: 139 additions & 2 deletions src/Utils/Notifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,147 @@

namespace App\Utils;

use Illuminate\Support\Facades\Log;
use Kiwilan\Steward\Utils\Notifier\NotifierMail;
use Symfony\Component\Mime\Email;

/**
* Send notifications to email, Slack or Discord.
*/
class Notifier
{
public function notify($message)
protected function __construct(
protected ?string $type = null,
protected ?string $message = null,
protected ?NotifierMail $mail = null,
protected ?string $slack = null,
protected ?string $discord = null,
protected bool $success = false,
) {
}

/**
* Send notification to email.
*/
public static function mail(): NotifierMail
{
$self = new self();

$self->type = 'mail';
$self->mail = NotifierMail::make($self);

return $self->mail;
}

/**
* Send notification to Slack channel via webhook.
*
* @param string $webhook Slack webhook URL, like `https://hooks.slack.com/services/X/Y/Z`
*
* @see https://api.slack.com/messaging/webhooks
*/
public static function slack(string $webhook): self
{
$self = new self();

$self->type = 'slack';
$self->slack = $webhook;

return $self;
}

/**
* Send notification to Discord channel via webhook.
*
* @param string $webhook Discord webhook URL, like `https://discord.com/api/webhooks/X/Y`
*
* @see https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks
*/
public static function discord(string $webhook): self
{
$self = new self();

$self->type = 'discord';
$self->discord = $webhook;

return $self;
}

public function message(string $message): self
{
echo $message;
$this->message = $message;

return $this;
}

public function send(): bool
{
if (! $this->type) {
throw new \Exception('Notifier type is not defined');
}

if (! $this->message) {
throw new \Exception('Notifier message is not defined');
}

Log::debug("Sending {$this->type} notification: {$this->message}...");

try {
if ($this->type === 'slack') {
$this->sendToSlack();
}

if ($this->type === 'discord') {
$this->sendToDiscord();
}
} catch (\Throwable $th) {
Log::error("{$this->type} notification failed: {$th->getMessage()}");

return false;
}

Log::debug("{$this->type} notification sent");

return $this->success;
}

private function sendToDiscord(): void
{
$res = $this->sendRequest($this->discord, 'content');
if ($res->getStatusCode() !== 204) {
Log::error('Discord notification failed', [
'response' => $res->getBody()->getContents(),
]);
} else {
$this->success = true;
}
}

private function sendToSlack(): void
{
$res = $this->sendRequest($this->slack, 'text');
if ($res->getStatusCode() !== 200) {
Log::error('Slack notification failed', [
'response' => $res->getBody()->getContents(),
]);
} else {
$this->success = true;
}
}

private function sendRequest(string $url, string $bodyName): \Psr\Http\Message\ResponseInterface
{
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $url, [
'headers' => [
'Accept' => 'application/json',
],
'json' => [
$bodyName => $this->message,
],
'http_errors' => false,
]);

return $response;
}
}
Loading

0 comments on commit 1f39ce1

Please sign in to comment.