Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
edalzell committed Aug 13, 2021
0 parents commit b1f63cf
Show file tree
Hide file tree
Showing 14 changed files with 563 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/mix-manifest.json
/node_modules
/yarn.lock
/vendor
/.phpunit.result.cache
/composer.lock
/dist
42 changes: 42 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "transformstudios/uptime",
"autoload": {
"psr-4": {
"TransformStudios\\Uptime\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"TransformStudios\\Uptime\\Tests\\": "tests"
}
},
"require": {
"php": "^8.0",
"laravel/framework": "^8.53",
"statamic/cms": "^3.1"
},
"require-dev": {
"cweagans/composer-patches": "^1.7",
"mockery/mockery": "^1.3.1",
"nunomaduro/collision": "^4.1 || ^5.0",
"phpunit/phpunit": "^8.0 || ^9.0",
"orchestra/testbench": "^5.0 || ^6.0",
"jasonmccreary/laravel-test-assertions": "^1.0"
},
"extra": {
"statamic": {
"name": "Uptime",
"description": "Uptime addon"
},
"laravel": {
"providers": [
"TransformStudios\\Uptime\\ServiceProvider"
]
},
"patches": {
"statamic/cms": {
"Add getKey to User": "patches/4122.diff"
}
}
}
}
5 changes: 5 additions & 0 deletions config/uptime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
'api_key' => env('UPTIME_API_KEY'),
];
37 changes: 37 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
printerClass="NunoMaduro\Collision\Adapters\Phpunit\Printer"
stopOnFailure="false"
verbose="true">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">tests/Unit/</directory>
</testsuite>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_KEY" value="base64:xRIcDp1ReW8Y8rd9V9D7hOVV4TI7ThCF3FKxRg01Rm8="/>
<env name="APP_URL" value="http://uptime.test"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="MAIL_DRIVER" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
</php>
</phpunit>
16 changes: 16 additions & 0 deletions routes/actions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

use App\Http\Middleware\VerifyCsrfToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use TransformStudios\Uptime\Http\Controllers\WebhookController;

Route::post('webhook', [WebhookController::class, '__invoke'])
->withoutMiddleware(VerifyCsrfToken::class)
->name('uptime.webhook');

Route::get('test', function(Request $request) {
// abort(500);
return response()->noContent();
})
->name('uptime.test');
132 changes: 132 additions & 0 deletions src/Http/Controllers/WebhookController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace TransformStudios\Uptime\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Statamic\Facades\Entry;
use Statamic\Facades\User;
use Statamic\Support\Arr;
use TransformStudios\Uptime\Notifications\AlertCleared;

class WebhookController extends Controller
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

/*
"data" => [
"service" => [
"id" => 937828
"name" => "Erin Test"
"device_id" => 537094
"monitoring_service_type" => "HTTP"
"is_paused" => false
"msp_address" => "https://transform.share.silentz.dev/!/uptime/test"
"msp_version" => 2
"msp_interval" => 5
"msp_sensitivity" => 2
"msp_num_retries" => 2
"msp_url_scheme" => "https"
"msp_url_path" => "/!/uptime/test"
"msp_port" => null
"msp_protocol" => null
"msp_username" => null
"msp_proxy" => null
"msp_dns_server" => null
"msp_dns_record_type" => null
"msp_send_string" => null
"msp_expect_string" => null
"msp_expect_string_type" => "STRING"
"msp_encryption" => "SSL_TLS"
"msp_threshold" => 40
"msp_notes" => null
"msp_include_in_global_metrics" => true
"msp_use_ip_version" => null
"msp_uptime_sla" => "0.9900"
"msp_response_time_sla" => "2.200"
"monitoring_service_type_display" => "HTTP(S)"
"display_name" => "Erin Test"
"short_name" => "Erin Test"
"tags" => [
"Erin"
]
]
"account" => [
"id" => 151373
"name" => "Transform Studios"
"brand" => "uptime"
"timezone" => "America/Los_Angeles"
"site_url" => "https://uptime.com"
]
"integration" => [
"id" => 4310
"name" => "Erin Test"
"module" => "webhook"
"module_verbose_name" => "Custom Postback URL (Webhook)"
"is_enabled" => true
"is_errored" => false
"is_test_supported" => true
"postback_url" => "https://transform.share.silentz.dev/!/uptime/webhook"
"headers" => null
"use_legacy_payload" => false
]
"date" => "2021-08-06T19:16:47.928Z"
"alert" => [
"id" => 112738275
"created_at" => "2021-08-06T19:16:47.928Z"
"state" => "OK"
"output" => """
HTTP OK: HTTP/1.1 204 No Content - 1178 bytes in 0.881 second response time
time=0.881087s;;;0.000000;40.000000 size=1178B;;;0
"""
"short_output" => "HTTP OK: HTTP/1.1 204 No Content - 1178 bytes in 0.881 second response time"
"is_up" => true
]
"global_alert_state" => array:6 [▶]
"device" => array:5 [▶]
"downtime" => array:4 [▶]
"links" => []
]
"event" => "alert_cleared"
*/
public function __invoke(Request $request)
{
$method = 'handle' . Str::studly(str_replace('.', '_', $request->input('event')));

if (method_exists($this, $method)) {
return $this->{$method}($request->input('data'));
}

return response()->noContent();
}

