Skip to content
Draft
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
232 changes: 232 additions & 0 deletions app/Classes/VATUSADiscord.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
<?php
/**
* Interact with Notifications
* @author Blake Nahin <b.nahin@vatusa.net>
*/

namespace App\Classes;

use App\Facility;
use App\FacilityNotificationChannel;
use App\NotificationSetting;
use App\User;
use Exception;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Carbon;
use Psr\Http\Message\ResponseInterface;

class VATUSADiscord
{
private $guzzle;

public const NOTIFY_EMAIL = 1;
public const NOTIFY_DISCORD = 2;
public const NOTIFY_BOTH = 3;

/**
* VATUSA Discord constructor.
*/
public function __construct()
{
$this->guzzle = new Client(['base_uri' => config('services.discord.botServer')]);
}

/**
* Get the user's Notification option for a type.
* @param \App\User $user
* @param string $type
*
* @return int
*/
public function getNotificationOption(User $user, string $type): int
{
$record = NotificationSetting::where('cid', $user->cid)->where('type', $type)->first();

return $record ? $record->option : 0;
}

/**
* Get the facility's Notification channel for a type.
* @param \App\Facility $facility
* @param string $type
*
* @return int
*/
public function getFacilityNotificationChannel(Facility $facility, string $type): int
{
$record = FacilityNotificationChannel::where('facility', $facility->id)->where('type', $type)->first();

return $record && $facility->discord_guild ? $record->channel : 0;
}

/**
* Get an array of all the user's notification options.
* @param \App\User $user
*
* @return array
*/
public function getAllUserNotificationOptions(User $user): array
{
$records = NotificationSetting::where('cid', $user->cid)->get();
$return = array();
foreach ($records as $record) {
$return[$record->type] = $record->option;
}

return $return;
}

/**
* Get an array of all the facility's notification channels.
* @param \App\Facility $facility
*
* @return array
*/
public function getAllFacilityNotificationChannels(Facility $facility): array
{
$records = FacilityNotificationChannel::where('facility', $facility->id)->get();
$return = array();
foreach ($records as $record) {
$return[$record->type] = $record->channel;
}

return $return;
}

/**
* Send Notification to Bot Server
*
* @param string $type The notification identifier.
* @param string $medium The medium of notification, dm | discord.
* @param array $data The notification data.
* @param string|null $guildId The guild's ID
* @param string|null $channelId The channel's ID
* @param string|null $userId The user's ID.
*
* @return bool
*/
public function sendNotification(
string $type,
string $medium,
array $data,
?string $guildId = null,
?string $channelId = null,
?string $userId = null
): bool {
if ($guildId && $channelId) {
$data = array_merge($data, compact('guildId', 'channelId'));
}
if ($userId) {
$data = array_merge($data, compact('userId'));
}
try {
$this->sendRequest('POST', "notifications/$medium/$type", ['json' => $data]);
} catch (Exception $e) {
return 0;
}

return 1;
}

/**
* Determine if the User has configured the Notification.
*
* @param \App\User|\Illuminate\Contracts\Auth\Authenticatable $user
* @param string $type
* @param string $medium
*
* @return bool
*/
public function userWantsNotification(User $user, string $type, string $medium): bool
{
if (!$user->discord_id) {
return false;
}
$option = $this->getNotificationOption($user, $type);
if ($option === self::NOTIFY_BOTH) {
return true;
}

switch (strtolower($medium)) {
case "discord":
return $option === self::NOTIFY_DISCORD;
case "email":
return $option === self::NOTIFY_EMAIL;
default:
return false;
}
}

/**
* Get an array of all the Guilds that the User is an admin in
* and that the Bot is a member of.
*
* @param \App\User $user
*
* @return array
*/
public function getUserAdminGuilds(User $user): array
{
try {
$response = $this->sendRequest("GET", "/guilds/" . $user->discord_id);
} catch (Exception $e) {
return [];
}

if ($response->getStatusCode() === 200) {
return json_decode($response->getBody(), true);
}

return [];
}

/**
* Get an array of all the channels in a Guild.
* @param string $guild
*
* @return array
*/
public function getGuildChannels(string $guild): array
{
try {
$response = $this->sendRequest("GET", "/guild/$guild/channels");
} catch (Exception $e) {
return [];
}
if ($response->getStatusCode() === 200) {
return json_decode($response->getBody(), true);
}

return [];
}

/**
* Send request to the Bot Server.
*
* @param string $method The request method.
* @param string $uri The request URI.
* @param array|null $data The request body.
*
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*/
private function sendRequest(string $method, string $uri, ?array $data = null): ResponseInterface
{
$iss = Carbon::now();
$jwt = JWT::encode([
'iat' => $iss->getTimestamp(),
'iss' => config('app.url'),
'aud' => config('services.discord.botServer'),
'nbf' => $iss->getTimestamp(),
'exp' => $iss->addMinute()->getTimestamp()
], config('services.discord.botSecret'), 'HS512');
try {
return $this->guzzle->request($method, $uri,
['json' => $data ?? [], 'headers' => ['Authorization' => 'Bearer ' . $jwt]]);
} catch (GuzzleException $e) {
throw new Exception("Unable to make request to the Discord Bot Server. " . $e->getMessage());
}
}
}
73 changes: 60 additions & 13 deletions app/Console/Commands/SendAcademyRatingExamEmails.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

use App\AcademyBasicExamEmail;
use App\AcademyExamAssignment;
use App\Classes\VATUSADiscord;
use App\Classes\VATUSAMoodle;
use App\Http\Middleware\PrivateCORS;
use App\Facility;
use App\Mail\AcademyExamSubmitted;
use App\User;
use Carbon\Carbon;
Expand All @@ -30,6 +31,7 @@ class SendAcademyRatingExamEmails extends Command
protected $description = 'Checks for final exam attempts and sends emails.';