private function handleAlertCleared(array $payload)
{
return $this->handleAlert(AlertCleared::class, $payload);
}

private function handleAlert($notificationClass, $payload)
{
if (! $tag = Arr::get($payload, 'service.tags.0')) {
return response()->noContent();
}

if (! $site = Entry::query()->where('collection', 'sites')->where('uptime_tag', $tag)->first()) {
return response()->noContent();
}

if (! $users = collect($site->augmentedValue('users'))->map(fn (string $id) => User::find($id))) {
return response()->noContent();
}

Notification::send($users, new $notificationClass($payload));

return response('Webhook handled');
}
}
51 changes: 51 additions & 0 deletions src/Notifications/AlertCleared.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace TransformStudios\Uptime\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use TransformStudios\Front\Notifications\Channel\Message;

class AlertCleared extends Notification
{
use Queueable;

public function __construct(private $alert = [])
{
}

/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['front'];
}

/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toFront($notifiable)
{
return new Message($notifiable);
}

/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return $this->alert;
}
}
17 changes: 17 additions & 0 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace TransformStudios\Uptime;

use Statamic\Providers\AddonServiceProvider;
use TransformStudios\Uptime\Fieldtypes\Tag;

class ServiceProvider extends AddonServiceProvider
{
protected $routes = [
'actions' => __DIR__.'/../routes/actions.php',
];

protected $fieldtypes = [
Tag::class,
];
}
27 changes: 27 additions & 0 deletions tests/ExceptionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
protected $dontReport = [
];

protected $dontFlash = [
'password',
'password_confirmation',
];

public function report(Exception $exception)
{
parent::report($exception);
}

public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
}
30 changes: 30 additions & 0 deletions tests/PreventSavingStacheItemsToDisk.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace TransformStudios\Uptime\Tests;

use Statamic\Facades\Path;
use Statamic\Facades\Stache;

trait PreventSavingStacheItemsToDisk
{
protected $fakeStacheDirectory = __DIR__ . '/__fixtures__/dev-null';

protected function preventSavingStacheItemsToDisk()
{
$this->fakeStacheDirectory = Path::tidy($this->fakeStacheDirectory);

Stache::stores()->each(function ($store) {
$dir = Path::tidy(__DIR__ . '/__fixtures__');
$relative = str_after(str_after($store->directory(), $dir), '/');
$store->directory($this->fakeStacheDirectory . '/' . $relative);
});
}

protected function deleteFakeStacheDirectory()
{
app('files')->deleteDirectory($this->fakeStacheDirectory);

mkdir($this->fakeStacheDirectory);
touch($this->fakeStacheDirectory . '/.gitkeep');
}
}
Loading

0 comments on commit b1f63cf

Please sign in to comment.