private $moodle;
private $notify;

/**
* Create a new command instance.
Expand All @@ -40,12 +42,13 @@ public function __construct()
{
parent::__construct();
$this->moodle = new VATUSAMoodle();
$this->notify = new VATUSADiscord();
}

/**
* Execute the console command.
*
* @return mixed
* @return void
* @throws \Exception
*/
public function handle()
Expand All @@ -54,8 +57,16 @@ public function handle()
$student = $assignment->student;
$studentName = $student->name;
$instructor = $assignment->instructor;
$instructorName = $instructor->fullname();
$quizId = $assignment->quiz_id;
$attemptEmailsSent = $assignment->attempt_emails_sent ? explode(',', $assignment->attempt_emails_sent) : [];
$ta = $assignment->student->facilityObj->ta();
if (!$ta) {
$ta = $assignment->student->facilityObj->datm();
}
if (!$ta) {
$ta = $assignment->student->facilityObj->atm();
}

if ($assignment->created_at->diffInDays(Carbon::now()) > 30) {
log_action($assignment->student->cid,
Expand Down Expand Up @@ -90,14 +101,40 @@ public function handle()
$grade = $attempt['grade'];
$passed = $grade >= $passingGrade;

$result = compact('testName', 'studentName', 'attemptNum', 'grade',
$result = compact('testName', 'studentName', 'instructorName', 'attemptNum', 'grade',
'passed', 'passingGrade', 'attemptId');
$mail = Mail::bcc(['vatusa3@vatusa.net', 'vatusa13@vatusa.net']);
if ($hasUser = $this->notify->userWantsNotification($student, "academyExamResult", "email")) {
$mail->to($student);
}
if ($this->notify->userWantsNotification($instructor, "academyExamResult", "email")) {
$hasUser ? $mail->cc($instructor) : $mail->to($instructor);
$hasUser = true;
}
if ($ta && $this->notify->userWantsNotification($ta, "academyExamResult", "email")) {
$hasUser ? $mail->cc($instructor) : $mail->to($ta);
}

$mail = Mail::to($student)->cc($instructor);
//if ($attemptNum == 3 && !$passed) {
$mail->bcc(['vatusa3@vatusa.net', 'vatusa13@vatusa.net']);
//}
$mail->queue(new AcademyExamSubmitted($result));
$studentId = $this->notify->userWantsNotification($student, "academyExamResult",
"discord") ? $student->discord_id : 0;
$instructorId = $this->notify->userWantsNotification($instructor, "academyExamResult",
"discord") ? $instructor->discord_id : 0;
$taId = $ta && $this->notify->userWantsNotification($instructor, "academyExamResult",
"discord") ? $ta->discord_id : 0;
if ($studentId || $instructorId) {
$this->notify->sendNotification("academyExamResult", "dm",
array_merge($result, compact('studentId', 'instructorId')));
}
if ($taId) {
$this->notify->sendNotification("academyExamResult", "dm",
array_merge($result, ['instructorId' => $taId]));
}
if ($channel = $this->notify->getFacilityNotificationChannel(Facility::find($student->facility),
"academyExamResult")) {
$this->notify->sendNotification("academyExamResult", "channel", $result,
$student->facilityObj->discord_guild, $channel);
}

if ($passed) {
$assignment->delete();
Expand Down Expand Up @@ -153,13 +190,23 @@ public function handle()

$result = compact('testName', 'studentName', 'attemptNum', 'grade',
'passed', 'passingGrade', 'attemptId');
$mail = Mail::to($student);
//if ($attemptNum == 3 && !$passed) {
$mail->bcc(['vatusa3@vatusa.net', 'vatusa13@vatusa.net']);
//}
$mail = Mail::bcc(['vatusa3@vatusa.net', 'vatusa13@vatusa.net']);
if ($hasUser = $this->notify->userWantsNotification($student, "academyExamResult", "email")) {
$mail->to($student);
}
$mail->queue(new AcademyExamSubmitted($result));

if($passed) {
$studentId = $this->notify->userWantsNotification($student, "academyExamResult",
"discord") ? $student->discord_id : 0;
if ($studentId) {
$this->notify->sendNotification("academyExamResult", "dm",
array_merge($result, compact('studentId')));
}
if ($channel = $this->notify->getFacilityNotificationChannel(Facility::find($student->facility),
"academyExamResult")) {
$this->notify->sendNotification("academyExamResult", "channel", $result,
$student->facilityObj->discord_guild, $channel);
}
if ($passed) {
$student->flag_needbasic = 0;
$student->save();
}
Expand Down
8 changes: 4 additions & 4 deletions app/Exam.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ class Exam extends Model
protected $table = "exams";

public function questions() {
return $this->hasMany('App\ExamQuestions', 'exam_id');
return $this->hasMany(ExamQuestions::class, 'exam_id');
}

public function facility() {
return $this->hasOne('App\Facility', 'id', 'facility_id');
return $this->hasOne(Facility::class, 'id', 'facility_id');
}

public function results() {
return $this->hasMany('App\ExamResults', 'exam_id', 'id');
return $this->hasMany(ExamResults::class, 'exam_id', 'id');
}

public function CBT() {
return $this->hasOne("App\TrainingBlock", "id", "cbt_required");
return $this->hasOne(TrainingBlock::class, 'id', 'cbt_required');
}

public function CBTComplete(User $user = null) {
Expand Down
2 changes: 1 addition & 1 deletion app/Facility.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function datm()

public function ta()
{
return $this->hasOne('App\User', 'cid', 'ta')->first();
return $this->hasOne(User::class, 'cid', 'ta')->first();
}

public function ec()
Expand Down
Loading