repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Settings/AppearanceController.php
app/Http/Controllers/Settings/AppearanceController.php
<?php namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; use Inertia\Inertia; use Inertia\Response; class AppearanceController extends Controller { public function __invoke(): Response { return Inertia::render('settings/Appearance'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Controllers/Settings/DatabaseBackupController.php
app/Http/Controllers/Settings/DatabaseBackupController.php
<?php namespace App\Http\Controllers\Settings; use App\Http\Controllers\Controller; use App\Http\Requests\Settings\RestoreDatabaseRequest; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; use Inertia\Inertia; use Inertia\Response; use Symfony\Component\HttpFoundation\StreamedResponse; class DatabaseBackupController extends Controller { /** * Tables that contain essential data and should be backed up. * These are configuration and user data that cannot be regenerated. */ private const ESSENTIAL_TABLES = [ 'users', 'monitors', 'notification_channels', 'status_pages', 'status_page_monitor', 'user_monitor', 'tags', 'taggables', 'social_accounts', 'monitor_incidents', // Historical incident data is valuable ]; /** * Tables that will be excluded from backup. * These contain regenerable data (monitoring history, cache, sessions, etc.) */ private const EXCLUDED_TABLES = [ 'monitor_histories', // Can be regenerated from monitoring 'monitor_statistics', // Aggregated from histories 'monitor_uptime_dailies', // Aggregated from histories 'monitor_performance_hourly', // Aggregated from histories 'health_check_result_history_items', // System health logs 'cache', // Temporary cache data 'cache_locks', // Temporary cache locks 'sessions', // User sessions 'password_reset_tokens', // Temporary tokens ]; public function index(): Response { $databasePath = config('database.connections.sqlite.database'); $isFileBased = $databasePath !== ':memory:' && ! str_starts_with($databasePath, ':memory:'); $databaseExists = $isFileBased && file_exists($databasePath); $databaseSize = $databaseExists ? filesize($databasePath) : 0; // Calculate essential data size estimate $essentialRecordCount = 0; if ($databaseExists) { foreach (self::ESSENTIAL_TABLES as $table) { try { $essentialRecordCount += DB::table($table)->count(); } catch (\Exception) { // Table might not exist } } } return Inertia::render('settings/Database', [ 'databaseSize' => $databaseSize, 'databaseExists' => $databaseExists, 'isFileBased' => $isFileBased, 'essentialRecordCount' => $essentialRecordCount, 'essentialTables' => self::ESSENTIAL_TABLES, 'excludedTables' => self::EXCLUDED_TABLES, ]); } public function download(): StreamedResponse { $filename = 'uptime-kita-backup-'.now()->format('Y-m-d-His').'.sql'; return response()->streamDownload(function () { $this->generateSqlBackup(); }, $filename, [ 'Content-Type' => 'application/sql', ]); } private function generateSqlBackup(): void { // Output header echo "-- Uptime Kita Database Backup\n"; echo '-- Generated: '.now()->toIso8601String()."\n"; echo "-- Essential data only (excludes monitoring history and cache)\n"; echo "--\n"; echo "-- To restore: sqlite3 database.sqlite < backup.sql\n"; echo "--\n\n"; echo "PRAGMA foreign_keys = OFF;\n\n"; // Export migrations table first (important for schema version) $this->exportTable('migrations'); // Export essential tables foreach (self::ESSENTIAL_TABLES as $table) { $this->exportTable($table); } echo "PRAGMA foreign_keys = ON;\n"; } private function exportTable(string $table): void { try { $rows = DB::table($table)->get(); if ($rows->isEmpty()) { echo "-- Table '{$table}' is empty\n\n"; return; } echo "-- Table: {$table} ({$rows->count()} rows)\n"; echo "DELETE FROM \"{$table}\";\n"; foreach ($rows as $row) { $columns = array_keys((array) $row); $values = array_map(function ($value) { if ($value === null) { return 'NULL'; } if (is_bool($value)) { return $value ? '1' : '0'; } if (is_int($value) || is_float($value)) { return $value; } return "'".str_replace("'", "''", (string) $value)."'"; }, array_values((array) $row)); $columnList = '"'.implode('", "', $columns).'"'; $valueList = implode(', ', $values); echo "INSERT INTO \"{$table}\" ({$columnList}) VALUES ({$valueList});\n"; } echo "\n"; } catch (\Exception $e) { echo "-- Error exporting table '{$table}': {$e->getMessage()}\n\n"; } } public function restore(RestoreDatabaseRequest $request): RedirectResponse { $uploadedFile = $request->file('database'); $extension = strtolower($uploadedFile->getClientOriginalExtension()); $databasePath = config('database.connections.sqlite.database'); // Create a backup of the current database before restoring $backupPath = $databasePath.'.backup-'.now()->format('Y-m-d-His'); if (file_exists($databasePath)) { copy($databasePath, $backupPath); } try { if ($extension === 'sql') { $this->restoreFromSql($uploadedFile->getRealPath(), $databasePath); } else { $this->restoreFromSqlite($uploadedFile, $databasePath); } // Clean up the backup file on success if (file_exists($backupPath)) { unlink($backupPath); } return back()->with('success', 'Database restored successfully. Please log in again.'); } catch (\Exception $e) { // Restore the backup on failure if (file_exists($backupPath)) { copy($backupPath, $databasePath); unlink($backupPath); } DB::reconnect('sqlite'); return back()->withErrors([ 'database' => 'Failed to restore database: '.$e->getMessage(), ]); } } private function restoreFromSql(string $sqlFilePath, string $databasePath): void { // Read and execute the SQL file $sql = file_get_contents($sqlFilePath); if ($sql === false) { throw new \RuntimeException('Failed to read SQL file'); } // Disable foreign keys temporarily DB::statement('PRAGMA foreign_keys = OFF'); // Split SQL into statements and execute each $statements = $this->parseSqlStatements($sql); foreach ($statements as $statement) { $statement = trim($statement); if (! empty($statement) && ! str_starts_with($statement, '--')) { DB::unprepared($statement); } } // Re-enable foreign keys DB::statement('PRAGMA foreign_keys = ON'); // Reconnect to ensure changes are applied DB::reconnect('sqlite'); DB::connection('sqlite')->getPdo(); } private function parseSqlStatements(string $sql): array { $statements = []; $currentStatement = ''; $lines = explode("\n", $sql); foreach ($lines as $line) { $trimmedLine = trim($line); // Skip empty lines and comments if (empty($trimmedLine) || str_starts_with($trimmedLine, '--')) { continue; } $currentStatement .= $line."\n"; // Check if statement ends with semicolon if (str_ends_with($trimmedLine, ';')) { $statements[] = $currentStatement; $currentStatement = ''; } } // Add any remaining statement if (! empty(trim($currentStatement))) { $statements[] = $currentStatement; } return $statements; } private function restoreFromSqlite(\Illuminate\Http\UploadedFile $uploadedFile, string $databasePath): void { // Close database connections before replacing DB::disconnect('sqlite'); // Move the uploaded file to replace the database $uploadedFile->move(dirname($databasePath), basename($databasePath)); // Reconnect and verify the database is valid DB::reconnect('sqlite'); DB::connection('sqlite')->getPdo(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Middleware/HandleInertiaRequests.php
app/Http/Middleware/HandleInertiaRequests.php
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Inspiring; use Illuminate\Http\Request; use Inertia\Middleware; use Tighten\Ziggy\Ziggy; class HandleInertiaRequests extends Middleware { /** * The root template that's loaded on the first page visit. * * @see https://inertiajs.com/server-side-setup#root-template * * @var string */ protected $rootView = 'app'; /** * Determines the current asset version. * * @see https://inertiajs.com/asset-versioning */ public function version(Request $request): ?string { return parent::version($request); } /** * Define the props that are shared by default. * * @see https://inertiajs.com/shared-data * * @return array<string, mixed> */ public function share(Request $request): array { [$message, $author] = str(Inspiring::quotes()->random())->explode('-'); return [ ...parent::share($request), 'name' => config('app.name'), 'quote' => ['message' => trim($message), 'author' => trim($author)], 'auth' => [ 'user' => $request->user(), ], 'ziggy' => [ ...(new Ziggy)->toArray(), 'location' => $request->url(), ], 'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true', 'flash' => $request->session()->get('flash'), // Add last update date for UI 'lastUpdate' => config('app.last_update'), ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Middleware/CustomDomainMiddleware.php
app/Http/Middleware/CustomDomainMiddleware.php
<?php namespace App\Http\Middleware; use App\Models\StatusPage; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class CustomDomainMiddleware { /** * Handle an incoming request. */ public function handle(Request $request, Closure $next): Response { $host = $request->getHost(); $appDomain = parse_url(config('app.url'), PHP_URL_HOST); // Skip if it's the main app domain if ($host === $appDomain || $host === 'localhost' || $host === '127.0.0.1') { return $next($request); } // Check if this is a custom domain for a status page $statusPage = StatusPage::where('custom_domain', $host) ->where('custom_domain_verified', true) ->first(); if ($statusPage) { // Force HTTPS if enabled if ($statusPage->force_https && ! $request->secure()) { return redirect()->secure($request->getRequestUri()); } // Store the status page in the request for later use $request->attributes->set('custom_domain_status_page', $statusPage); // Override the route to point to the status page $request->merge(['path' => $statusPage->path]); $request->server->set('REQUEST_URI', '/status/'.$statusPage->path); } return $next($request); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Middleware/HandleAppearance.php
app/Http/Middleware/HandleAppearance.php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\View; use Symfony\Component\HttpFoundation\Response; class HandleAppearance { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { View::share('appearance', $request->cookie('appearance') ?? 'system'); return $next($request); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Resources/MonitorHistoryResource.php
app/Http/Resources/MonitorHistoryResource.php
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class MonitorHistoryResource extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'monitor_id' => $this->monitor_id, 'uptime_status' => $this->uptime_status, 'message' => $this->message, 'response_time' => $this->response_time, 'status_code' => $this->status_code, 'checked_at' => $this->checked_at, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Resources/MonitorResource.php
app/Http/Resources/MonitorResource.php
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class MonitorResource extends JsonResource { /** * Transform the resource into an array. * * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->raw_url, 'url' => $this->raw_url, 'host' => $this->host, 'uptime_status' => $this->uptime_status, 'uptime_check_enabled' => (bool) $this->uptime_check_enabled, 'favicon' => $this->favicon, 'last_check_date' => $this->uptime_last_check_date, 'last_check_date_human' => $this->uptime_last_check_date ? $this->uptime_last_check_date->diffForHumans() : null, 'certificate_check_enabled' => (bool) $this->certificate_check_enabled, 'certificate_status' => $this->certificate_status, 'certificate_expiration_date' => $this->certificate_expiration_date, 'down_for_events_count' => $this->getDownEventsCount(), 'uptime_check_interval' => $this->uptime_check_interval_in_minutes, 'is_subscribed' => $this->is_subscribed, 'is_pinned' => $this->is_pinned, 'is_public' => $this->is_public, 'page_views_count' => $this->page_views_count ?? 0, 'formatted_page_views' => $this->formatted_page_views, 'today_uptime_percentage' => $this->getTodayUptimePercentage(), 'uptime_status_last_change_date' => $this->uptime_status_last_change_date, 'uptime_check_failure_reason' => $this->uptime_check_failure_reason, 'sensitivity' => $this->sensitivity ?? 'medium', 'confirmation_delay_seconds' => $this->confirmation_delay_seconds, 'confirmation_retries' => $this->confirmation_retries, 'transient_failures_count' => $this->transient_failures_count ?? 0, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'tags' => $this->when($this->relationLoaded('tags'), function () { return $this->tags->map(function ($tag) { return [ 'id' => $tag->id, 'name' => $tag->name, 'type' => $tag->type, 'color' => $tag->color ?? null, ]; }); }), 'histories' => MonitorHistoryResource::collection($this->whenLoaded('histories')), 'latest_history' => $this->whenLoaded('latestHistory', function () { return $this->latestHistory ? new MonitorHistoryResource($this->latestHistory) : null; }), 'uptimes_daily' => $this->whenLoaded('uptimesDaily', function () { return $this->uptimesDaily->map(function ($uptime) { return [ 'date' => $uptime->date->toDateString(), 'uptime_percentage' => $uptime->uptime_percentage, ]; }); }), 'statistics' => $this->whenLoaded('statistics', function () { return [ 'uptime_24h' => $this->statistics->uptime_24h ?? null, 'uptime_7d' => $this->statistics->uptime_7d ?? null, 'uptime_30d' => $this->statistics->uptime_30d ?? null, 'avg_response_time_24h' => $this->statistics->avg_response_time_24h ?? null, 'incidents_24h' => $this->statistics->incidents_24h ?? 0, 'incidents_7d' => $this->statistics->incidents_7d ?? 0, ]; }), ]; } /** * Get the count of down events from histories. */ protected function getDownEventsCount(): int { // If histories are loaded, count from the collection if ($this->relationLoaded('histories')) { return $this->histories->where('uptime_status', 'down')->count(); } // Otherwise, don't return anything return 0; } /** * Get today's uptime percentage safely. */ protected function getTodayUptimePercentage(): float { // If uptimeDaily is loaded, use it if ($this->relationLoaded('uptimeDaily')) { return $this->uptimeDaily?->uptime_percentage ?? 0; } // Otherwise, return 0 to avoid lazy loading return 0; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Resources/MonitorCollection.php
app/Http/Resources/MonitorCollection.php
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\ResourceCollection; class MonitorCollection extends ResourceCollection { /** * Transform the resource collection into an array. * * @return array<int|string, mixed> */ public function toArray(Request $request): array { return [ 'data' => MonitorResource::collection($this->collection), 'links' => [ 'self' => url()->current(), 'first' => $this->url(1), 'last' => $this->url($this->lastPage()), 'prev' => $this->previousPageUrl(), 'next' => $this->nextPageUrl(), ], 'meta' => [ 'current_page' => $this->currentPage(), 'from' => $this->firstItem(), 'last_page' => $this->lastPage(), 'path' => url()->current(), 'per_page' => $this->perPage(), 'to' => $this->lastItem(), 'total' => $this->total(), ], ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Resources/StatusPageCollection.php
app/Http/Resources/StatusPageCollection.php
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\ResourceCollection; class StatusPageCollection extends ResourceCollection { /** * The resource that this resource collects. * * @var string */ public $collects = StatusPageResource::class; /** * Transform the resource collection into an array. * * @return array<int|string, mixed> */ public function toArray(Request $request): array { return parent::toArray($request); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Http/Resources/StatusPageResource.php
app/Http/Resources/StatusPageResource.php
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class StatusPageResource extends JsonResource { /** * The "data" wrapper that should be applied. * * @var string|null */ public static $wrap = null; // <--- TAMBAHKAN BARIS INI /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array<string, mixed> */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'description' => $this->description, 'icon' => $this->icon, 'path' => $this->path, 'custom_domain' => $this->custom_domain, 'custom_domain_verified' => $this->custom_domain_verified, 'force_https' => $this->force_https, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'monitors' => MonitorResource::collection($this->whenLoaded('monitors')), ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Listeners/SendCustomMonitorNotification.php
app/Listeners/SendCustomMonitorNotification.php
<?php namespace App\Listeners; use App\Notifications\MonitorStatusChanged; use Illuminate\Support\Facades\Log; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; class SendCustomMonitorNotification { /** * Create the event listener. */ public function __construct() { // } /** * Handle the event. */ public function handle(object $event): void { $monitor = $event->monitor; Log::info('SendCustomMonitorNotification: Event received', [ 'event_type' => get_class($event), 'monitor_id' => $monitor->id, 'monitor_url' => $monitor->url, ]); // Skip notification if monitor is in maintenance window if ($monitor->isInMaintenance()) { Log::info('SendCustomMonitorNotification: Skipping notification - monitor is in maintenance window', [ 'monitor_id' => $monitor->id, 'monitor_url' => (string) $monitor->url, 'maintenance_ends_at' => $monitor->maintenance_ends_at, ]); return; } // Get all users associated with this monitor $users = $monitor->users()->where('user_monitor.is_active', true)->get(); Log::info('SendCustomMonitorNotification: Found users for monitor', [ 'monitor_id' => $monitor->id, 'user_count' => $users->count(), 'user_ids' => $users->pluck('id')->toArray(), ]); if ($users->isEmpty()) { Log::warning('SendCustomMonitorNotification: No active users found for monitor', [ 'monitor_id' => $monitor->id, 'monitor_url' => $monitor->url, ]); return; } $status = $event instanceof UptimeCheckFailed ? 'DOWN' : 'UP'; Log::info('SendCustomMonitorNotification: Sending notifications', [ 'monitor_id' => $monitor->id, 'status' => $status, 'user_count' => $users->count(), ]); // Send notification to all active users of this monitor foreach ($users as $user) { try { $user->notify(new MonitorStatusChanged([ 'id' => $monitor->id, 'url' => (string) $monitor->url, 'status' => $status, 'message' => "Website {$monitor->url} is {$status}", 'is_public' => $monitor->is_public, ])); Log::info('SendCustomMonitorNotification: Notification sent successfully', [ 'monitor_id' => $monitor->id, 'user_id' => $user->id, 'status' => $status, ]); } catch (\Exception $e) { Log::error('SendCustomMonitorNotification: Failed to send notification', [ 'monitor_id' => $monitor->id, 'user_id' => $user->id, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); } } Log::info('SendCustomMonitorNotification: Completed processing', [ 'monitor_id' => $monitor->id, 'status' => $status, 'total_users_processed' => $users->count(), ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Listeners/DispatchConfirmationCheck.php
app/Listeners/DispatchConfirmationCheck.php
<?php namespace App\Listeners; use App\Jobs\ConfirmMonitorDowntimeJob; use App\Services\SmartRetryService; use Illuminate\Support\Facades\Log; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; class DispatchConfirmationCheck { /** * Handle the event. * * This listener intercepts UptimeCheckFailed events and dispatches * a confirmation check job with a delay to reduce false positives. * * The confirmation check will verify if the monitor is truly down * before allowing notifications to be sent. */ public function handle(UptimeCheckFailed $event): bool { $monitor = $event->monitor; // Check if confirmation check is enabled if (! config('uptime-monitor.confirmation_check.enabled', true)) { Log::debug('DispatchConfirmationCheck: Confirmation check disabled, proceeding with original event', [ 'monitor_id' => $monitor->id, ]); return true; // Let other listeners handle the event } $failureCount = $monitor->uptime_check_times_failed_in_a_row; $threshold = config('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures', 3); // Only dispatch confirmation check on first failure of a new incident // If already at threshold, the event was already confirmed if ($failureCount === 1) { // Get per-monitor delay or use sensitivity preset $delay = $this->getConfirmationDelay($monitor); Log::info('DispatchConfirmationCheck: Dispatching confirmation check', [ 'monitor_id' => $monitor->id, 'url' => (string) $monitor->url, 'failure_count' => $failureCount, 'delay_seconds' => $delay, 'sensitivity' => $monitor->sensitivity ?? 'medium', ]); ConfirmMonitorDowntimeJob::dispatch( $monitor->id, $monitor->uptime_check_failure_reason ?? 'Unknown failure', $failureCount )->delay(now()->addSeconds($delay)); // Stop event propagation for first failure // We'll fire a new event from the job if confirmed return false; } Log::debug('DispatchConfirmationCheck: Failure count > 1, letting event propagate', [ 'monitor_id' => $monitor->id, 'failure_count' => $failureCount, 'threshold' => $threshold, ]); // Let other listeners handle the event for subsequent failures return true; } /** * Get confirmation delay for a monitor. * * Priority: * 1. Per-monitor custom delay (confirmation_delay_seconds) * 2. Sensitivity preset delay * 3. Global config default */ protected function getConfirmationDelay($monitor): int { // Check for custom per-monitor delay if ($monitor->confirmation_delay_seconds !== null) { return $monitor->confirmation_delay_seconds; } // Use sensitivity preset $sensitivity = $monitor->sensitivity ?? 'medium'; $preset = SmartRetryService::getPreset($sensitivity); return $preset['confirmation_delay'] ?? config('uptime-monitor.confirmation_check.delay_seconds', 30); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Listeners/StoreMonitorCheckData.php
app/Listeners/StoreMonitorCheckData.php
<?php namespace App\Listeners; use App\Models\MonitorHistory; use App\Models\MonitorIncident; use App\Services\MonitorPerformanceService; use Illuminate\Support\Facades\Log; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; use Spatie\UptimeMonitor\Events\UptimeCheckRecovered; use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded; class StoreMonitorCheckData { protected MonitorPerformanceService $performanceService; public function __construct(MonitorPerformanceService $performanceService) { $this->performanceService = $performanceService; } /** * Handle the event. */ public function handle(object $event): void { $monitor = $event->monitor; // Extract response time and status code from the event or monitor $responseTime = $this->extractResponseTime($event); $statusCode = $this->extractStatusCode($event); $status = $this->determineStatus($event); $failureReason = $event instanceof UptimeCheckFailed ? $event->monitor->uptime_check_failure_reason : null; // Store in monitor_histories with new fields MonitorHistory::create([ 'monitor_id' => $monitor->id, 'uptime_status' => $status, 'response_time' => $responseTime, 'status_code' => $statusCode, 'checked_at' => now(), 'message' => $failureReason, ]); // Update hourly performance metrics $this->performanceService->updateHourlyMetrics($monitor->id, $responseTime, $status === 'up'); // Handle incidents $this->handleIncident($monitor, $event, $responseTime, $statusCode); Log::info('Monitor check data stored', [ 'monitor_id' => $monitor->id, 'status' => $status, 'response_time' => $responseTime, 'status_code' => $statusCode, ]); } /** * Extract response time from the event. */ protected function extractResponseTime($event): ?int { // The Spatie package doesn't provide response time directly // We'll need to measure it in a custom check command or estimate it // For now, we'll generate a realistic value based on status if ($event instanceof UptimeCheckSucceeded) { return rand(100, 500); // Successful checks are typically faster } elseif ($event instanceof UptimeCheckRecovered) { return rand(200, 800); } else { return rand(1000, 30000); // Failed checks might timeout } } /** * Extract status code from the event. */ protected function extractStatusCode($event): ?int { if ($event instanceof UptimeCheckSucceeded || $event instanceof UptimeCheckRecovered) { return 200; } elseif ($event instanceof UptimeCheckFailed) { // Parse failure reason for status code if available $reason = $event->monitor->uptime_check_failure_reason ?? ''; if (preg_match('/(\d{3})/', $reason, $matches)) { return (int) $matches[1]; } return 0; // Connection failed } return null; } /** * Determine the status from the event type. */ protected function determineStatus($event): string { if ($event instanceof UptimeCheckSucceeded || $event instanceof UptimeCheckRecovered) { return 'up'; } elseif ($event instanceof UptimeCheckFailed) { return 'down'; } return 'not yet checked'; } /** * Handle incident tracking. */ protected function handleIncident($monitor, $event, ?int $responseTime, ?int $statusCode): void { if ($event instanceof UptimeCheckFailed) { // Check if there's an ongoing incident $ongoingIncident = MonitorIncident::where('monitor_id', $monitor->id) ->whereNull('ended_at') ->first(); if (! $ongoingIncident) { // Create new incident MonitorIncident::create([ 'monitor_id' => $monitor->id, 'type' => 'down', 'started_at' => now(), 'reason' => $monitor->uptime_check_failure_reason, 'response_time' => $responseTime, 'status_code' => $statusCode, ]); } } elseif ($event instanceof UptimeCheckRecovered) { // End any ongoing incident $ongoingIncident = MonitorIncident::where('monitor_id', $monitor->id) ->whereNull('ended_at') ->first(); if ($ongoingIncident) { $ongoingIncident->endIncident(); } } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Listeners/BroadcastMonitorStatusChange.php
app/Listeners/BroadcastMonitorStatusChange.php
<?php namespace App\Listeners; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; use Spatie\UptimeMonitor\Events\UptimeCheckRecovered; class BroadcastMonitorStatusChange { /** * Handle the event. * * Broadcasts monitor status changes to the cache for SSE consumers. * Only broadcasts for public monitors. */ public function handle(object $event): void { $monitor = $event->monitor; // Only broadcast for public monitors if (! $monitor->is_public) { return; } $oldStatus = $event instanceof UptimeCheckRecovered ? 'down' : 'up'; $newStatus = $event instanceof UptimeCheckFailed ? 'down' : 'up'; // Skip if status hasn't actually changed if ($oldStatus === $newStatus) { return; } $statusChange = [ 'id' => uniqid('msc_'), 'monitor_id' => $monitor->id, 'monitor_name' => $monitor->display_name ?? $monitor->url->getHost(), 'monitor_url' => (string) $monitor->url, 'old_status' => $oldStatus, 'new_status' => $newStatus, 'changed_at' => now()->toIso8601String(), 'favicon' => $monitor->favicon, 'status_page_ids' => $monitor->statusPages()->pluck('status_pages.id')->toArray(), ]; Log::info('BroadcastMonitorStatusChange: Broadcasting status change', [ 'monitor_id' => $monitor->id, 'old_status' => $oldStatus, 'new_status' => $newStatus, ]); // Store in cache with TTL of 5 minutes $cacheKey = 'monitor_status_changes'; $changes = Cache::get($cacheKey, []); // Add new change $changes[] = $statusChange; // Keep only changes within last 5 minutes and max 100 entries $fiveMinutesAgo = now()->subMinutes(5); $changes = collect($changes) ->filter(fn ($c) => \Carbon\Carbon::parse($c['changed_at'])->isAfter($fiveMinutesAgo)) ->take(100) ->values() ->toArray(); Cache::put($cacheKey, $changes, now()->addMinutes(5)); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/SmartRetryAttempt.php
app/Services/SmartRetryAttempt.php
<?php namespace App\Services; class SmartRetryAttempt { public const TYPE_HTTP = 'http'; public const TYPE_TCP = 'tcp'; public const ERROR_TIMEOUT = 'timeout'; public const ERROR_CONNECTION_REFUSED = 'connection_refused'; public const ERROR_DNS = 'dns'; public const ERROR_SSL = 'ssl'; public const ERROR_HTTP_STATUS = 'http_status'; public const ERROR_STRING_NOT_FOUND = 'string_not_found'; public const ERROR_UNKNOWN = 'unknown'; public function __construct( public bool $success, public string $type = self::TYPE_HTTP, public ?string $method = null, public ?int $statusCode = null, public ?float $responseTime = null, public ?string $errorType = null, public ?string $errorMessage = null, public int $attemptNumber = 1, ) {} public function isSuccess(): bool { return $this->success; } public function isTimeout(): bool { return $this->errorType === self::ERROR_TIMEOUT; } public function isConnectionRefused(): bool { return $this->errorType === self::ERROR_CONNECTION_REFUSED; } public function isDnsError(): bool { return $this->errorType === self::ERROR_DNS; } public function isSslError(): bool { return $this->errorType === self::ERROR_SSL; } public function isHttpStatusError(): bool { return $this->errorType === self::ERROR_HTTP_STATUS; } public function toArray(): array { return [ 'success' => $this->success, 'type' => $this->type, 'method' => $this->method, 'status_code' => $this->statusCode, 'response_time' => $this->responseTime, 'error_type' => $this->errorType, 'error_message' => $this->errorMessage, 'attempt_number' => $this->attemptNumber, ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/EmailRateLimitService.php
app/Services/EmailRateLimitService.php
<?php namespace App\Services; use App\Models\User; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class EmailRateLimitService { private const DAILY_EMAIL_LIMIT = 10; /** * Check if the user can send an email notification */ public function canSendEmail(User $user, string $notificationType): bool { $today = Carbon::today()->toDateString(); $count = DB::table('email_notification_logs') ->where('user_id', $user->id) ->where('sent_date', $today) ->count(); if ($count >= self::DAILY_EMAIL_LIMIT) { Log::warning('User exceeded daily email limit', [ 'user_id' => $user->id, 'email' => $user->email, 'current_count' => $count, 'limit' => self::DAILY_EMAIL_LIMIT, 'notification_type' => $notificationType, ]); return false; } return true; } /** * Log a sent email notification */ public function logEmailSent(User $user, string $notificationType, array $notificationData = []): void { DB::table('email_notification_logs')->insert([ 'user_id' => $user->id, 'email' => $user->email, 'notification_type' => $notificationType, 'notification_data' => json_encode($notificationData), 'sent_date' => Carbon::today()->toDateString(), 'created_at' => now(), 'updated_at' => now(), ]); Log::info('Email notification logged', [ 'user_id' => $user->id, 'email' => $user->email, 'notification_type' => $notificationType, ]); } /** * Get the remaining email count for today */ public function getRemainingEmailCount(User $user): int { $today = Carbon::today()->toDateString(); $count = DB::table('email_notification_logs') ->where('user_id', $user->id) ->where('sent_date', $today) ->count(); return max(0, self::DAILY_EMAIL_LIMIT - $count); } /** * Get today's email count for a user */ public function getTodayEmailCount(User $user): int { $today = Carbon::today()->toDateString(); return DB::table('email_notification_logs') ->where('user_id', $user->id) ->where('sent_date', $today) ->count(); } /** * Get the daily email limit */ public function getDailyLimit(): int { return self::DAILY_EMAIL_LIMIT; } /** * Check if user is approaching the limit (e.g., 80% of limit) */ public function isApproachingLimit(User $user): bool { $currentCount = $this->getTodayEmailCount($user); $threshold = self::DAILY_EMAIL_LIMIT * 0.8; return $currentCount >= $threshold; } /** * Clean up old email logs (optional, for maintenance) */ public function cleanupOldLogs(int $daysToKeep = 30): int { $cutoffDate = Carbon::now()->subDays($daysToKeep)->toDateString(); return DB::table('email_notification_logs') ->where('sent_date', '<', $cutoffDate) ->delete(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/MonitorImportService.php
app/Services/MonitorImportService.php
<?php namespace App\Services; use App\Models\Monitor; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; class MonitorImportService { private array $validationRules = [ 'url' => ['required', 'url'], 'display_name' => ['nullable', 'string', 'max:255'], 'uptime_check_enabled' => ['nullable'], 'certificate_check_enabled' => ['nullable'], 'uptime_check_interval' => ['nullable', 'integer', 'min:1', 'max:60'], 'is_public' => ['nullable'], 'sensitivity' => ['nullable', 'string', 'in:low,medium,high'], 'expected_status_code' => ['nullable', 'integer', 'min:100', 'max:599'], 'tags' => ['nullable'], ]; /** * Parse uploaded file and validate rows */ public function parseFile(UploadedFile $file, string $format): array { $rows = $format === 'csv' ? $this->parseCsv($file) : $this->parseJson($file); return $this->validateRows($rows); } /** * Parse CSV file */ private function parseCsv(UploadedFile $file): array { $rows = []; $handle = fopen($file->getPathname(), 'r'); $headers = fgetcsv($handle); if (! $headers) { fclose($handle); return []; } // Normalize headers $headers = array_map(fn ($h) => strtolower(trim($h)), $headers); while (($data = fgetcsv($handle)) !== false) { if (count($data) === count($headers)) { $row = array_combine($headers, $data); $rows[] = $this->normalizeRow($row); } } fclose($handle); return $rows; } /** * Parse JSON file */ private function parseJson(UploadedFile $file): array { $content = file_get_contents($file->getPathname()); $data = json_decode($content, true); if (json_last_error() !== JSON_ERROR_NONE) { return []; } // Handle both array of monitors and {monitors: [...]} format $monitors = isset($data['monitors']) ? $data['monitors'] : $data; if (! is_array($monitors)) { return []; } return array_map(fn ($row) => $this->normalizeRow($row), $monitors); } /** * Normalize row data */ private function normalizeRow(array $row): array { // Normalize URL (enforce HTTPS) if (isset($row['url']) && ! empty($row['url'])) { $url = rtrim(filter_var($row['url'], FILTER_VALIDATE_URL) ?: $row['url'], '/'); if (str_starts_with($url, 'http://')) { $url = 'https://'.substr($url, 7); } $row['url'] = $url; } // Normalize booleans foreach (['uptime_check_enabled', 'certificate_check_enabled', 'is_public'] as $field) { if (isset($row[$field])) { $row[$field] = filter_var($row[$field], FILTER_VALIDATE_BOOLEAN); } } // Normalize tags (support comma-separated string or array) if (isset($row['tags']) && is_string($row['tags']) && ! empty($row['tags'])) { $row['tags'] = array_map('trim', explode(',', $row['tags'])); } elseif (! isset($row['tags']) || empty($row['tags'])) { $row['tags'] = []; } // Cast numeric fields if (isset($row['uptime_check_interval']) && is_numeric($row['uptime_check_interval'])) { $row['uptime_check_interval'] = (int) $row['uptime_check_interval']; } if (isset($row['expected_status_code']) && is_numeric($row['expected_status_code'])) { $row['expected_status_code'] = (int) $row['expected_status_code']; } return $row; } /** * Validate all rows and check for duplicates */ private function validateRows(array $rows): array { $result = [ 'rows' => [], 'valid_count' => 0, 'error_count' => 0, 'duplicate_count' => 0, ]; if (empty($rows)) { return $result; } // Get existing URLs for duplicate detection $existingUrls = Monitor::withoutGlobalScopes() ->pluck('url') ->map(fn ($url) => (string) $url) ->toArray(); foreach ($rows as $index => $row) { $rowNumber = $index + 1; $validator = Validator::make($row, $this->validationRules); if ($validator->fails()) { $result['rows'][] = array_merge($row, [ '_row_number' => $rowNumber, '_status' => 'error', '_errors' => $validator->errors()->all(), ]); $result['error_count']++; continue; } // Check for duplicates $url = $row['url'] ?? ''; if (in_array($url, $existingUrls)) { $existingMonitor = Monitor::withoutGlobalScopes() ->where('url', $url) ->first(); $result['rows'][] = array_merge($row, [ '_row_number' => $rowNumber, '_status' => 'duplicate', '_existing_monitor_id' => $existingMonitor?->id, '_existing_monitor_name' => $existingMonitor?->raw_url, ]); $result['duplicate_count']++; continue; } $result['rows'][] = array_merge($row, [ '_row_number' => $rowNumber, '_status' => 'valid', ]); $result['valid_count']++; } return $result; } /** * Import monitors with duplicate resolution */ public function import(array $rows, string $defaultAction, array $resolutions = []): array { $imported = 0; $updated = 0; $skipped = 0; DB::beginTransaction(); try { foreach ($rows as $row) { $status = $row['_status'] ?? 'valid'; $rowNumber = $row['_row_number'] ?? 0; // Skip error rows if ($status === 'error') { $skipped++; continue; } // Determine action for duplicates $action = $status === 'duplicate' ? ($resolutions[$rowNumber] ?? $defaultAction) : 'create'; // Clean metadata from row $monitorData = $this->cleanRowData($row); switch ($action) { case 'skip': $skipped++; break; case 'update': $this->updateMonitor($monitorData); $updated++; break; case 'create': default: $this->createMonitor($monitorData); $imported++; break; } } DB::commit(); } catch (\Exception $e) { DB::rollBack(); throw $e; } // Clear cache if (auth()->check()) { cache()->forget('monitors_list_page_1_per_page_15_user_'.auth()->id()); } return [ 'imported' => $imported, 'updated' => $updated, 'skipped' => $skipped, ]; } /** * Create a new monitor */ private function createMonitor(array $data): Monitor { $tags = $data['tags'] ?? []; unset($data['tags']); $monitor = Monitor::create([ 'url' => $data['url'], 'display_name' => $data['display_name'] ?? null, 'is_public' => $data['is_public'] ?? false, 'uptime_check_enabled' => $data['uptime_check_enabled'] ?? true, 'certificate_check_enabled' => $data['certificate_check_enabled'] ?? false, 'uptime_check_interval_in_minutes' => $data['uptime_check_interval'] ?? 5, 'sensitivity' => $data['sensitivity'] ?? 'medium', 'expected_status_code' => $data['expected_status_code'] ?? 200, ]); if (! empty($tags)) { $monitor->attachTags($tags); } return $monitor; } /** * Update an existing monitor */ private function updateMonitor(array $data): Monitor { $monitor = Monitor::withoutGlobalScopes() ->where('url', $data['url']) ->first(); if (! $monitor) { return $this->createMonitor($data); } $tags = $data['tags'] ?? null; unset($data['tags']); $updateData = []; if (isset($data['display_name'])) { $updateData['display_name'] = $data['display_name']; } if (isset($data['is_public'])) { $updateData['is_public'] = $data['is_public']; } if (isset($data['uptime_check_enabled'])) { $updateData['uptime_check_enabled'] = $data['uptime_check_enabled']; } if (isset($data['certificate_check_enabled'])) { $updateData['certificate_check_enabled'] = $data['certificate_check_enabled']; } if (isset($data['uptime_check_interval'])) { $updateData['uptime_check_interval_in_minutes'] = $data['uptime_check_interval']; } if (isset($data['sensitivity'])) { $updateData['sensitivity'] = $data['sensitivity']; } if (isset($data['expected_status_code'])) { $updateData['expected_status_code'] = $data['expected_status_code']; } if (! empty($updateData)) { $monitor->update($updateData); } if ($tags !== null && ! empty($tags)) { $monitor->syncTags($tags); } // Attach current user if not already attached if (auth()->check() && ! $monitor->users->contains(auth()->id())) { $monitor->users()->attach(auth()->id(), ['is_active' => true, 'is_pinned' => false]); } return $monitor; } /** * Remove metadata fields from row */ private function cleanRowData(array $row): array { return array_filter($row, fn ($key) => ! str_starts_with($key, '_'), ARRAY_FILTER_USE_KEY); } /** * Generate sample CSV content */ public function generateSampleCsv(): string { $headers = ['url', 'display_name', 'uptime_check_enabled', 'certificate_check_enabled', 'uptime_check_interval', 'is_public', 'sensitivity', 'expected_status_code', 'tags']; $sample = [ ['https://example.com', 'Example Website', 'true', 'true', '5', 'true', 'medium', '200', 'production,web'], ['https://api.example.com', 'Example API', 'true', 'false', '1', 'false', 'high', '200', 'api,critical'], ]; $output = implode(',', $headers)."\n"; foreach ($sample as $row) { $output .= implode(',', $row)."\n"; } return $output; } /** * Generate sample JSON content */ public function generateSampleJson(): string { $sample = [ 'monitors' => [ [ 'url' => 'https://example.com', 'display_name' => 'Example Website', 'uptime_check_enabled' => true, 'certificate_check_enabled' => true, 'uptime_check_interval' => 5, 'is_public' => true, 'sensitivity' => 'medium', 'expected_status_code' => 200, 'tags' => ['production', 'web'], ], [ 'url' => 'https://api.example.com', 'display_name' => 'Example API', 'uptime_check_enabled' => true, 'certificate_check_enabled' => false, 'uptime_check_interval' => 1, 'is_public' => false, 'sensitivity' => 'high', 'expected_status_code' => 200, 'tags' => ['api', 'critical'], ], ], ]; return json_encode($sample, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); } /** * Detect file format from extension */ public function detectFormat(UploadedFile $file): string { $extension = strtolower($file->getClientOriginalExtension()); return in_array($extension, ['json']) ? 'json' : 'csv'; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/TwitterRateLimitService.php
app/Services/TwitterRateLimitService.php
<?php namespace App\Services; use App\Models\NotificationChannel; use App\Models\User; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; class TwitterRateLimitService { private const RATE_LIMIT_PER_HOUR = 30; private const RATE_LIMIT_PER_DAY = 200; private const CACHE_TTL_HOURS = 24; public function shouldSendNotification(User $user, ?NotificationChannel $channel = null): bool { $hourlyKey = $this->getHourlyCacheKey($user, $channel); $dailyKey = $this->getDailyCacheKey($user, $channel); $hourlyCount = Cache::get($hourlyKey, 0); $dailyCount = Cache::get($dailyKey, 0); if ($hourlyCount >= self::RATE_LIMIT_PER_HOUR) { Log::warning('Twitter hourly rate limit reached', [ 'user_id' => $user->id, 'channel_id' => $channel?->id ?? 'system', 'hourly_count' => $hourlyCount, ]); return false; } if ($dailyCount >= self::RATE_LIMIT_PER_DAY) { Log::warning('Twitter daily rate limit reached', [ 'user_id' => $user->id, 'channel_id' => $channel?->id ?? 'system', 'daily_count' => $dailyCount, ]); return false; } return true; } public function trackSuccessfulNotification(User $user, ?NotificationChannel $channel = null): void { $hourlyKey = $this->getHourlyCacheKey($user, $channel); $dailyKey = $this->getDailyCacheKey($user, $channel); Cache::increment($hourlyKey); Cache::increment($dailyKey); // Set expiration if not set if (! Cache::has($hourlyKey)) { Cache::put($hourlyKey, 1, now()->addHour()); } if (! Cache::has($dailyKey)) { Cache::put($dailyKey, 1, now()->addDay()); } } public function getRemainingTweets(User $user, ?NotificationChannel $channel = null): array { $hourlyKey = $this->getHourlyCacheKey($user, $channel); $dailyKey = $this->getDailyCacheKey($user, $channel); $hourlyCount = Cache::get($hourlyKey, 0); $dailyCount = Cache::get($dailyKey, 0); return [ 'hourly_remaining' => max(0, self::RATE_LIMIT_PER_HOUR - $hourlyCount), 'daily_remaining' => max(0, self::RATE_LIMIT_PER_DAY - $dailyCount), ]; } private function getHourlyCacheKey(User $user, ?NotificationChannel $channel = null): string { $channelId = $channel?->id ?? 'system'; return sprintf('twitter_rate_limit:hourly:%d:%s', $user->id, $channelId); } private function getDailyCacheKey(User $user, ?NotificationChannel $channel = null): string { $channelId = $channel?->id ?? 'system'; return sprintf('twitter_rate_limit:daily:%d:%s', $user->id, $channelId); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/TelegramRateLimitService.php
app/Services/TelegramRateLimitService.php
<?php namespace App\Services; use App\Models\NotificationChannel; use App\Models\User; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; class TelegramRateLimitService { private const MAX_MESSAGES_PER_MINUTE = 20; private const MAX_MESSAGES_PER_HOUR = 100; private const CACHE_TTL = 120; // 2 minutes private const BACKOFF_MULTIPLIER = 2; private const MAX_BACKOFF_MINUTES = 60; /** * Check if Telegram notification should be sent */ public function shouldSendNotification(User $user, NotificationChannel $telegramChannel): bool { if ($telegramChannel->type !== 'telegram') { throw new \InvalidArgumentException('NotificationChannel must be of type telegram'); } $rateLimitKey = $this->getRateLimitKey($user, $telegramChannel); $rateLimitData = $this->getRateLimitData($rateLimitKey); // Check if we're in a backoff period if ($this->isInBackoffPeriod($rateLimitData)) { Log::info('Telegram notification blocked due to backoff period', [ 'user_id' => $user->id, 'telegram_destination' => $telegramChannel->destination, 'backoff_until' => $rateLimitData['backoff_until'] ?? null, ]); return false; } // Check minute rate limit if (! $this->checkMinuteRateLimit($rateLimitData)) { Log::info('Telegram notification blocked due to minute rate limit', [ 'user_id' => $user->id, 'telegram_destination' => $telegramChannel->destination, 'minute_count' => $rateLimitData['minute_count'] ?? 0, ]); return false; } // Check hour rate limit if (! $this->checkHourRateLimit($rateLimitData)) { Log::info('Telegram notification blocked due to hour rate limit', [ 'user_id' => $user->id, 'telegram_destination' => $telegramChannel->destination, 'hour_count' => $rateLimitData['hour_count'] ?? 0, ]); return false; } return true; } /** * Track a successful notification */ public function trackSuccessfulNotification(User $user, NotificationChannel $telegramChannel): void { $rateLimitKey = $this->getRateLimitKey($user, $telegramChannel); $rateLimitData = $this->getRateLimitData($rateLimitKey); $currentTime = now()->timestamp; // Update minute counter $rateLimitData = $this->updateMinuteCounter($rateLimitData, $currentTime); // Update hour counter $rateLimitData = $this->updateHourCounter($rateLimitData, $currentTime); // Reset backoff on successful notification unset($rateLimitData['backoff_until']); unset($rateLimitData['backoff_count']); $this->storeRateLimitData($rateLimitKey, $rateLimitData); Log::info('Telegram notification tracked successfully', [ 'user_id' => $user->id, 'telegram_destination' => $telegramChannel->destination, 'minute_count' => $rateLimitData['minute_count'], 'hour_count' => $rateLimitData['hour_count'], ]); } /** * Track a failed notification (429 error) */ public function trackFailedNotification(User $user, NotificationChannel $telegramChannel): void { $rateLimitKey = $this->getRateLimitKey($user, $telegramChannel); $rateLimitData = $this->getRateLimitData($rateLimitKey); $currentTime = now()->timestamp; $currentTime = now()->timestamp; $backoffCount = ($rateLimitData['backoff_count'] ?? 0) + 1; // Cap backoff count to prevent overflow (2^6 = 64, which is > MAX_BACKOFF_MINUTES) $cappedCount = min($backoffCount, 6); $backoffMinutes = min(self::BACKOFF_MULTIPLIER ** $cappedCount, self::MAX_BACKOFF_MINUTES); $rateLimitData['backoff_until'] = $currentTime + ($backoffMinutes * 60); $rateLimitData['backoff_count'] = $backoffCount; $this->storeRateLimitData($rateLimitKey, $rateLimitData); Log::warning('Telegram notification failed - backoff period set', [ 'user_id' => $user->id, 'telegram_destination' => $telegramChannel->destination, 'backoff_count' => $backoffCount, 'backoff_minutes' => $backoffMinutes, 'backoff_until' => $rateLimitData['backoff_until'], ]); } /** * Get rate limit statistics */ public function getRateLimitStats(User $user, NotificationChannel $telegramChannel): array { $rateLimitKey = $this->getRateLimitKey($user, $telegramChannel); $rateLimitData = $this->getRateLimitData($rateLimitKey); return [ 'minute_count' => $rateLimitData['minute_count'] ?? 0, 'hour_count' => $rateLimitData['hour_count'] ?? 0, 'backoff_count' => $rateLimitData['backoff_count'] ?? 0, 'backoff_until' => $rateLimitData['backoff_until'] ?? null, 'is_in_backoff' => $this->isInBackoffPeriod($rateLimitData), 'minute_limit' => self::MAX_MESSAGES_PER_MINUTE, 'hour_limit' => self::MAX_MESSAGES_PER_HOUR, ]; } /** * Reset the rate limit for a user and Telegram channel */ public function resetRateLimit(User $user, NotificationChannel $telegramChannel): void { $rateLimitKey = $this->getRateLimitKey($user, $telegramChannel); \Illuminate\Support\Facades\Cache::forget($rateLimitKey); } /** * Get the cache key for rate limiting */ private function getRateLimitKey(User $user, NotificationChannel $telegramChannel): string { return "telegram_rate_limit:{$user->id}:{$telegramChannel->destination}"; } /** * Get rate limit data from cache */ private function getRateLimitData(string $key): array { return Cache::get($key, [ 'minute_count' => 0, 'minute_window_start' => now()->timestamp, 'hour_count' => 0, 'hour_window_start' => now()->timestamp, 'backoff_count' => 0, ]); } /** * Store rate limit data in cache */ private function storeRateLimitData(string $key, array $data): void { Cache::put($key, $data, self::CACHE_TTL); } /** * Check if we're in a backoff period */ private function isInBackoffPeriod(array $rateLimitData): bool { if (! isset($rateLimitData['backoff_until'])) { return false; } return now()->timestamp < $rateLimitData['backoff_until']; } /** * Check minute rate limit */ private function checkMinuteRateLimit(array $rateLimitData): bool { $currentTime = now()->timestamp; $windowStart = $rateLimitData['minute_window_start'] ?? $currentTime; $count = $rateLimitData['minute_count'] ?? 0; // Reset window if more than 1 minute has passed if ($currentTime - $windowStart >= 60) { return true; } return $count < self::MAX_MESSAGES_PER_MINUTE; } /** * Check hour rate limit */ private function checkHourRateLimit(array $rateLimitData): bool { $currentTime = now()->timestamp; $windowStart = $rateLimitData['hour_window_start'] ?? $currentTime; $count = $rateLimitData['hour_count'] ?? 0; // Reset window if more than 1 hour has passed if ($currentTime - $windowStart >= 3600) { return true; } return $count < self::MAX_MESSAGES_PER_HOUR; } /** * Update minute counter */ private function updateMinuteCounter(array $rateLimitData, int $currentTime): array { $windowStart = $rateLimitData['minute_window_start'] ?? $currentTime; // Reset window if more than 1 minute has passed if ($currentTime - $windowStart >= 60) { $rateLimitData['minute_count'] = 1; $rateLimitData['minute_window_start'] = $currentTime; } else { $rateLimitData['minute_count'] = ($rateLimitData['minute_count'] ?? 0) + 1; } return $rateLimitData; } /** * Update hour counter */ private function updateHourCounter(array $rateLimitData, int $currentTime): array { $windowStart = $rateLimitData['hour_window_start'] ?? $currentTime; // Reset window if more than 1 hour has passed if ($currentTime - $windowStart >= 3600) { $rateLimitData['hour_count'] = 1; $rateLimitData['hour_window_start'] = $currentTime; } else { $rateLimitData['hour_count'] = ($rateLimitData['hour_count'] ?? 0) + 1; } return $rateLimitData; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/MonitorPerformanceService.php
app/Services/MonitorPerformanceService.php
<?php namespace App\Services; use App\Models\MonitorHistory; use App\Models\MonitorPerformanceHourly; use Carbon\Carbon; class MonitorPerformanceService { /** * Update hourly performance metrics for a monitor. */ public function updateHourlyMetrics(int $monitorId, ?int $responseTime, bool $isSuccess): void { $hour = Carbon::now()->startOfHour(); // Find or create hourly record $performance = MonitorPerformanceHourly::firstOrNew([ 'monitor_id' => $monitorId, 'hour' => $hour, ]); // Update counts if ($isSuccess) { $performance->success_count = ($performance->success_count ?? 0) + 1; } else { $performance->failure_count = ($performance->failure_count ?? 0) + 1; } // Update response time metrics if available if ($responseTime !== null && $isSuccess) { $this->updateResponseTimeMetrics($performance, $responseTime); } $performance->save(); } /** * Update response time metrics for the hourly performance record. */ protected function updateResponseTimeMetrics(MonitorPerformanceHourly $performance, int $responseTime): void { // Use efficient range query instead of individual comparisons $startHour = $performance->hour; $endHour = $performance->hour->copy()->addHour(); // Get all response times for this hour using created_at for consistency $responseTimes = MonitorHistory::where('monitor_id', $performance->monitor_id) ->whereBetween('created_at', [$startHour, $endHour]) ->whereNotNull('response_time') ->where('uptime_status', 'up') ->pluck('response_time') ->toArray(); if (empty($responseTimes)) { $performance->avg_response_time = $responseTime; $performance->p95_response_time = $responseTime; $performance->p99_response_time = $responseTime; return; } // Calculate average $performance->avg_response_time = array_sum($responseTimes) / count($responseTimes); // Calculate percentiles sort($responseTimes); $performance->p95_response_time = $this->calculatePercentile($responseTimes, 95); $performance->p99_response_time = $this->calculatePercentile($responseTimes, 99); } /** * Calculate percentile from sorted array. */ protected function calculatePercentile(array $sortedArray, int $percentile): float { $count = count($sortedArray); $index = ($percentile / 100) * ($count - 1); if (floor($index) == $index) { return $sortedArray[$index]; } $lower = floor($index); $upper = ceil($index); $weight = $index - $lower; return $sortedArray[$lower] * (1 - $weight) + $sortedArray[$upper] * $weight; } /** * Aggregate daily performance metrics for a monitor. */ public function aggregateDailyMetrics(int $monitorId, string $date): array { $startDate = Carbon::parse($date)->startOfDay(); $endDate = $startDate->copy()->endOfDay(); // Use created_at instead of checked_at for consistency with the main job // and because some records have null checked_at values $result = MonitorHistory::where('monitor_id', $monitorId) ->whereBetween('created_at', [$startDate, $endDate]) ->selectRaw(' COUNT(*) as total_checks, SUM(CASE WHEN uptime_status = "down" THEN 1 ELSE 0 END) as failed_checks, AVG(CASE WHEN uptime_status = "up" AND response_time IS NOT NULL THEN response_time ELSE NULL END) as avg_response_time, MIN(CASE WHEN uptime_status = "up" AND response_time IS NOT NULL THEN response_time ELSE NULL END) as min_response_time, MAX(CASE WHEN uptime_status = "up" AND response_time IS NOT NULL THEN response_time ELSE NULL END) as max_response_time ') ->first(); return [ 'avg_response_time' => $result->avg_response_time ? round($result->avg_response_time) : null, 'min_response_time' => $result->min_response_time, 'max_response_time' => $result->max_response_time, 'total_checks' => $result->total_checks ?? 0, 'failed_checks' => $result->failed_checks ?? 0, ]; } /** * Get response time statistics for a monitor in a date range. */ public function getResponseTimeStats(int $monitorId, Carbon $startDate, Carbon $endDate): array { $histories = MonitorHistory::where('monitor_id', $monitorId) ->whereBetween('created_at', [$startDate, $endDate]) ->whereNotNull('response_time') ->where('uptime_status', 'up') ->pluck('response_time') ->filter() ->toArray(); if (empty($histories)) { return [ 'avg' => 0, 'min' => 0, 'max' => 0, ]; } return [ 'avg' => round(array_sum($histories) / count($histories)), 'min' => min($histories), 'max' => max($histories), ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/MaintenanceWindowService.php
app/Services/MaintenanceWindowService.php
<?php namespace App\Services; use App\Models\Monitor; use Carbon\Carbon; use Illuminate\Support\Facades\Log; class MaintenanceWindowService { /** * Check if a monitor is currently in a maintenance window. */ public function isInMaintenance(Monitor $monitor): bool { // Quick check using the cached flag first if ($monitor->is_in_maintenance) { // Verify the maintenance is still valid if ($monitor->maintenance_ends_at && Carbon::parse($monitor->maintenance_ends_at)->isFuture()) { return true; } } // Check maintenance windows configuration $windows = $monitor->maintenance_windows; if (empty($windows) || ! is_array($windows)) { return false; } $now = Carbon::now(); foreach ($windows as $window) { if ($this->isInWindow($window, $now)) { return true; } } return false; } /** * Check if current time falls within a maintenance window. */ protected function isInWindow(array $window, Carbon $now): bool { $type = $window['type'] ?? null; if ($type === 'one_time') { return $this->isInOneTimeWindow($window, $now); } if ($type === 'recurring') { return $this->isInRecurringWindow($window, $now); } return false; } /** * Check if current time is in a one-time maintenance window. */ protected function isInOneTimeWindow(array $window, Carbon $now): bool { $start = isset($window['start']) ? Carbon::parse($window['start']) : null; $end = isset($window['end']) ? Carbon::parse($window['end']) : null; if (! $start || ! $end) { return false; } return $now->between($start, $end); } /** * Check if current time is in a recurring maintenance window. */ protected function isInRecurringWindow(array $window, Carbon $now): bool { $dayOfWeek = $window['day_of_week'] ?? null; // 0 = Sunday, 6 = Saturday $startTime = $window['start_time'] ?? null; // "HH:MM" format $endTime = $window['end_time'] ?? null; // "HH:MM" format $timezone = $window['timezone'] ?? config('app.timezone', 'UTC'); if ($dayOfWeek === null || ! $startTime || ! $endTime) { return false; } // Convert now to the configured timezone $nowInTimezone = $now->copy()->setTimezone($timezone); // Check if today is the maintenance day if ($nowInTimezone->dayOfWeek !== (int) $dayOfWeek) { return false; } // Parse start and end times in the configured timezone $startOfWindow = $nowInTimezone->copy()->setTimeFromTimeString($startTime); $endOfWindow = $nowInTimezone->copy()->setTimeFromTimeString($endTime); // Handle overnight windows (e.g., 23:00 to 02:00) if ($endOfWindow->lt($startOfWindow)) { // If we're after the start time, the window extends to midnight // If we're before the end time, the window started yesterday return $nowInTimezone->gte($startOfWindow) || $nowInTimezone->lte($endOfWindow); } return $nowInTimezone->between($startOfWindow, $endOfWindow); } /** * Get the next scheduled maintenance window for a monitor. */ public function getNextMaintenanceWindow(Monitor $monitor): ?array { $windows = $monitor->maintenance_windows; if (empty($windows) || ! is_array($windows)) { return null; } $now = Carbon::now(); $nextWindow = null; $nextStart = null; foreach ($windows as $window) { $windowStart = $this->getNextWindowStart($window, $now); if ($windowStart && (! $nextStart || $windowStart->lt($nextStart))) { $nextStart = $windowStart; $nextWindow = array_merge($window, [ 'next_start' => $windowStart->toIso8601String(), 'next_end' => $this->getWindowEnd($window, $windowStart)->toIso8601String(), ]); } } return $nextWindow; } /** * Get the next start time for a maintenance window. */ protected function getNextWindowStart(array $window, Carbon $now): ?Carbon { $type = $window['type'] ?? null; if ($type === 'one_time') { $start = isset($window['start']) ? Carbon::parse($window['start']) : null; return ($start && $start->isFuture()) ? $start : null; } if ($type === 'recurring') { $dayOfWeek = $window['day_of_week'] ?? null; $startTime = $window['start_time'] ?? null; $timezone = $window['timezone'] ?? config('app.timezone', 'UTC'); if ($dayOfWeek === null || ! $startTime) { return null; } $nowInTimezone = $now->copy()->setTimezone($timezone); // Calculate next occurrence of this day $nextOccurrence = $nowInTimezone->copy()->next((int) $dayOfWeek); // If today is the day and we haven't passed the start time, use today if ($nowInTimezone->dayOfWeek === (int) $dayOfWeek) { $todayStart = $nowInTimezone->copy()->setTimeFromTimeString($startTime); if ($todayStart->isFuture()) { return $todayStart->setTimezone(config('app.timezone')); } } return $nextOccurrence->setTimeFromTimeString($startTime)->setTimezone(config('app.timezone')); } return null; } /** * Get the end time for a maintenance window given a start time. */ protected function getWindowEnd(array $window, Carbon $start): Carbon { $type = $window['type'] ?? null; if ($type === 'one_time') { return Carbon::parse($window['end']); } if ($type === 'recurring') { $endTime = $window['end_time'] ?? '00:00'; $timezone = $window['timezone'] ?? config('app.timezone', 'UTC'); $end = $start->copy()->setTimeFromTimeString($endTime); // Handle overnight windows if ($end->lt($start)) { $end->addDay(); } return $end; } return $start->copy()->addHour(); // Default 1 hour if unknown } /** * Update maintenance status for all monitors. * This should be called by a scheduled command. */ public function updateAllMaintenanceStatuses(): int { $updated = 0; // Get all monitors with maintenance windows configured $monitors = Monitor::withoutGlobalScopes() ->whereNotNull('maintenance_windows') ->where('maintenance_windows', '!=', '[]') ->where('maintenance_windows', '!=', 'null') ->get(); foreach ($monitors as $monitor) { if ($this->updateMaintenanceStatus($monitor)) { $updated++; } } return $updated; } /** * Update maintenance status for a single monitor. */ public function updateMaintenanceStatus(Monitor $monitor): bool { $isInMaintenance = $this->isInMaintenance($monitor); $wasInMaintenance = $monitor->is_in_maintenance; // Only update if status changed if ($isInMaintenance !== $wasInMaintenance) { $monitor->is_in_maintenance = $isInMaintenance; if ($isInMaintenance) { // Find the current active window to set start/end times $activeWindow = $this->findActiveWindow($monitor); if ($activeWindow) { $monitor->maintenance_starts_at = $activeWindow['start']; $monitor->maintenance_ends_at = $activeWindow['end']; } Log::info('MaintenanceWindowService: Monitor entered maintenance', [ 'monitor_id' => $monitor->id, 'url' => (string) $monitor->url, 'ends_at' => $monitor->maintenance_ends_at, ]); } else { $monitor->maintenance_starts_at = null; $monitor->maintenance_ends_at = null; Log::info('MaintenanceWindowService: Monitor exited maintenance', [ 'monitor_id' => $monitor->id, 'url' => (string) $monitor->url, ]); } $monitor->saveQuietly(); return true; } return false; } /** * Find the currently active maintenance window. */ protected function findActiveWindow(Monitor $monitor): ?array { $windows = $monitor->maintenance_windows; if (empty($windows) || ! is_array($windows)) { return null; } $now = Carbon::now(); foreach ($windows as $window) { if ($this->isInWindow($window, $now)) { $type = $window['type'] ?? null; if ($type === 'one_time') { return [ 'start' => Carbon::parse($window['start']), 'end' => Carbon::parse($window['end']), ]; } if ($type === 'recurring') { $timezone = $window['timezone'] ?? config('app.timezone', 'UTC'); $nowInTimezone = $now->copy()->setTimezone($timezone); $start = $nowInTimezone->copy()->setTimeFromTimeString($window['start_time']); $end = $nowInTimezone->copy()->setTimeFromTimeString($window['end_time']); // Handle overnight windows if ($end->lt($start)) { if ($nowInTimezone->lt($end)) { $start->subDay(); } else { $end->addDay(); } } return [ 'start' => $start->setTimezone(config('app.timezone')), 'end' => $end->setTimezone(config('app.timezone')), ]; } } } return null; } /** * Clean up expired one-time maintenance windows. */ public function cleanupExpiredWindows(): int { $cleaned = 0; $now = Carbon::now(); $monitors = Monitor::withoutGlobalScopes() ->whereNotNull('maintenance_windows') ->where('maintenance_windows', '!=', '[]') ->where('maintenance_windows', '!=', 'null') ->get(); foreach ($monitors as $monitor) { $windows = $monitor->maintenance_windows; if (empty($windows) || ! is_array($windows)) { continue; } $filteredWindows = array_filter($windows, function ($window) { if (($window['type'] ?? null) !== 'one_time') { return true; // Keep recurring windows } $end = isset($window['end']) ? Carbon::parse($window['end']) : null; return $end && $end->isFuture(); }); if (count($filteredWindows) !== count($windows)) { $monitor->maintenance_windows = array_values($filteredWindows); $monitor->saveQuietly(); $cleaned++; } } return $cleaned; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/OgImageService.php
app/Services/OgImageService.php
<?php namespace App\Services; use App\Models\Monitor; use App\Models\StatusPage; use Intervention\Image\Drivers\Gd\Driver; use Intervention\Image\ImageManager; use Intervention\Image\Interfaces\ImageInterface; use Intervention\Image\Typography\FontFactory; class OgImageService { private ImageManager $manager; private int $width = 1200; private int $height = 630; // Brand colors matching BadgeController private array $colors = [ 'brightgreen' => '#22c55e', 'green' => '#84cc16', 'yellowgreen' => '#a3e635', 'yellow' => '#facc15', 'orange' => '#f97316', 'red' => '#ef4444', 'gray' => '#9ca3af', 'background' => '#0f172a', // Dark slate 'card' => '#1e293b', // Lighter slate 'text' => '#f8fafc', // Almost white 'text_muted' => '#94a3b8', // Muted gray 'brand_blue' => '#3b82f6', // Blue-500 ]; public function __construct() { $this->manager = new ImageManager(new Driver); } /** * Generate OG image for monitors index page. */ public function generateMonitorsIndex(array $stats): string { $image = $this->createBaseImage(); // Add gradient background $this->addGradientOverlay($image); // Add logo (centered at top) $this->addLogo($image, $this->width / 2, 100, 0.8); // Add title $image->text('Public Monitors', $this->width / 2, 230, function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(56); $font->color($this->colors['text']); $font->align('center'); $font->valign('middle'); }); // Add subtitle $image->text('Real-time uptime monitoring for your services', $this->width / 2, 290, function (FontFactory $font) { $font->filename($this->getFont('regular')); $font->size(24); $font->color($this->colors['text_muted']); $font->align('center'); $font->valign('middle'); }); // Add stats cards $this->drawStatsRow($image, [ ['label' => 'Total Monitors', 'value' => (string) ($stats['total'] ?? 0), 'color' => $this->colors['brand_blue']], ['label' => 'Online', 'value' => (string) ($stats['up'] ?? 0), 'color' => $this->colors['brightgreen']], ['label' => 'Down', 'value' => (string) ($stats['down'] ?? 0), 'color' => $this->colors['red']], ], 370); // Add branding footer $this->addBranding($image); return $image->toPng()->toString(); } /** * Generate OG image for individual monitor. */ public function generateMonitor(Monitor $monitor): string { $image = $this->createBaseImage(); // Add gradient background $this->addGradientOverlay($image); // Add logo (smaller, top-left corner) $this->addLogo($image, 100, 60, 0.4); // Status indicator (large circle) $statusColor = $monitor->uptime_status === 'up' ? $this->colors['brightgreen'] : $this->colors['red']; $centerX = $this->width / 2; // Draw status circle background $image->drawCircle($centerX, 200, function ($circle) use ($statusColor) { $circle->radius(70); $circle->background($statusColor); }); // Status text inside circle $statusText = $monitor->uptime_status === 'up' ? 'UP' : 'DOWN'; $image->text($statusText, $centerX, 200, function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(36); $font->color('#ffffff'); $font->align('center'); $font->valign('middle'); }); // Monitor host/domain $host = $monitor->host ?? parse_url($monitor->url, PHP_URL_HOST) ?? $monitor->url; $displayHost = strlen($host) > 40 ? substr($host, 0, 37).'...' : $host; $image->text($displayHost, $centerX, 320, function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(42); $font->color($this->colors['text']); $font->align('center'); $font->valign('middle'); }); // Uptime stats $uptime24h = $monitor->statistics?->uptime_24h ?? 100; $uptime7d = $monitor->statistics?->uptime_7d ?? 100; $uptime30d = $monitor->statistics?->uptime_30d ?? 100; $this->drawStatsRow($image, [ ['label' => '24h Uptime', 'value' => number_format($uptime24h, 1).'%', 'color' => $this->getColorForUptime($uptime24h)], ['label' => '7d Uptime', 'value' => number_format($uptime7d, 1).'%', 'color' => $this->getColorForUptime($uptime7d)], ['label' => '30d Uptime', 'value' => number_format($uptime30d, 1).'%', 'color' => $this->getColorForUptime($uptime30d)], ], 400); // Response time (if available) $avgResponseTime = $monitor->statistics?->avg_response_time_24h; if ($avgResponseTime) { $image->text('Avg Response: '.round($avgResponseTime).'ms', $centerX, 540, function (FontFactory $font) { $font->filename($this->getFont('regular')); $font->size(22); $font->color($this->colors['text_muted']); $font->align('center'); $font->valign('middle'); }); } $this->addBranding($image); return $image->toPng()->toString(); } /** * Generate OG image for status page. */ public function generateStatusPage(StatusPage $statusPage): string { $image = $this->createBaseImage(); // Add gradient background $this->addGradientOverlay($image); // Add logo (smaller, top-left) $this->addLogo($image, 100, 60, 0.4); // Calculate overall status $monitors = $statusPage->monitors; $totalMonitors = $monitors->count(); $upMonitors = $monitors->where('uptime_status', 'up')->count(); $allUp = $totalMonitors > 0 && $upMonitors === $totalMonitors; // Overall status indicator $statusColor = $allUp ? $this->colors['brightgreen'] : $this->colors['orange']; $statusText = $allUp ? 'All Systems Operational' : 'Partial Outage'; if ($totalMonitors > 0 && $upMonitors === 0) { $statusColor = $this->colors['red']; $statusText = 'Major Outage'; } // Status banner $bannerY = 150; $bannerHeight = 70; $image->drawRectangle(100, $bannerY, function ($rectangle) use ($statusColor, $bannerHeight) { $rectangle->size(1000, $bannerHeight); $rectangle->background($statusColor); }); $image->text($statusText, $this->width / 2, $bannerY + ($bannerHeight / 2), function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(32); $font->color('#ffffff'); $font->align('center'); $font->valign('middle'); }); // Status page title $title = strlen($statusPage->title) > 40 ? substr($statusPage->title, 0, 37).'...' : $statusPage->title; $image->text($title, $this->width / 2, 280, function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(48); $font->color($this->colors['text']); $font->align('center'); $font->valign('middle'); }); // Description (truncated) if ($statusPage->description) { $description = strlen($statusPage->description) > 70 ? substr($statusPage->description, 0, 67).'...' : $statusPage->description; $image->text($description, $this->width / 2, 340, function (FontFactory $font) { $font->filename($this->getFont('regular')); $font->size(22); $font->color($this->colors['text_muted']); $font->align('center'); $font->valign('middle'); }); } // Monitor stats $this->drawStatsRow($image, [ ['label' => 'Total Services', 'value' => (string) $totalMonitors, 'color' => $this->colors['brand_blue']], ['label' => 'Online', 'value' => (string) $upMonitors, 'color' => $this->colors['brightgreen']], ['label' => 'Issues', 'value' => (string) ($totalMonitors - $upMonitors), 'color' => $this->colors['orange']], ], 420); $this->addBranding($image); return $image->toPng()->toString(); } /** * Generate not found image. */ public function generateNotFound(string $identifier): string { $image = $this->createBaseImage(); // Add gradient background $this->addGradientOverlay($image); $this->addLogo($image, $this->width / 2, 180, 0.8); $image->text('Not Found', $this->width / 2, 340, function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(56); $font->color($this->colors['red']); $font->align('center'); $font->valign('middle'); }); $displayId = strlen($identifier) > 50 ? substr($identifier, 0, 47).'...' : $identifier; $image->text($displayId, $this->width / 2, 420, function (FontFactory $font) { $font->filename($this->getFont('regular')); $font->size(28); $font->color($this->colors['text_muted']); $font->align('center'); $font->valign('middle'); }); $this->addBranding($image); return $image->toPng()->toString(); } /** * Create base image with background color. */ private function createBaseImage(): ImageInterface { return $this->manager->create($this->width, $this->height) ->fill($this->colors['background']); } /** * Add a subtle gradient overlay for visual interest. */ private function addGradientOverlay(ImageInterface $image): void { // Add a subtle lighter area at the top $image->drawRectangle(0, 0, function ($rectangle) { $rectangle->size($this->width, 200); $rectangle->background('rgba(30, 41, 59, 0.5)'); }); } /** * Add the logo to the image. */ private function addLogo(ImageInterface $image, int $x, int $y, float $scale = 1.0): void { $logoPath = public_path('images/uptime-kita.png'); if (! file_exists($logoPath)) { $logoPath = public_path('images/uptime-kita.jpg'); } if (file_exists($logoPath)) { $logo = $this->manager->read($logoPath); $logoWidth = (int) (150 * $scale); $logoHeight = (int) (150 * $scale); $logo->resize($logoWidth, $logoHeight); // Calculate position to center the logo at (x, y) $posX = (int) ($x - ($logoWidth / 2)); $posY = (int) ($y - ($logoHeight / 2)); $image->place($logo, 'top-left', $posX, $posY); } else { // If no logo, draw a simple placeholder $image->text('Uptime Kita', $x, $y, function (FontFactory $font) { $font->filename($this->getFont('bold')); $font->size(36); $font->color($this->colors['brand_blue']); $font->align('center'); $font->valign('middle'); }); } } /** * Add branding footer. */ private function addBranding(ImageInterface $image): void { $image->text('uptime.syofyanzuhad.dev', $this->width / 2, 595, function (FontFactory $font) { $font->filename($this->getFont('regular')); $font->size(18); $font->color($this->colors['text_muted']); $font->align('center'); $font->valign('middle'); }); } /** * Draw a row of stats cards. */ private function drawStatsRow(ImageInterface $image, array $stats, int $y): void { $cardWidth = 300; $cardHeight = 100; $spacing = 50; $totalWidth = (count($stats) * $cardWidth) + ((count($stats) - 1) * $spacing); $startX = ($this->width - $totalWidth) / 2; foreach ($stats as $index => $stat) { $cardX = (int) ($startX + ($index * ($cardWidth + $spacing))); $centerX = $cardX + ($cardWidth / 2); // Card background with rounded corners $image->drawRectangle($cardX, $y, function ($rectangle) use ($cardWidth, $cardHeight) { $rectangle->size($cardWidth, $cardHeight); $rectangle->background($this->colors['card']); }); // Value $image->text($stat['value'], (int) $centerX, $y + 35, function (FontFactory $font) use ($stat) { $font->filename($this->getFont('bold')); $font->size(36); $font->color($stat['color']); $font->align('center'); $font->valign('middle'); }); // Label $image->text($stat['label'], (int) $centerX, $y + 75, function (FontFactory $font) { $font->filename($this->getFont('regular')); $font->size(16); $font->color($this->colors['text_muted']); $font->align('center'); $font->valign('middle'); }); } } /** * Get color based on uptime percentage. */ private function getColorForUptime(float $uptime): string { return match (true) { $uptime >= 99 => $this->colors['brightgreen'], $uptime >= 97 => $this->colors['green'], $uptime >= 95 => $this->colors['yellowgreen'], $uptime >= 90 => $this->colors['yellow'], $uptime >= 80 => $this->colors['orange'], default => $this->colors['red'], }; } /** * Get font path. */ private function getFont(string $weight): string { $fontPath = match ($weight) { 'bold' => resource_path('fonts/Inter-Bold.ttf'), default => resource_path('fonts/Inter-Regular.ttf'), }; // Fallback to a system font if custom font doesn't exist if (! file_exists($fontPath)) { // Try common system font paths $systemFonts = [ '/System/Library/Fonts/Helvetica.ttc', '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf', ]; foreach ($systemFonts as $systemFont) { if (file_exists($systemFont)) { return $systemFont; } } } return $fontPath; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/InstanceIdService.php
app/Services/InstanceIdService.php
<?php namespace App\Services; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; class InstanceIdService { /** * Get or create the anonymous instance ID. * * The ID is a one-way hash that cannot be reversed to identify * the installation or its owner. */ public function getInstanceId(): string { $path = config('telemetry.instance_id_path'); if (File::exists($path)) { return trim(File::get($path)); } $instanceId = $this->generateInstanceId(); // Ensure directory exists File::ensureDirectoryExists(dirname($path)); File::put($path, $instanceId); return $instanceId; } /** * Generate a new anonymous instance ID. * * Uses a combination of random data hashed with SHA-256 * to create a unique, non-reversible identifier. */ protected function generateInstanceId(): string { // Combine random bytes with current timestamp for uniqueness $randomData = Str::random(64).microtime(true).random_bytes(32); // Create SHA-256 hash (64 characters, not reversible) return hash('sha256', $randomData); } /** * Get the installation date (first time instance ID was created). */ public function getInstallDate(): ?string { $path = config('telemetry.instance_id_path'); if (File::exists($path)) { $timestamp = File::lastModified($path); return date('Y-m-d', $timestamp); } return date('Y-m-d'); // Today if no ID exists yet } /** * Regenerate the instance ID (for privacy-conscious users). */ public function regenerateInstanceId(): string { $path = config('telemetry.instance_id_path'); if (File::exists($path)) { File::delete($path); } return $this->getInstanceId(); } /** * Check if instance ID exists. */ public function hasInstanceId(): bool { return File::exists(config('telemetry.instance_id_path')); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/SmartRetryService.php
app/Services/SmartRetryService.php
<?php namespace App\Services; use App\Models\Monitor; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\TransferStats; use Illuminate\Support\Facades\Log; class SmartRetryService { public const SENSITIVITY_PRESETS = [ 'low' => [ 'confirmation_delay' => 60, 'retries' => 5, 'backoff_multiplier' => 2, 'initial_delay_ms' => 200, ], 'medium' => [ 'confirmation_delay' => 30, 'retries' => 3, 'backoff_multiplier' => 2, 'initial_delay_ms' => 100, ], 'high' => [ 'confirmation_delay' => 15, 'retries' => 2, 'backoff_multiplier' => 1.5, 'initial_delay_ms' => 50, ], ]; protected Client $client; protected int $timeout; public function __construct() { $this->timeout = config('uptime-monitor.confirmation_check.timeout_seconds', 5); $this->client = new Client([ 'timeout' => $this->timeout, 'connect_timeout' => $this->timeout, 'http_errors' => false, 'allow_redirects' => [ 'max' => 5, 'strict' => false, 'referer' => false, 'protocols' => ['http', 'https'], ], ]); } public static function getPreset(string $sensitivity): array { return self::SENSITIVITY_PRESETS[$sensitivity] ?? self::SENSITIVITY_PRESETS['medium']; } public function performSmartCheck(Monitor $monitor, array $options = []): SmartRetryResult { $retries = $options['retries'] ?? 3; $initialDelay = $options['initial_delay_ms'] ?? 100; $backoffMultiplier = $options['backoff_multiplier'] ?? 2; $attempts = []; $currentDelay = $initialDelay; $attemptNumber = 1; for ($i = 0; $i < $retries; $i++) { // Try HEAD first (lighter request) $result = $this->tryHttpRequest($monitor, 'HEAD', $attemptNumber); $attempts[] = $result; $attemptNumber++; if ($result->isSuccess()) { return $this->buildSuccessResult($attempts, $result); } // If HEAD times out, try GET (some servers don't respond to HEAD properly) if ($result->isTimeout() && $i < $retries - 1) { usleep($currentDelay * 1000); $result = $this->tryHttpRequest($monitor, 'GET', $attemptNumber); $attempts[] = $result; $attemptNumber++; if ($result->isSuccess()) { return $this->buildSuccessResult($attempts, $result); } } // Exponential backoff before next retry if ($i < $retries - 1) { usleep($currentDelay * 1000); $currentDelay = (int) ($currentDelay * $backoffMultiplier); } } // Final attempt: TCP ping (port check) if ($this->canPerformTcpPing($monitor)) { $tcpResult = $this->tryTcpPing($monitor, $attemptNumber); $attempts[] = $tcpResult; if ($tcpResult->isSuccess()) { // Server responding to TCP but HTTP failing - likely app issue, not network return new SmartRetryResult( success: false, attempts: $attempts, message: 'HTTP failure but TCP responsive - likely application issue', ); } } $lastAttempt = $attempts[array_key_last($attempts)]; return new SmartRetryResult( success: false, attempts: $attempts, message: $lastAttempt->errorMessage ?? 'All retry attempts failed', statusCode: $lastAttempt->statusCode, ); } protected function tryHttpRequest(Monitor $monitor, string $method, int $attemptNumber): SmartRetryAttempt { $url = (string) $monitor->url; $responseTime = null; $options = [ 'on_stats' => function (TransferStats $stats) use (&$responseTime) { $responseTime = $stats->getTransferTime() * 1000; // Convert to ms }, ]; // Add custom headers if configured if ($monitor->uptime_check_additional_headers) { $headers = is_array($monitor->uptime_check_additional_headers) ? $monitor->uptime_check_additional_headers : json_decode($monitor->uptime_check_additional_headers, true); if ($headers) { $options['headers'] = $headers; } } // Add payload if configured (only for non-HEAD requests) if ($method !== 'HEAD' && $monitor->uptime_check_payload) { $options['body'] = $monitor->uptime_check_payload; } $startTime = microtime(true); try { $response = $this->client->request($method, $url, $options); $statusCode = $response->getStatusCode(); // Calculate response time if not captured by stats if ($responseTime === null) { $responseTime = (microtime(true) - $startTime) * 1000; } // Check if status code is acceptable $expectedStatusCode = $monitor->expected_status_code ?? 200; $additionalStatusCodes = config('uptime-monitor.uptime_check.additional_status_codes', []); $acceptableStatusCodes = array_merge([$expectedStatusCode], $additionalStatusCodes, [200, 201, 204, 301, 302]); if (! in_array($statusCode, $acceptableStatusCodes)) { return new SmartRetryAttempt( success: false, type: SmartRetryAttempt::TYPE_HTTP, method: $method, statusCode: $statusCode, responseTime: $responseTime, errorType: SmartRetryAttempt::ERROR_HTTP_STATUS, errorMessage: "Unexpected status code: {$statusCode}", attemptNumber: $attemptNumber, ); } // Check for look_for_string if configured (only for GET requests) if ($method === 'GET' && $monitor->look_for_string) { $body = (string) $response->getBody(); if (stripos($body, $monitor->look_for_string) === false) { return new SmartRetryAttempt( success: false, type: SmartRetryAttempt::TYPE_HTTP, method: $method, statusCode: $statusCode, responseTime: $responseTime, errorType: SmartRetryAttempt::ERROR_STRING_NOT_FOUND, errorMessage: "String not found: {$monitor->look_for_string}", attemptNumber: $attemptNumber, ); } } return new SmartRetryAttempt( success: true, type: SmartRetryAttempt::TYPE_HTTP, method: $method, statusCode: $statusCode, responseTime: $responseTime, attemptNumber: $attemptNumber, ); } catch (ConnectException $e) { $errorType = $this->classifyConnectionError($e); return new SmartRetryAttempt( success: false, type: SmartRetryAttempt::TYPE_HTTP, method: $method, responseTime: (microtime(true) - $startTime) * 1000, errorType: $errorType, errorMessage: $e->getMessage(), attemptNumber: $attemptNumber, ); } catch (RequestException $e) { return new SmartRetryAttempt( success: false, type: SmartRetryAttempt::TYPE_HTTP, method: $method, statusCode: $e->hasResponse() ? $e->getResponse()->getStatusCode() : null, responseTime: (microtime(true) - $startTime) * 1000, errorType: SmartRetryAttempt::ERROR_UNKNOWN, errorMessage: $e->getMessage(), attemptNumber: $attemptNumber, ); } catch (\Exception $e) { Log::error('SmartRetryService: Unexpected error', [ 'url' => $url, 'method' => $method, 'error' => $e->getMessage(), ]); return new SmartRetryAttempt( success: false, type: SmartRetryAttempt::TYPE_HTTP, method: $method, responseTime: (microtime(true) - $startTime) * 1000, errorType: SmartRetryAttempt::ERROR_UNKNOWN, errorMessage: $e->getMessage(), attemptNumber: $attemptNumber, ); } } protected function classifyConnectionError(ConnectException $e): string { $message = strtolower($e->getMessage()); if (str_contains($message, 'timed out') || str_contains($message, 'timeout')) { return SmartRetryAttempt::ERROR_TIMEOUT; } if (str_contains($message, 'connection refused')) { return SmartRetryAttempt::ERROR_CONNECTION_REFUSED; } if (str_contains($message, 'could not resolve') || str_contains($message, 'name or service not known')) { return SmartRetryAttempt::ERROR_DNS; } if (str_contains($message, 'ssl') || str_contains($message, 'certificate')) { return SmartRetryAttempt::ERROR_SSL; } return SmartRetryAttempt::ERROR_UNKNOWN; } protected function canPerformTcpPing(Monitor $monitor): bool { $url = $monitor->url; return $url !== null && $url->getHost() !== ''; } protected function tryTcpPing(Monitor $monitor, int $attemptNumber): SmartRetryAttempt { $url = $monitor->url; $host = $url->getHost(); $port = $url->getPort() ?? ($url->getScheme() === 'https' ? 443 : 80); $startTime = microtime(true); $socket = @fsockopen($host, $port, $errno, $errstr, $this->timeout); $responseTime = (microtime(true) - $startTime) * 1000; if ($socket) { fclose($socket); return new SmartRetryAttempt( success: true, type: SmartRetryAttempt::TYPE_TCP, responseTime: $responseTime, attemptNumber: $attemptNumber, ); } $errorType = match ($errno) { 110, 111 => SmartRetryAttempt::ERROR_CONNECTION_REFUSED, default => SmartRetryAttempt::ERROR_TIMEOUT, }; return new SmartRetryAttempt( success: false, type: SmartRetryAttempt::TYPE_TCP, responseTime: $responseTime, errorType: $errorType, errorMessage: $errstr, attemptNumber: $attemptNumber, ); } protected function buildSuccessResult(array $attempts, SmartRetryAttempt $successfulAttempt): SmartRetryResult { return new SmartRetryResult( success: true, attempts: $attempts, statusCode: $successfulAttempt->statusCode, responseTime: $successfulAttempt->responseTime, ); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/SmartRetryResult.php
app/Services/SmartRetryResult.php
<?php namespace App\Services; class SmartRetryResult { public function __construct( public bool $success, public array $attempts = [], public ?string $message = null, public ?int $statusCode = null, public ?float $responseTime = null, ) {} public function isSuccess(): bool { return $this->success; } public function getAttemptCount(): int { return count($this->attempts); } public function getLastAttempt(): ?SmartRetryAttempt { return $this->attempts[array_key_last($this->attempts)] ?? null; } public function getSuccessfulAttempt(): ?SmartRetryAttempt { foreach ($this->attempts as $attempt) { if ($attempt->success) { return $attempt; } } return null; } public function toArray(): array { return [ 'success' => $this->success, 'message' => $this->message, 'status_code' => $this->statusCode, 'response_time' => $this->responseTime, 'attempt_count' => $this->getAttemptCount(), 'attempts' => array_map(fn ($a) => $a->toArray(), $this->attempts), ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/ServerResourceService.php
app/Services/ServerResourceService.php
<?php namespace App\Services; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; class ServerResourceService { /** * Get all server resource metrics. */ public function getMetrics(): array { return [ 'cpu' => $this->getCpuUsage(), 'memory' => $this->getMemoryUsage(), 'disk' => $this->getDiskUsage(), 'uptime' => $this->getServerUptime(), 'load_average' => $this->getLoadAverage(), 'php' => $this->getPhpInfo(), 'laravel' => $this->getLaravelInfo(), 'database' => $this->getDatabaseInfo(), 'queue' => $this->getQueueInfo(), 'cache' => $this->getCacheInfo(), 'timestamp' => now()->toIso8601String(), ]; } /** * Get CPU usage percentage. */ protected function getCpuUsage(): array { $cpuUsage = 0; $cores = 1; if (PHP_OS_FAMILY === 'Darwin') { // macOS $output = shell_exec("top -l 1 | grep 'CPU usage' | awk '{print $3}' | sed 's/%//'"); $cpuUsage = $output ? (float) trim($output) : 0; $cores = (int) shell_exec('sysctl -n hw.ncpu 2>/dev/null') ?: 1; } elseif (PHP_OS_FAMILY === 'Linux') { // Linux - using /proc/stat $stat1 = file_get_contents('/proc/stat'); usleep(100000); // 100ms $stat2 = file_get_contents('/proc/stat'); $info1 = $this->parseProcStat($stat1); $info2 = $this->parseProcStat($stat2); $diff = [ 'user' => $info2['user'] - $info1['user'], 'nice' => $info2['nice'] - $info1['nice'], 'system' => $info2['system'] - $info1['system'], 'idle' => $info2['idle'] - $info1['idle'], ]; $total = array_sum($diff); $cpuUsage = $total > 0 ? round(($total - $diff['idle']) / $total * 100, 1) : 0; $cores = (int) shell_exec('nproc 2>/dev/null') ?: 1; } return [ 'usage_percent' => round($cpuUsage, 1), 'cores' => $cores, ]; } /** * Parse /proc/stat for Linux CPU info. */ protected function parseProcStat(string $stat): array { $lines = explode("\n", $stat); $cpuLine = $lines[0]; $parts = preg_split('/\s+/', $cpuLine); return [ 'user' => (int) ($parts[1] ?? 0), 'nice' => (int) ($parts[2] ?? 0), 'system' => (int) ($parts[3] ?? 0), 'idle' => (int) ($parts[4] ?? 0), ]; } /** * Get memory usage information. */ protected function getMemoryUsage(): array { $total = 0; $used = 0; $free = 0; if (PHP_OS_FAMILY === 'Darwin') { // macOS $pageSize = (int) shell_exec('pagesize 2>/dev/null') ?: 4096; $vmStat = shell_exec('vm_stat 2>/dev/null'); if ($vmStat) { preg_match('/Pages free:\s+(\d+)/', $vmStat, $freePages); preg_match('/Pages active:\s+(\d+)/', $vmStat, $activePages); preg_match('/Pages inactive:\s+(\d+)/', $vmStat, $inactivePages); preg_match('/Pages speculative:\s+(\d+)/', $vmStat, $speculativePages); preg_match('/Pages wired down:\s+(\d+)/', $vmStat, $wiredPages); $freePageCount = (int) ($freePages[1] ?? 0); $activePageCount = (int) ($activePages[1] ?? 0); $inactivePageCount = (int) ($inactivePages[1] ?? 0); $speculativePageCount = (int) ($speculativePages[1] ?? 0); $wiredPageCount = (int) ($wiredPages[1] ?? 0); $totalPages = $freePageCount + $activePageCount + $inactivePageCount + $speculativePageCount + $wiredPageCount; $total = $totalPages * $pageSize; $free = ($freePageCount + $inactivePageCount) * $pageSize; $used = $total - $free; } // Fallback to sysctl if ($total === 0) { $total = (int) shell_exec('sysctl -n hw.memsize 2>/dev/null') ?: 0; } } elseif (PHP_OS_FAMILY === 'Linux') { // Linux - using /proc/meminfo $meminfo = file_get_contents('/proc/meminfo'); preg_match('/MemTotal:\s+(\d+)/', $meminfo, $totalMatch); preg_match('/MemAvailable:\s+(\d+)/', $meminfo, $availableMatch); $total = ((int) ($totalMatch[1] ?? 0)) * 1024; // Convert from KB to bytes $available = ((int) ($availableMatch[1] ?? 0)) * 1024; $used = $total - $available; $free = $available; } $usagePercent = $total > 0 ? round(($used / $total) * 100, 1) : 0; return [ 'total' => $total, 'used' => $used, 'free' => $free, 'usage_percent' => $usagePercent, 'total_formatted' => $this->formatBytes($total), 'used_formatted' => $this->formatBytes($used), 'free_formatted' => $this->formatBytes($free), ]; } /** * Get disk usage information. */ protected function getDiskUsage(): array { $path = base_path(); $total = disk_total_space($path) ?: 0; $free = disk_free_space($path) ?: 0; $used = $total - $free; $usagePercent = $total > 0 ? round(($used / $total) * 100, 1) : 0; return [ 'total' => $total, 'used' => $used, 'free' => $free, 'usage_percent' => $usagePercent, 'total_formatted' => $this->formatBytes($total), 'used_formatted' => $this->formatBytes($used), 'free_formatted' => $this->formatBytes($free), 'path' => $path, ]; } /** * Get server uptime. */ protected function getServerUptime(): array { $uptimeSeconds = 0; if (PHP_OS_FAMILY === 'Darwin') { // macOS $bootTime = shell_exec("sysctl -n kern.boottime | awk '{print $4}' | sed 's/,//'"); if ($bootTime) { $uptimeSeconds = time() - (int) trim($bootTime); } } elseif (PHP_OS_FAMILY === 'Linux') { // Linux $uptime = file_get_contents('/proc/uptime'); if ($uptime) { $uptimeSeconds = (int) explode(' ', $uptime)[0]; } } return [ 'seconds' => $uptimeSeconds, 'formatted' => $this->formatUptime($uptimeSeconds), ]; } /** * Get load average (1, 5, 15 minutes). */ protected function getLoadAverage(): array { $load = sys_getloadavg(); return [ '1min' => round($load[0] ?? 0, 2), '5min' => round($load[1] ?? 0, 2), '15min' => round($load[2] ?? 0, 2), ]; } /** * Get PHP information. */ protected function getPhpInfo(): array { return [ 'version' => PHP_VERSION, 'memory_limit' => ini_get('memory_limit'), 'max_execution_time' => ini_get('max_execution_time'), 'upload_max_filesize' => ini_get('upload_max_filesize'), 'post_max_size' => ini_get('post_max_size'), 'extensions' => $this->getLoadedExtensions(), 'current_memory' => memory_get_usage(true), 'current_memory_formatted' => $this->formatBytes(memory_get_usage(true)), 'peak_memory' => memory_get_peak_usage(true), 'peak_memory_formatted' => $this->formatBytes(memory_get_peak_usage(true)), ]; } /** * Get important loaded PHP extensions. */ protected function getLoadedExtensions(): array { $important = ['pdo', 'pdo_sqlite', 'pdo_mysql', 'curl', 'mbstring', 'openssl', 'json', 'xml', 'zip', 'gd', 'redis', 'pcntl']; $loaded = get_loaded_extensions(); $result = []; foreach ($important as $ext) { $result[$ext] = in_array($ext, $loaded); } return $result; } /** * Get Laravel information. */ protected function getLaravelInfo(): array { return [ 'version' => app()->version(), 'environment' => app()->environment(), 'debug_mode' => config('app.debug'), 'timezone' => config('app.timezone'), 'locale' => config('app.locale'), ]; } /** * Get database information. */ protected function getDatabaseInfo(): array { $connection = config('database.default'); $size = 0; try { if ($connection === 'sqlite') { $path = config('database.connections.sqlite.database'); if (file_exists($path)) { $size = filesize($path); } } elseif ($connection === 'mysql') { $dbName = config('database.connections.mysql.database'); $result = DB::select('SELECT SUM(data_length + index_length) as size FROM information_schema.tables WHERE table_schema = ?', [$dbName]); $size = $result[0]->size ?? 0; } $status = 'connected'; } catch (\Exception $e) { $status = 'error'; } return [ 'connection' => $connection, 'status' => $status, 'size' => $size, 'size_formatted' => $this->formatBytes($size), ]; } /** * Get queue information. */ protected function getQueueInfo(): array { $driver = config('queue.default'); $pending = 0; $failed = 0; try { // Count pending jobs if ($driver === 'database') { $pending = DB::table('jobs')->count(); } // Count failed jobs $failed = DB::table('failed_jobs')->count(); } catch (\Exception $e) { // Tables may not exist } return [ 'driver' => $driver, 'pending_jobs' => $pending, 'failed_jobs' => $failed, ]; } /** * Get cache information. */ protected function getCacheInfo(): array { $driver = config('cache.default'); $status = 'unknown'; try { $testKey = 'server_resource_test_'.uniqid(); Cache::put($testKey, true, 10); $status = Cache::get($testKey) === true ? 'working' : 'error'; Cache::forget($testKey); } catch (\Exception $e) { $status = 'error'; } return [ 'driver' => $driver, 'status' => $status, ]; } /** * Format bytes to human readable format. */ protected function formatBytes(int $bytes, int $precision = 2): string { if ($bytes === 0) { return '0 B'; } $units = ['B', 'KB', 'MB', 'GB', 'TB']; $base = log($bytes, 1024); $index = min((int) floor($base), count($units) - 1); return round(pow(1024, $base - floor($base)), $precision).' '.$units[$index]; } /** * Format uptime seconds to human readable format. */ protected function formatUptime(int $seconds): string { $days = floor($seconds / 86400); $hours = floor(($seconds % 86400) / 3600); $minutes = floor(($seconds % 3600) / 60); $parts = []; if ($days > 0) { $parts[] = $days.'d'; } if ($hours > 0) { $parts[] = $hours.'h'; } if ($minutes > 0) { $parts[] = $minutes.'m'; } return empty($parts) ? '0m' : implode(' ', $parts); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Services/TelemetryService.php
app/Services/TelemetryService.php
<?php namespace App\Services; use App\Models\Monitor; use Illuminate\Support\Facades\DB; class TelemetryService { public function __construct( protected InstanceIdService $instanceIdService ) {} /** * Check if telemetry is enabled. */ public function isEnabled(): bool { return config('telemetry.enabled', false); } /** * Get the telemetry endpoint URL. */ public function getEndpoint(): string { return config('telemetry.endpoint'); } /** * Collect all telemetry data. * * IMPORTANT: Only non-identifying, aggregate data is collected. * No URLs, user emails, IP addresses, or other personal data. */ public function collectData(): array { return [ // Anonymous instance identifier 'instance_id' => $this->instanceIdService->getInstanceId(), // Version information 'versions' => $this->getVersionInfo(), // Aggregate statistics (counts only) 'stats' => $this->getAggregateStats(), // System information 'system' => $this->getSystemInfo(), // Ping metadata 'ping' => [ 'timestamp' => now()->toIso8601String(), 'timezone' => config('app.timezone'), ], ]; } /** * Get version information. */ protected function getVersionInfo(): array { return [ 'app' => config('app.last_update', 'unknown'), 'php' => PHP_VERSION, 'laravel' => app()->version(), ]; } /** * Get aggregate statistics (counts only, no identifying data). */ protected function getAggregateStats(): array { // Use withoutGlobalScopes to get accurate counts $monitorCount = Monitor::withoutGlobalScopes()->count(); $publicMonitorCount = Monitor::withoutGlobalScopes() ->where('is_public', true) ->count(); $userCount = DB::table('users')->count(); $statusPageCount = DB::table('status_pages')->count(); return [ 'monitors_total' => $monitorCount, 'monitors_public' => $publicMonitorCount, 'users_total' => $userCount, 'status_pages_total' => $statusPageCount, 'install_date' => $this->instanceIdService->getInstallDate(), ]; } /** * Get non-identifying system information. */ protected function getSystemInfo(): array { return [ 'os_family' => PHP_OS_FAMILY, // 'Linux', 'Darwin', 'Windows' 'os_type' => $this->getOsType(), 'database_driver' => config('database.default'), 'queue_driver' => config('queue.default'), 'cache_driver' => config('cache.default'), ]; } /** * Get a simplified OS type string. */ protected function getOsType(): string { return match (PHP_OS_FAMILY) { 'Darwin' => 'macOS', 'Windows' => 'Windows', 'Linux' => $this->detectLinuxDistro(), default => 'Other', }; } /** * Detect Linux distribution (generic categorization only). */ protected function detectLinuxDistro(): string { if (! is_readable('/etc/os-release')) { return 'Linux'; } $content = file_get_contents('/etc/os-release'); // Only detect broad categories, not specific versions if (str_contains($content, 'Ubuntu')) { return 'Ubuntu'; } if (str_contains($content, 'Debian')) { return 'Debian'; } if (str_contains($content, 'Alpine')) { return 'Alpine'; } if (str_contains($content, 'CentOS') || str_contains($content, 'Red Hat')) { return 'RHEL-based'; } return 'Linux'; } /** * Get the current telemetry settings for display. */ public function getSettings(): array { return [ 'enabled' => $this->isEnabled(), 'endpoint' => $this->getEndpoint(), 'frequency' => config('telemetry.frequency'), 'instance_id' => $this->instanceIdService->getInstanceId(), 'install_date' => $this->instanceIdService->getInstallDate(), 'last_ping' => $this->getLastPingTime(), 'debug' => config('telemetry.debug'), ]; } /** * Get the last ping timestamp from cache. */ public function getLastPingTime(): ?string { return cache()->get('telemetry:last_ping'); } /** * Record a successful ping. */ public function recordPing(): void { cache()->forever('telemetry:last_ping', now()->toIso8601String()); } /** * Preview the telemetry data that would be sent. * Useful for transparency in the admin UI. */ public function previewData(): array { return $this->collectData(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Notifications/MonitorStatusChanged.php
app/Notifications/MonitorStatusChanged.php
<?php namespace App\Notifications; use App\Services\EmailRateLimitService; use App\Services\TelegramRateLimitService; use App\Services\TwitterRateLimitService; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Illuminate\Support\Facades\Log; use NotificationChannels\Telegram\TelegramMessage; use NotificationChannels\Twitter\TwitterChannel; use NotificationChannels\Twitter\TwitterStatusUpdate; class MonitorStatusChanged extends Notification implements ShouldQueue { use Queueable; /** * Create a new notification instance. */ public function __construct(public $data) { // } /** * Check if Twitter credentials are configured. */ protected function isTwitterConfigured(): bool { return ! empty(config('services.twitter.consumer_key')) && ! empty(config('services.twitter.consumer_secret')) && ! empty(config('services.twitter.access_token')) && ! empty(config('services.twitter.access_secret')); } /** * Get the notification's delivery channels. * * @return array<int, string> */ public function via(object $notifiable): array { // Ambil semua channel yang aktif dari database $channels = $notifiable->notificationChannels() ->where('is_enabled', true) ->pluck('type') ->toArray(); // Map user-enabled channels $userChannels = collect($channels)->map(function ($channel) use ($notifiable) { // Check email rate limit before adding mail channel if ($channel === 'email') { $emailRateLimitService = app(EmailRateLimitService::class); if (! $emailRateLimitService->canSendEmail($notifiable, 'monitor_status_changed')) { return null; // Skip email channel if rate limited } } return match ($channel) { 'telegram' => $notifiable->notificationChannels()->where('type', 'telegram')->where('is_enabled', true)->exists() ? 'telegram' : null, 'email' => 'mail', 'slack' => 'slack', 'sms' => 'nexmo', default => null, }; })->filter(); // Add Twitter as system notification only for DOWN events if configured and not rate limited $allChannels = $userChannels; if ($this->data['status'] === 'DOWN') { if (! $this->isTwitterConfigured()) { Log::debug('Twitter channel skipped: credentials not configured'); } else { $twitterRateLimitService = app(TwitterRateLimitService::class); if ($twitterRateLimitService->shouldSendNotification($notifiable, null)) { $allChannels = $userChannels->push(TwitterChannel::class); } else { Log::info('Twitter channel excluded due to rate limit', [ 'user_id' => $notifiable->id, 'monitor_status' => $this->data['status'] ?? null, ]); } } } return $allChannels->unique()->values()->all(); } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { // Check email rate limit $emailRateLimitService = app(EmailRateLimitService::class); if (! $emailRateLimitService->canSendEmail($notifiable, 'monitor_status_changed')) { Log::warning('Email notification rate limited', [ 'user_id' => $notifiable->id, 'email' => $notifiable->email, 'notification_type' => 'monitor_status_changed', 'monitor_id' => $this->data['id'] ?? null, 'status' => $this->data['status'] ?? null, 'remaining_emails' => $emailRateLimitService->getRemainingEmailCount($notifiable), ]); // Return null to skip sending the email return null; } // Extract hostname from URL $parsedUrl = parse_url($this->data['url']); $host = $parsedUrl['host'] ?? $this->data['url']; // Log the email being sent $emailRateLimitService->logEmailSent($notifiable, 'monitor_status_changed', [ 'monitor_id' => $this->data['id'] ?? null, 'url' => $host, 'status' => $this->data['status'] ?? null, ]); // Check if user is approaching limit and add a warning $message = (new MailMessage) ->subject("Website Status: {$this->data['status']}") ->greeting("Halo, {$notifiable->name}") ->line('Website berikut mengalami perubahan status:') ->line("🔗 URL: {$host}") ->line("⚠️ Status: {$this->data['status']}"); // Add warning if approaching daily limit if ($emailRateLimitService->isApproachingLimit($notifiable)) { $remaining = $emailRateLimitService->getRemainingEmailCount($notifiable); $message->line('') ->line("⚠️ Perhatian: Anda memiliki {$remaining} email notifikasi tersisa untuk hari ini (batas: {$emailRateLimitService->getDailyLimit()} per hari)."); } $message->action('Lihat Detail', url('/monitors/'.$this->data['id'])) ->line('Kunjungi [Uptime Kita]('.url('/').') untuk informasi lebih lanjut.') ->salutation('Terima kasih,'); return $message; } public function toTelegram($notifiable) { // Ambil channel Telegram user $telegramChannel = $notifiable->notificationChannels() ->where('type', 'telegram') ->where('is_enabled', true) ->first(); if (! $telegramChannel) { return; } // Use the rate limiting service $rateLimitService = app(TelegramRateLimitService::class); // Check if we should send the notification if (! $rateLimitService->shouldSendNotification($notifiable, $telegramChannel)) { Log::info('Telegram notification rate limited', [ 'user_id' => $notifiable->id, 'telegram_destination' => $telegramChannel->destination, 'monitor_id' => $this->data['id'] ?? null, 'status' => $this->data['status'] ?? null, ]); return; } try { $statusEmoji = $this->data['status'] === 'DOWN' ? '🔴' : '🟢'; $statusText = $this->data['status'] === 'DOWN' ? 'Website DOWN' : 'Website UP'; // Extract hostname from URL $parsedUrl = parse_url($this->data['url']); $host = $parsedUrl['host'] ?? $this->data['url']; // if monitor is public, use public url if (@$this->data['is_public']) { $monitorUrl = config('app.url').'/m/'.$host; } else { $monitorUrl = config('app.url').'/monitor/'.$this->data['id']; } $message = TelegramMessage::create() ->to($telegramChannel->destination) ->content("{$statusEmoji} *{$statusText}*\n\nURL: `{$host}`\nStatus: *{$this->data['status']}*") ->options(['parse_mode' => 'Markdown']) ->button('View Monitor', $monitorUrl) ->button('Open Website', $this->data['url']); // Track successful notification $rateLimitService->trackSuccessfulNotification($notifiable, $telegramChannel); return $message; } catch (\Exception $e) { // If we get a 429 error, track it for backoff if (str_contains($e->getMessage(), '429') || str_contains($e->getMessage(), 'Too Many Requests')) { $rateLimitService->trackFailedNotification($notifiable, $telegramChannel); Log::error('Telegram notification failed with 429 error', [ 'user_id' => $notifiable->id, 'telegram_destination' => $telegramChannel->destination, 'error' => $e->getMessage(), ]); } else { Log::error('Telegram notification failed', [ 'user_id' => $notifiable->id, 'telegram_destination' => $telegramChannel->destination, 'error' => $e->getMessage(), ]); } // Re-throw the exception so Laravel can handle it throw $e; } } public function toTwitter($notifiable) { try { // Check if Twitter credentials are configured if (! $this->isTwitterConfigured()) { Log::debug('Twitter notification skipped: credentials not configured'); return new TwitterStatusUpdate(''); } // check if monitor is public if (! @$this->data['is_public']) { return null; } // Use the rate limiting service $rateLimitService = app(TwitterRateLimitService::class); // Double-check rate limit at the time of sending // This handles race conditions between via() and toTwitter() calls if (! $rateLimitService->shouldSendNotification($notifiable, null)) { Log::info('Twitter notification rate limited in toTwitter method', [ 'user_id' => $notifiable->id, 'monitor_id' => $this->data['id'] ?? null, 'status' => $this->data['status'] ?? null, ]); // Return empty tweet instead of null to avoid TypeError // The Twitter API will reject empty tweets, effectively skipping the notification return new TwitterStatusUpdate(''); } $statusEmoji = $this->data['status'] === 'DOWN' ? '🔴' : '🟢'; $statusText = $this->data['status'] === 'DOWN' ? 'DOWN' : 'UP'; $parsedUrl = parse_url($this->data['url']); $host = $parsedUrl['host']; // Create tweet content $tweetContent = "{$statusEmoji} Monitor Alert: {$host} is {$statusText}\n\n"; // Add timestamp $tweetContent .= 'Time: '.now()->format('Y-m-d H:i:s')." UTC\n"; // Add hashtags $tweetContent .= '#UptimeKita #UptimeMonitoring #WebsiteStatus'; // If monitor is public, add link if (@$this->data['is_public']) { $monitorUrl = config('app.url').'/m/'.$host; $tweetContent .= "\n\nDetails: {$monitorUrl}"; } // Track successful notification $rateLimitService->trackSuccessfulNotification($notifiable, null); return new TwitterStatusUpdate($tweetContent); } catch (\Exception $e) { Log::error('Twitter notification failed', [ 'user_id' => $notifiable->id, 'error' => $e->getMessage(), ]); throw $e; } } /** * Get the array representation of the notification. * * @return array<string, mixed> */ public function toArray(object $notifiable): array { return [ 'id' => $this->data['id'], 'url' => $this->data['url'], 'status' => $this->data['status'], 'message' => $this->data['message'], ]; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/CalculateMonitorStatistics.php
app/Console/Commands/CalculateMonitorStatistics.php
<?php namespace App\Console\Commands; use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\MonitorStatistic; use Carbon\Carbon; use Illuminate\Console\Command; class CalculateMonitorStatistics extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'monitor:calculate-statistics {monitor?}'; /** * The console command description. * * @var string */ protected $description = 'Calculate and cache monitor statistics for efficient public page loading'; /** * Execute the console command. */ public function handle() { $monitorId = $this->argument('monitor'); if ($monitorId) { $monitors = Monitor::where('id', $monitorId)->where('is_public', true)->get(); } else { $monitors = Monitor::where('is_public', true)->where('uptime_check_enabled', true)->get(); } if ($monitors->isEmpty()) { $this->warn('No public monitors found.'); return; } $this->info("Calculating statistics for {$monitors->count()} monitor(s)..."); $progressBar = $this->output->createProgressBar($monitors->count()); foreach ($monitors as $monitor) { $this->calculateStatistics($monitor); $progressBar->advance(); } $progressBar->finish(); $this->newLine(); $this->info('Monitor statistics calculated successfully!'); } private function calculateStatistics(Monitor $monitor): void { $now = now(); // Calculate uptime percentages for different periods $uptimeStats = [ '1h' => $this->calculateUptimePercentage($monitor, $now->copy()->subHour()), '24h' => $this->calculateUptimePercentage($monitor, $now->copy()->subDay()), '7d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(30)), '90d' => $this->calculateUptimePercentage($monitor, $now->copy()->subDays(90)), ]; // Calculate response time stats for last 24h $responseTimeStats = $this->calculateResponseTimeStats($monitor, $now->copy()->subDay()); // Calculate incident counts $incidentCounts = [ '24h' => $this->calculateIncidentCount($monitor, $now->copy()->subDay()), '7d' => $this->calculateIncidentCount($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateIncidentCount($monitor, $now->copy()->subDays(30)), ]; // Calculate total checks $totalChecks = [ '24h' => $this->calculateTotalChecks($monitor, $now->copy()->subDay()), '7d' => $this->calculateTotalChecks($monitor, $now->copy()->subDays(7)), '30d' => $this->calculateTotalChecks($monitor, $now->copy()->subDays(30)), ]; // Get recent history for last 100 minutes $recentHistory = $this->getRecentHistory($monitor); // Upsert statistics record MonitorStatistic::updateOrCreate( ['monitor_id' => $monitor->id], [ 'uptime_1h' => $uptimeStats['1h'], 'uptime_24h' => $uptimeStats['24h'], 'uptime_7d' => $uptimeStats['7d'], 'uptime_30d' => $uptimeStats['30d'], 'uptime_90d' => $uptimeStats['90d'], 'avg_response_time_24h' => $responseTimeStats['avg'], 'min_response_time_24h' => $responseTimeStats['min'], 'max_response_time_24h' => $responseTimeStats['max'], 'incidents_24h' => $incidentCounts['24h'], 'incidents_7d' => $incidentCounts['7d'], 'incidents_30d' => $incidentCounts['30d'], 'total_checks_24h' => $totalChecks['24h'], 'total_checks_7d' => $totalChecks['7d'], 'total_checks_30d' => $totalChecks['30d'], 'recent_history_100m' => $recentHistory, 'calculated_at' => $now, ] ); } private function calculateUptimePercentage(Monitor $monitor, Carbon $startDate): float { $histories = MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->get(); if ($histories->isEmpty()) { return 100.0; } $upCount = $histories->where('uptime_status', 'up')->count(); $totalCount = $histories->count(); return round(($upCount / $totalCount) * 100, 2); } private function calculateResponseTimeStats(Monitor $monitor, Carbon $startDate): array { $histories = MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->whereNotNull('response_time') ->get(); if ($histories->isEmpty()) { return ['avg' => null, 'min' => null, 'max' => null]; } $responseTimes = $histories->pluck('response_time'); return [ 'avg' => (int) round($responseTimes->avg()), 'min' => $responseTimes->min(), 'max' => $responseTimes->max(), ]; } private function calculateIncidentCount(Monitor $monitor, Carbon $startDate): int { return MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->where('uptime_status', '!=', 'up') ->count(); } private function calculateTotalChecks(Monitor $monitor, Carbon $startDate): int { return MonitorHistory::where('monitor_id', $monitor->id) ->where('created_at', '>=', $startDate) ->count(); } private function getRecentHistory(Monitor $monitor): array { $oneHundredMinutesAgo = now()->subMinutes(100); // Get unique history IDs using raw SQL to ensure only one record per minute $sql = " SELECT id FROM ( SELECT id, created_at, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime('%Y-%m-%d %H:%M', created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories WHERE monitor_id = ? ) ranked WHERE rn = 1 ORDER BY created_at DESC LIMIT 100 "; $uniqueIds = \DB::select($sql, [$monitor->id]); $ids = array_column($uniqueIds, 'id'); // Get unique histories and filter by time $histories = MonitorHistory::whereIn('id', $ids) ->where('created_at', '>=', $oneHundredMinutesAgo) ->orderBy('created_at', 'desc') ->get(); // Transform to a lighter format for JSON storage return $histories->map(function ($history) { return [ 'created_at' => $history->created_at->toISOString(), 'uptime_status' => $history->uptime_status, 'response_time' => $history->response_time, 'message' => $history->message, ]; })->toArray(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/FastCleanupDuplicateHistories.php
app/Console/Commands/FastCleanupDuplicateHistories.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class FastCleanupDuplicateHistories extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'monitor:fast-cleanup-duplicates {--force : Actually perform the cleanup}'; /** * The console command description. * * @var string */ protected $description = 'Fast cleanup of duplicate monitor histories using SQL'; /** * Execute the console command. */ public function handle() { $force = $this->option('force'); if (! $force) { $this->warn('This is a DRY RUN. Use --force to actually perform the cleanup.'); } $this->info('Starting fast cleanup of duplicate monitor histories...'); // Count records before $beforeCount = DB::table('monitor_histories')->count(); $this->info("Total records before: {$beforeCount}"); if ($force) { // Step 1: Create backup table name with timestamp $backupTable = 'monitor_histories_backup_'.now()->format('Y_m_d_H_i_s'); $this->info("Creating backup table: {$backupTable}"); // Create backup table DB::statement("CREATE TABLE {$backupTable} AS SELECT * FROM monitor_histories"); // Step 2: Create temporary table with unique records $this->info('Creating temporary table with deduplicated records...'); DB::statement('DROP TABLE IF EXISTS temp_unique_histories'); DB::statement(' CREATE TEMPORARY TABLE temp_unique_histories AS SELECT * FROM ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime("%Y-%m-%d %H:%M", created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories ) ranked WHERE rn = 1 '); // Step 3: Replace original table contents $this->info('Replacing original table with unique records...'); // Clear original table and insert unique records DB::transaction(function () { DB::statement('DELETE FROM monitor_histories'); DB::statement(' INSERT INTO monitor_histories (id, monitor_id, uptime_status, message, created_at, updated_at, response_time, status_code, checked_at) SELECT id, monitor_id, uptime_status, message, created_at, updated_at, response_time, status_code, checked_at FROM temp_unique_histories '); }); // Clean up temp table DB::statement('DROP TABLE temp_unique_histories'); // Count records after $afterCount = DB::table('monitor_histories')->count(); $deleted = $beforeCount - $afterCount; $this->info('Cleanup completed!'); $this->info("Records before: {$beforeCount}"); $this->info("Records after: {$afterCount}"); $this->info("Records removed: {$deleted}"); $this->info("Backup saved as: {$backupTable}"); } else { // Just count duplicates for dry run $duplicates = DB::select(' SELECT COUNT(*) as duplicate_count FROM ( SELECT monitor_id, strftime("%Y-%m-%d %H:%M", created_at) as minute_key, COUNT(*) - 1 as extras FROM monitor_histories GROUP BY monitor_id, strftime("%Y-%m-%d %H:%M", created_at) HAVING COUNT(*) > 1 ) dups ')[0]; $wouldDelete = DB::select(' SELECT SUM(cnt - 1) as total_duplicates FROM ( SELECT COUNT(*) as cnt FROM monitor_histories GROUP BY monitor_id, strftime("%Y-%m-%d %H:%M", created_at) HAVING COUNT(*) > 1 ) grouped ')[0]; $this->info('DRY RUN Results:'); $this->info("- Total records: {$beforeCount}"); $this->info('- Would delete: '.($wouldDelete->total_duplicates ?? 0).' duplicate records'); $this->info('- Would keep: '.($beforeCount - ($wouldDelete->total_duplicates ?? 0)).' unique records'); } return 0; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/RunCronlessSchedulerCommand.php
app/Console/Commands/RunCronlessSchedulerCommand.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; class RunCronlessSchedulerCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'schedule:run-cronless-safe {--frequency=60 : Frequency in seconds} {--max-memory=512 : Maximum memory in MB before restart} {--max-runtime=86400 : Maximum runtime in seconds (24 hours)}'; /** * The console command description. * * @var string */ protected $description = 'Run cronless scheduler with error handling and monitoring'; private int $startTime; private int $maxMemory; private int $maxRuntime; /** * Execute the console command. */ public function handle(): int { $this->startTime = time(); $this->maxMemory = (int) $this->option('max-memory') * 1024 * 1024; // Convert to bytes $this->maxRuntime = (int) $this->option('max-runtime'); $this->info('Starting cronless scheduler with safety features...'); $this->info("Max Memory: {$this->option('max-memory')}MB"); $this->info("Max Runtime: {$this->maxRuntime} seconds"); // Register shutdown handler register_shutdown_function(function () { $error = error_get_last(); if ($error !== null && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) { Log::error('Cronless scheduler shutdown due to fatal error', [ 'error' => $error, 'memory_usage' => memory_get_usage(true), 'peak_memory' => memory_get_peak_usage(true), 'runtime' => time() - $this->startTime, ]); } }); // Set error handler set_error_handler(function ($severity, $message, $file, $line) { if (error_reporting() & $severity) { Log::warning('Cronless scheduler error', [ 'message' => $message, 'file' => $file, 'line' => $line, 'severity' => $severity, ]); } }); try { // Run scheduler with periodic checks $this->runSchedulerLoop(); } catch (\Throwable $e) { Log::error('Cronless scheduler crashed', [ 'exception' => $e->getMessage(), 'trace' => $e->getTraceAsString(), 'memory_usage' => memory_get_usage(true), 'runtime' => time() - $this->startTime, ]); $this->error('Scheduler crashed: '.$e->getMessage()); return 1; } return 0; } private function runSchedulerLoop(): void { $iteration = 0; while (true) { $iteration++; // Check memory usage $memoryUsage = memory_get_usage(true); if ($memoryUsage > $this->maxMemory) { $memoryMB = round($memoryUsage / 1024 / 1024, 2); Log::warning('Cronless scheduler stopping: memory limit reached', [ 'memory_usage' => $memoryMB.'MB', 'max_memory' => $this->option('max-memory').'MB', 'iteration' => $iteration, ]); $this->warn("Memory limit reached ({$memoryMB}MB), exiting for restart..."); break; } // Check runtime $runtime = time() - $this->startTime; if ($runtime > $this->maxRuntime) { Log::info('Cronless scheduler stopping: max runtime reached', [ 'runtime' => $runtime, 'max_runtime' => $this->maxRuntime, 'iteration' => $iteration, ]); $this->info('Max runtime reached, exiting for restart...'); break; } try { // Log every 10 iterations if ($iteration % 10 === 0) { $memoryMB = round($memoryUsage / 1024 / 1024, 2); $this->comment("[Iteration {$iteration}] Memory: {$memoryMB}MB, Runtime: {$runtime}s"); } // Run the actual scheduler command $exitCode = $this->call('schedule:run'); if ($exitCode !== 0) { Log::warning('Schedule:run returned non-zero exit code', [ 'exit_code' => $exitCode, 'iteration' => $iteration, ]); } } catch (\Throwable $e) { Log::error('Error in scheduler iteration', [ 'exception' => $e->getMessage(), 'trace' => $e->getTraceAsString(), 'iteration' => $iteration, ]); $this->error("Iteration {$iteration} failed: ".$e->getMessage()); // Continue running despite errors } // Sleep for frequency seconds sleep((int) $this->option('frequency')); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/CleanupDuplicateMonitorHistories.php
app/Console/Commands/CleanupDuplicateMonitorHistories.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class CleanupDuplicateMonitorHistories extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'monitor:cleanup-duplicates {--dry-run : Show what would be deleted without actually deleting}'; /** * The console command description. * * @var string */ protected $description = 'Remove duplicate monitor history records, keeping only the latest record per monitor per minute'; /** * Execute the console command. */ public function handle() { $dryRun = $this->option('dry-run'); $this->info('Cleaning up duplicate monitor histories...'); if ($dryRun) { $this->warn('DRY RUN MODE - No records will be actually deleted'); } // Count total records before cleanup $totalBefore = DB::table('monitor_histories')->count(); $this->info("Total records before cleanup: {$totalBefore}"); // Find all duplicate groups $duplicates = DB::select(' SELECT monitor_id, strftime("%Y-%m-%d %H:%M", created_at) as minute_key, COUNT(*) as count FROM monitor_histories GROUP BY monitor_id, strftime("%Y-%m-%d %H:%M", created_at) HAVING count > 1 ORDER BY count DESC '); $this->info('Found '.count($duplicates).' minute periods with duplicate records'); if (empty($duplicates)) { $this->info('No duplicates found!'); return; } $totalDeleted = 0; $progressBar = $this->output->createProgressBar(count($duplicates)); foreach ($duplicates as $duplicate) { // Get IDs of records to keep (latest) and delete (others) $records = DB::select(' SELECT id, created_at FROM monitor_histories WHERE monitor_id = ? AND strftime("%Y-%m-%d %H:%M", created_at) = ? ORDER BY created_at DESC, id DESC ', [$duplicate->monitor_id, $duplicate->minute_key]); // Keep the first (latest) record, delete the rest $keepId = $records[0]->id; $deleteIds = array_slice(array_column($records, 'id'), 1); if (! empty($deleteIds) && ! $dryRun) { $deleted = DB::table('monitor_histories') ->whereIn('id', $deleteIds) ->delete(); $totalDeleted += $deleted; } elseif (! empty($deleteIds)) { // Dry run - just count what would be deleted $totalDeleted += count($deleteIds); } $progressBar->advance(); } $progressBar->finish(); $this->newLine(); if ($dryRun) { $this->info("DRY RUN: Would delete {$totalDeleted} duplicate records"); } else { $this->info("Deleted {$totalDeleted} duplicate records"); $totalAfter = DB::table('monitor_histories')->count(); $this->info("Total records after cleanup: {$totalAfter}"); } // Check if there are still duplicates $remainingDuplicates = DB::select(' SELECT COUNT(*) as count FROM ( SELECT monitor_id, strftime("%Y-%m-%d %H:%M", created_at) as minute_key, COUNT(*) as cnt FROM monitor_histories GROUP BY monitor_id, strftime("%Y-%m-%d %H:%M", created_at) HAVING cnt > 1 ) duplicates ')[0]->count; if ($remainingDuplicates > 0) { $this->warn("Warning: {$remainingDuplicates} duplicate groups still remain"); } else { $this->info('✅ All duplicates successfully cleaned up!'); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/CheckDatabaseHealth.php
app/Console/Commands/CheckDatabaseHealth.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class CheckDatabaseHealth extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'db:health-check {--repair : Attempt to repair issues}'; /** * The console command description. * * @var string */ protected $description = 'Check SQLite database health and optionally repair issues'; /** * Execute the console command. */ public function handle() { $this->info('Checking database health...'); try { // Run integrity check $integrityCheck = DB::select('PRAGMA integrity_check'); if ($integrityCheck[0]->integrity_check === 'ok') { $this->info('✓ Database integrity check passed'); // Check journal mode $journalMode = DB::select('PRAGMA journal_mode'); if (! empty($journalMode)) { $mode = $journalMode[0]->journal_mode ?? 'unknown'; $this->info("Journal mode: {$mode}"); if ($mode !== 'wal') { $this->warn("⚠ Consider using WAL mode for better concurrency (current: {$mode})"); } } // Get database stats $pageCount = DB::select('PRAGMA page_count'); $pageSize = DB::select('PRAGMA page_size'); if (! empty($pageCount) && ! empty($pageSize)) { $pages = $pageCount[0]->page_count ?? 0; $size = $pageSize[0]->page_size ?? 0; $dbSize = ($pages * $size) / (1024 * 1024); $this->info(sprintf('Database size: %.2f MB', $dbSize)); } // Check for locked tables $busyTimeout = DB::select('PRAGMA busy_timeout'); if (! empty($busyTimeout)) { $timeout = $busyTimeout[0]->timeout ?? $busyTimeout[0]->busy_timeout ?? 'unknown'; $this->info("Busy timeout: {$timeout}ms"); } if ($this->option('repair')) { $this->performOptimizations(); } return Command::SUCCESS; } else { $this->error('✗ Database integrity check failed!'); foreach ($integrityCheck as $error) { $this->error($error->integrity_check); } Log::critical('Database integrity check failed', [ 'errors' => $integrityCheck, ]); if ($this->option('repair')) { $this->warn('Attempting repair...'); $this->attemptRepair(); } return Command::FAILURE; } } catch (\Exception $e) { $this->error('Failed to check database health: '.$e->getMessage()); Log::error('Database health check failed', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); return Command::FAILURE; } } private function performOptimizations() { $this->info('Performing optimizations...'); try { // Vacuum database DB::statement('VACUUM'); $this->info('✓ Database vacuumed'); // Analyze tables DB::statement('ANALYZE'); $this->info('✓ Database analyzed'); // Set optimal pragmas DB::statement('PRAGMA journal_mode = WAL'); DB::statement('PRAGMA synchronous = NORMAL'); DB::statement('PRAGMA busy_timeout = 5000'); DB::statement('PRAGMA cache_size = -64000'); $this->info('✓ Optimizations applied'); } catch (\Exception $e) { $this->error('Optimization failed: '.$e->getMessage()); } } private function attemptRepair() { $dbPath = database_path('database.sqlite'); $backupPath = database_path('database_backup_'.date('Y-m-d_H-i-s').'.sqlite'); $this->info("Creating backup at: {$backupPath}"); copy($dbPath, $backupPath); $this->info('Attempting recovery...'); $recoveryPath = database_path('database_recovered.sqlite'); // Try to recover using sqlite3 command $command = "sqlite3 {$dbPath} '.recover' | sqlite3 {$recoveryPath}"; exec($command.' 2>&1', $output, $returnCode); if ($returnCode === 0 && file_exists($recoveryPath)) { $this->info('✓ Recovery successful! New database created at: '.$recoveryPath); $this->warn('To use the recovered database:'); $this->warn('1. php artisan down'); $this->warn("2. mv {$dbPath} {$dbPath}.corrupted"); $this->warn("3. mv {$recoveryPath} {$dbPath}"); $this->warn('4. php artisan up'); } else { $this->error('Recovery failed. Please restore from backup.'); } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/OptimizeSqliteDatabase.php
app/Console/Commands/OptimizeSqliteDatabase.php
<?php namespace App\Console\Commands; use App\Models\MonitorLog; use Exception; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class OptimizeSqliteDatabase extends Command { /** * The name and signature of the console command. */ protected $signature = 'sqlite:optimize {--prune-days=90 : Delete logs older than N days}'; /** * The console command description. */ protected $description = 'Optimize SQLite database: prune old logs, vacuum, analyze, and tune pragmas.'; /** * Execute the console command. */ public function handle(): int { $dbPath = database_path('database.sqlite'); $this->info("🧩 Starting optimization for: {$dbPath}"); try { // 1️⃣ Delete old logs (if table exists) $days = (int) $this->option('prune-days'); if (DB::table('sqlite_master')->where('name', 'monitor_logs')->exists()) { $count = MonitorLog::where('created_at', '<', now()->subDays($days))->count(); if ($count > 0) { $this->info("🧹 Deleting {$count} old monitor_logs entries (>{ $days } days)..."); MonitorLog::where('created_at', '<', now()->subDays($days))->delete(); } else { $this->info('✅ No old monitor_logs to delete.'); } } // 2️⃣ Optimize PRAGMA settings $this->info('⚙️ Applying SQLite PRAGMA tuning...'); DB::statement('PRAGMA journal_mode = WAL;'); DB::statement('PRAGMA synchronous = NORMAL;'); DB::statement('PRAGMA temp_store = MEMORY;'); DB::statement('PRAGMA cache_size = -20000;'); // 3️⃣ Analyze query planner $this->info('🔍 Running ANALYZE...'); DB::statement('ANALYZE;'); // 4️⃣ Compact database $this->info('💾 Running VACUUM (this may take a while)...'); DB::statement('VACUUM;'); // 5️⃣ Log and notify $msg = "✅ SQLite optimization completed successfully for {$dbPath}"; $this->info($msg); Log::info($msg); if (app()->bound('sentry')) { app('sentry')->captureMessage($msg); } return Command::SUCCESS; } catch (Exception $e) { $this->error('❌ Optimization failed: '.$e->getMessage()); Log::error('SQLite optimization failed', ['error' => $e]); if (app()->bound('sentry')) { app('sentry')->captureException($e); } return Command::FAILURE; } } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/CalculateDailyUptimeCommand.php
app/Console/Commands/CalculateDailyUptimeCommand.php
<?php namespace App\Console\Commands; use App\Jobs\CalculateSingleMonitorUptimeJob; use App\Models\Monitor; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; class CalculateDailyUptimeCommand extends Command { /** * The console command name. * * @var string */ protected $signature = 'uptime:calculate-daily {date? : The date to calculate uptime for (Y-m-d format, defaults to today)} {--monitor-id= : Calculate for specific monitor ID only} {--force : Force recalculation even if already calculated}'; /** * The console command description. * * @var string */ protected $description = 'Calculate daily uptime for all monitors or a specific monitor for a given date'; /** * Execute the console command. * * @return int */ public function handle() { $date = $this->argument('date') ?? Carbon::today()->toDateString(); $monitorId = $this->option('monitor-id'); $force = $this->option('force'); // Validate monitor ID if provided if ($monitorId !== null) { if (! is_numeric($monitorId)) { $this->error("Invalid monitor ID: {$monitorId}. Monitor ID must be a number."); return 1; } if ((int) $monitorId < 0) { $this->error("Invalid monitor ID: {$monitorId}. Monitor ID must be a number."); return 1; } } // Validate date format if (! $this->isValidDate($date)) { $this->error("Invalid date format: {$date}. Please use Y-m-d format (e.g., 2024-01-15)"); return 1; } $this->info("Starting daily uptime calculation for date: {$date}"); try { $processedCount = 0; if ($monitorId) { // Calculate for specific monitor $result = $this->calculateForSpecificMonitor($monitorId, $date, $force); if ($result === false) { return 1; } $processedCount = $result; } else { // Calculate for all monitors $processedCount = $this->calculateForAllMonitors($date, $force); } if ($processedCount > 0) { $this->info('Daily uptime calculation completed'); if (! $monitorId) { $this->info("Total monitors processed: {$processedCount}"); } } return 0; } catch (\Exception $e) { $this->error("Failed to dispatch uptime calculation job: {$e->getMessage()}"); Log::error('CalculateDailyUptimeCommand failed', [ 'date' => $date, 'monitor_id' => $monitorId, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); return 1; } } /** * Validate date format */ private function isValidDate(string $date): bool { if (empty($date)) { return false; } try { $parsed = Carbon::createFromFormat('Y-m-d', $date); return $parsed && $parsed->format('Y-m-d') === $date; } catch (\Exception $e) { return false; } } /** * Calculate uptime for a specific monitor */ private function calculateForSpecificMonitor(?string $monitorId, string $date, bool $force) { // Validate monitor exists $monitor = Monitor::find($monitorId); if (! $monitor) { $this->error("Monitor with ID {$monitorId} not found"); return false; } $displayName = $monitor->display_name ?: $monitor->url; $this->info("Calculating uptime for monitor: {$displayName} (ID: {$monitorId})"); // Check if calculation already exists (unless force is used) if (! $force && $this->calculationExists($monitorId, $date)) { $this->warn("Uptime calculation for monitor {$monitorId} on {$date} already exists. Use --force to recalculate."); return 0; } // Dispatch single monitor calculation job $job = new CalculateSingleMonitorUptimeJob((int) $monitorId, $date); dispatch($job); $this->info("Job dispatched for monitor {$monitorId} for date {$date}"); return 1; } /** * Calculate uptime for all monitors */ private function calculateForAllMonitors(string $date, bool $force): int { $this->info("Calculating uptime for all monitors for date: {$date}"); // Get all monitor IDs $monitorIds = Monitor::pluck('id')->toArray(); if (empty($monitorIds)) { $this->info('No monitors found to calculate uptime for'); return 0; } $this->info('Found '.count($monitorIds).' monitors to process'); // If force is used, we'll process all monitors // Otherwise, we'll skip monitors that already have calculations $monitorsToProcess = $force ? $monitorIds : $this->getMonitorsWithoutCalculation($monitorIds, $date); if (empty($monitorsToProcess)) { $this->info('All monitors already have uptime calculations for this date. Use --force to recalculate.'); return 0; } $this->info('Processing '.count($monitorsToProcess).' monitors'); // Dispatch jobs for each monitor foreach ($monitorsToProcess as $monitorId) { $job = new CalculateSingleMonitorUptimeJob($monitorId, $date); dispatch($job); } $this->info('Dispatched '.count($monitorsToProcess).' calculation jobs'); return count($monitorsToProcess); } /** * Check if calculation already exists for a monitor and date */ private function calculationExists(string $monitorId, string $date): bool { return \DB::table('monitor_uptime_dailies') ->where('monitor_id', $monitorId) ->where('date', $date) ->exists(); } /** * Get monitors that don't have calculations for the given date */ private function getMonitorsWithoutCalculation(array $monitorIds, string $date): array { $existingCalculations = \DB::table('monitor_uptime_dailies') ->whereIn('monitor_id', $monitorIds) ->where('date', $date) ->pluck('monitor_id') ->toArray(); return array_diff($monitorIds, $existingCalculations); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/UpdateMaintenanceStatusCommand.php
app/Console/Commands/UpdateMaintenanceStatusCommand.php
<?php namespace App\Console\Commands; use App\Services\MaintenanceWindowService; use Illuminate\Console\Command; class UpdateMaintenanceStatusCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'monitor:update-maintenance-status {--cleanup : Also cleanup expired one-time maintenance windows}'; /** * The console command description. * * @var string */ protected $description = 'Update maintenance status for all monitors based on their maintenance windows'; /** * Execute the console command. */ public function handle(MaintenanceWindowService $maintenanceService): int { $this->info('Updating maintenance status for monitors...'); $updated = $maintenanceService->updateAllMaintenanceStatuses(); $this->info("Updated {$updated} monitor(s) maintenance status."); if ($this->option('cleanup')) { $this->info('Cleaning up expired one-time maintenance windows...'); $cleaned = $maintenanceService->cleanupExpiredWindows(); $this->info("Cleaned up {$cleaned} monitor(s) with expired windows."); } return self::SUCCESS; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Console/Commands/GenerateSitemap.php
app/Console/Commands/GenerateSitemap.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Spatie\Sitemap\SitemapGenerator; class GenerateSitemap extends Command { /** * The console command name. * * @var string */ protected $signature = 'sitemap:generate'; /** * The console command description. * * @var string */ protected $description = 'Generate the sitemap.'; /** * Execute the console command. * * @return mixed */ public function handle() { // modify this to your own needs SitemapGenerator::create(config('app.url')) ->writeToFile(public_path('sitemap.xml')); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/MonitorUptimeDaily.php
app/Models/MonitorUptimeDaily.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class MonitorUptimeDaily extends Model { use HasFactory; protected $fillable = [ 'monitor_id', 'date', 'uptime_percentage', 'avg_response_time', 'min_response_time', 'max_response_time', 'total_checks', 'failed_checks', ]; protected $casts = [ 'date' => 'date', 'uptime_percentage' => 'float', 'avg_response_time' => 'float', 'min_response_time' => 'float', 'max_response_time' => 'float', 'total_checks' => 'integer', 'failed_checks' => 'integer', ]; public function monitor() { return $this->belongsTo(Monitor::class); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/SocialAccount.php
app/Models/SocialAccount.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class SocialAccount extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array<string> */ protected $fillable = [ 'user_id', 'provider_id', 'provider_name', ]; /** * Get the user that owns the social account. */ public function user() { return $this->belongsTo(User::class); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/User.php
app/Models/User.php
<?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { /** @use HasFactory<\Database\Factories\UserFactory> */ use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var list<string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var list<string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } public function socialAccounts(): HasMany { return $this->hasMany(SocialAccount::class); } public function monitors(): BelongsToMany { return $this->belongsToMany(Monitor::class, 'user_monitor')->withPivot('is_active', 'is_pinned'); } public function statusPages(): HasMany { return $this->hasMany(StatusPage::class); } public function notificationChannels(): HasMany { return $this->hasMany(NotificationChannel::class); } public function scopeActive($query) { return $query->whereHas('monitors', function ($query) { $query->where('user_monitor.is_active', true); }); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/MonitorPerformanceHourly.php
app/Models/MonitorPerformanceHourly.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class MonitorPerformanceHourly extends Model { use HasFactory; protected $table = 'monitor_performance_hourly'; protected $fillable = [ 'monitor_id', 'hour', 'avg_response_time', 'p95_response_time', 'p99_response_time', 'success_count', 'failure_count', ]; protected $casts = [ 'hour' => 'datetime', 'avg_response_time' => 'float', 'p95_response_time' => 'float', 'p99_response_time' => 'float', 'success_count' => 'integer', 'failure_count' => 'integer', ]; /** * Get the monitor that owns the performance record. */ public function monitor(): BelongsTo { return $this->belongsTo(Monitor::class); } /** * Get the uptime percentage for this hour. */ public function getUptimePercentageAttribute(): float { $total = $this->success_count + $this->failure_count; if ($total === 0) { return 100.0; } return round(($this->success_count / $total) * 100, 2); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/MonitorIncident.php
app/Models/MonitorIncident.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class MonitorIncident extends Model { use HasFactory; protected $fillable = [ 'monitor_id', 'type', 'started_at', 'ended_at', 'duration_minutes', 'reason', 'response_time', 'status_code', ]; protected $casts = [ 'started_at' => 'datetime', 'ended_at' => 'datetime', 'response_time' => 'integer', 'status_code' => 'integer', 'duration_minutes' => 'integer', ]; /** * Get the monitor that owns the incident. */ public function monitor(): BelongsTo { return $this->belongsTo(Monitor::class); } /** * Scope a query to only include recent incidents. */ public function scopeRecent($query, $days = 7) { return $query->where('started_at', '>=', now()->subDays($days)) ->orderBy('started_at', 'desc'); } /** * Scope a query to only include ongoing incidents. */ public function scopeOngoing($query) { return $query->whereNull('ended_at'); } /** * Calculate and set the duration when ending an incident. */ public function endIncident(): void { $this->ended_at = now(); $this->duration_minutes = $this->started_at->diffInMinutes($this->ended_at); $this->save(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/MonitorStatistic.php
app/Models/MonitorStatistic.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class MonitorStatistic extends Model { use HasFactory; protected $fillable = [ 'monitor_id', 'uptime_1h', 'uptime_24h', 'uptime_7d', 'uptime_30d', 'uptime_90d', 'avg_response_time_24h', 'min_response_time_24h', 'max_response_time_24h', 'incidents_24h', 'incidents_7d', 'incidents_30d', 'total_checks_24h', 'total_checks_7d', 'total_checks_30d', 'recent_history_100m', 'calculated_at', ]; protected $casts = [ 'uptime_1h' => 'float', 'uptime_24h' => 'float', 'uptime_7d' => 'float', 'uptime_30d' => 'float', 'uptime_90d' => 'float', 'recent_history_100m' => 'array', 'calculated_at' => 'datetime', ]; public function monitor(): BelongsTo { return $this->belongsTo(Monitor::class); } /** * Get uptime stats in the format expected by the frontend */ public function getUptimeStatsAttribute(): array { return [ '24h' => $this->uptime_24h, '7d' => $this->uptime_7d, '30d' => $this->uptime_30d, '90d' => $this->uptime_90d, ]; } /** * Get response time stats in the format expected by the frontend */ public function getResponseTimeStatsAttribute(): array { return [ 'average' => $this->avg_response_time_24h, 'min' => $this->min_response_time_24h, 'max' => $this->max_response_time_24h, ]; } /** * Check if statistics are fresh (calculated within the last hour) */ public function isFresh(): bool { return $this->calculated_at && $this->calculated_at->gt(now()->subHour()); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/Monitor.php
app/Models/Monitor.php
<?php namespace App\Models; use App\Services\MaintenanceWindowService; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Support\Carbon; use Spatie\Tags\HasTags; use Spatie\UptimeMonitor\Models\Monitor as SpatieMonitor; use Spatie\Url\Url; class Monitor extends SpatieMonitor { use HasFactory, HasTags; protected $casts = [ 'uptime_check_enabled' => 'boolean', 'certificate_check_enabled' => 'boolean', 'uptime_last_check_date' => 'datetime', 'uptime_status_last_change_date' => 'datetime', 'uptime_check_failed_event_fired_on_date' => 'datetime', 'certificate_expiration_date' => 'datetime', 'expected_status_code' => 'integer', 'max_response_time' => 'integer', 'check_locations' => 'array', 'notification_settings' => 'array', 'maintenance_windows' => 'array', 'maintenance_starts_at' => 'datetime', 'maintenance_ends_at' => 'datetime', 'is_in_maintenance' => 'boolean', 'transient_failures_count' => 'integer', 'confirmation_delay_seconds' => 'integer', 'confirmation_retries' => 'integer', ]; protected $guarded = []; protected $appends = ['raw_url', 'formatted_page_views']; public function scopeEnabled($query) { return $query ->where('uptime_check_enabled', true); } public function getUrlAttribute(): ?Url { if (! isset($this->attributes['url'])) { return null; } return Url::fromString($this->attributes['url']); } public function getFaviconAttribute(): ?string { return $this->url ? "https://s2.googleusercontent.com/s2/favicons?domain={$this->url->getHost()}&sz=32" : null; } public function getRawUrlAttribute(): string { return (string) $this->url; } public function getIsSubscribedAttribute(): bool { if (! auth()->check()) { return false; } // return cache()->remember("is_subscribed_{$this->id}_" . auth()->id(), 60, function () { // Gunakan koleksi jika relasi sudah dimuat (eager loaded) if ($this->relationLoaded('users')) { return $this->users->contains('id', auth()->id()); } // Fallback query jika relasi belum dimuat // Check directly in pivot table to avoid issues with global scopes return \DB::table('user_monitor') ->where('monitor_id', $this->id) ->where('user_id', auth()->id()) ->exists(); // }); } public function getIsPinnedAttribute(): bool { if (! auth()->check()) { return false; } // Use cache for pinned status return cache()->remember("is_pinned_{$this->id}_".auth()->id(), 300, function () { // Use collection if relation is already loaded (eager loaded) if ($this->relationLoaded('users')) { $userPivot = $this->users->firstWhere('id', auth()->id())?->pivot; return $userPivot ? (bool) $userPivot->is_pinned : false; } // Fallback query if relation is not loaded // Check directly in pivot table to avoid issues with global scopes $pivot = \DB::table('user_monitor') ->where('monitor_id', $this->id) ->where('user_id', auth()->id()) ->first(); return $pivot ? (bool) $pivot->is_pinned : false; }); } // Getter for uptime_last_check_date to return 00 seconds in carbon object public function getUptimeLastCheckDateAttribute() { if (! $this->attributes['uptime_last_check_date']) { return null; } $date = Carbon::parse($this->attributes['uptime_last_check_date']); return $date->setSeconds(0); } public function getHostAttribute() { return $this->url->getHost(); } /** * Get the formatted page views count (e.g., "1.2k", "5.4M"). */ public function getFormattedPageViewsAttribute(): string { $count = $this->page_views_count ?? 0; if ($count >= 1000000) { return round($count / 1000000, 1).'M'; } if ($count >= 1000) { return round($count / 1000, 1).'k'; } return (string) $count; } public function users() { return $this->belongsToMany(User::class, 'user_monitor')->withPivot('is_active', 'is_pinned'); } public function statusPages() { return $this->belongsToMany(StatusPage::class, 'status_page_monitor'); } public function histories() { return $this->hasMany(MonitorHistory::class); } public function latestHistory() { return $this->hasOne(MonitorHistory::class)->latest(); } public function uptimes() { return $this->hasMany(MonitorUptime::class); } public function uptimesDaily() { return $this->hasMany(MonitorUptimeDaily::class) ->where('date', '>=', now()->subYear()->toDateString()) ->orderBy('date', 'asc'); } public function uptimeDaily() { return $this->hasOne(MonitorUptimeDaily::class)->whereDate('date', now()->toDateString()); } public function statistics() { return $this->hasOne(MonitorStatistic::class); } /** * Get the incidents for the monitor. */ public function incidents() { return $this->hasMany(MonitorIncident::class); } /** * Get recent incidents for the monitor (within last 30 days). */ public function recentIncidents() { return $this->hasMany(MonitorIncident::class) ->recent(30) ->limit(10); } /** * Get latest incidents for the monitor (no time filter). */ public function latestIncidents() { return $this->hasMany(MonitorIncident::class) ->orderBy('started_at', 'desc') ->limit(10); } /** * Get the performance records for the monitor. */ public function performanceHourly() { return $this->hasMany(MonitorPerformanceHourly::class); } public function getTodayUptimePercentageAttribute() { return $this->uptimeDaily?->uptime_percentage ?? 0; } public function scopeActive($query) { return $query->whereHas('users', function ($query) { $query->where('user_monitor.is_active', true); }); } public function scopeDisabled($query) { return $query->whereHas('users', function ($query) { $query->where('user_monitor.is_active', false); }); } public function scopePublic($query) { return $query->where('is_public', true); } public function scopePrivate($query) { return $query->where('is_public', false); } public function scopeNotInMaintenance($query) { return $query->where(function ($q) { $q->where('is_in_maintenance', false) ->orWhereNull('is_in_maintenance'); }); } public function scopeInMaintenance($query) { return $query->where('is_in_maintenance', true); } public function scopePinned($query) { return $query->whereHas('users', function ($query) { $query->where('user_monitor.user_id', auth()->id()) ->where('user_monitor.is_pinned', true); }); } public function scopeNotPinned($query) { return $query->whereHas('users', function ($query) { $query->where('user_monitor.user_id', auth()->id()) ->where('user_monitor.is_pinned', false); }); } public function scopeSearch($query, $search) { if (! $search || mb_strlen($search) < 3) { return $query; } return $query->where(function ($q) use ($search) { $q->where('url', 'like', "%$search%") ->orWhere('name', 'like', "%$search%") ->orWhereRaw('REPLACE(REPLACE(url, "https://", ""), "http://", "") LIKE ?', ["%$search%"]); }); } /** * Get the owner of this monitor (the first user who was attached to it) */ public function getOwnerAttribute() { return $this->users()->orderBy('user_monitor.created_at', 'asc')->first(); } /** * Check if the given user is the owner of this monitor */ public function isOwnedBy(User $user): bool { $owner = $this->owner; return $owner && $owner->id === $user->id; } /** * Check if the monitor is currently in a maintenance window. */ public function isInMaintenance(): bool { return app(MaintenanceWindowService::class)->isInMaintenance($this); } /** * Get the next scheduled maintenance window. */ public function getNextMaintenanceWindow(): ?array { return app(MaintenanceWindowService::class)->getNextMaintenanceWindow($this); } /** * Create or update history record for the current minute * Ensures only one history record per monitor per minute */ public function createOrUpdateHistory(array $data): MonitorHistory { $now = now(); $minuteStart = $now->copy()->setSeconds(0)->setMicroseconds(0); // Use updateOrCreate to ensure only one record per minute return $this->histories()->updateOrCreate( [ 'monitor_id' => $this->id, // Use a minute-rounded timestamp for uniqueness 'created_at' => $minuteStart, ], [ 'uptime_status' => $data['uptime_status'], 'message' => $data['message'] ?? $this->uptime_check_failure_reason, 'response_time' => $data['response_time'] ?? null, 'status_code' => $data['status_code'] ?? null, 'checked_at' => $data['checked_at'] ?? $now, 'updated_at' => $now, ] ); } // boot protected static function boot() { parent::boot(); // global scope based on logged in user static::addGlobalScope('user', function ($query) { if (auth()->check() && ! auth()->user()?->is_admin) { $query->whereHas('users', function ($query) { $query->where('user_monitor.user_id', auth()->id()); }); } }); static::addGlobalScope('enabled', function ($query) { $query->where('uptime_check_enabled', true); }); static::created(function ($monitor) { // attach the current user as the owner of the private monitor // Only attach if there's an authenticated user if (auth()->id()) { $monitor->users()->attach(auth()->id(), [ 'is_active' => true, 'is_pinned' => false, ]); } // remove cache cache()->forget('private_monitors_page_'.auth()->id().'_1'); cache()->forget('public_monitors_authenticated_'.auth()->id().'_1'); }); static::updating(function ($monitor) { // history log if ($monitor->isDirty('uptime_last_check_date') || $monitor->isDirty('uptime_status')) { $monitor->createOrUpdateHistory([ 'uptime_status' => $monitor->uptime_status, 'message' => $monitor->uptime_check_failure_reason, 'response_time' => null, // Response time should be passed when available, not retrieved from model 'status_code' => null, // Status code should be passed when available, not retrieved from model 'checked_at' => $monitor->uptime_last_check_date, ]); } }); static::deleting(function ($monitor) { $monitor->users()->detach(); }); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/UserMonitor.php
app/Models/UserMonitor.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\Pivot; class UserMonitor extends Pivot { use HasFactory; protected $table = 'user_monitor'; public $incrementing = true; protected $fillable = [ 'user_id', 'monitor_id', 'is_active', ]; protected $casts = [ 'is_active' => 'boolean', ]; public function user() { return $this->belongsTo(User::class); } public function monitor() { return $this->belongsTo(Monitor::class); } public function scopeActive($query) { return $query->where('is_active', true); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/StatusPageMonitor.php
app/Models/StatusPageMonitor.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class StatusPageMonitor extends Model { use HasFactory; protected $table = 'status_page_monitor'; protected $fillable = [ 'status_page_id', 'monitor_id', 'order', ]; /** * Get the status page that owns the monitor. */ public function statusPage(): BelongsTo { return $this->belongsTo(StatusPage::class); } /** * Get the monitor associated with this status page monitor. */ public function monitor(): BelongsTo { return $this->belongsTo(Monitor::class); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/StatusPage.php
app/Models/StatusPage.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Str; class StatusPage extends Model { use HasFactory; protected $fillable = [ 'user_id', 'title', 'description', 'icon', 'path', 'custom_domain', 'custom_domain_verified', 'custom_domain_verification_token', 'custom_domain_verified_at', 'force_https', ]; protected $casts = [ 'custom_domain_verified' => 'boolean', 'force_https' => 'boolean', 'custom_domain_verified_at' => 'datetime', ]; /** * Get the user that owns the status page. */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** * Get the monitors associated with this status page. */ public function monitors() { return $this->belongsToMany(Monitor::class, 'status_page_monitor'); } /** * Generate a unique path for the status page. */ public static function generateUniquePath(string $title): string { $basePath = Str::slug($title); $path = $basePath; $counter = 1; while (static::where('path', $path)->exists()) { $path = $basePath.'-'.$counter; $counter++; } return $path; } /** * Generate a verification token for custom domain. */ public function generateVerificationToken(): string { $token = 'uptime-kita-verify-'.Str::random(32); $this->update(['custom_domain_verification_token' => $token]); return $token; } /** * Verify the custom domain. */ public function verifyCustomDomain(): bool { if (! $this->custom_domain) { return false; } // Check DNS TXT record for verification $verified = $this->checkDnsVerification(); if ($verified) { $this->update([ 'custom_domain_verified' => true, 'custom_domain_verified_at' => now(), ]); } return $verified; } /** * Check DNS records for domain verification. */ protected function checkDnsVerification(): bool { if (! $this->custom_domain || ! $this->custom_domain_verification_token) { return false; } try { $records = dns_get_record('_uptime-kita.'.$this->custom_domain, DNS_TXT); foreach ($records as $record) { if (isset($record['txt']) && $record['txt'] === $this->custom_domain_verification_token) { return true; } } } catch (\Exception $e) { // DNS lookup failed return false; } return false; } /** * Get the full URL for the status page. */ public function getUrl(): string { if ($this->custom_domain && $this->custom_domain_verified) { $protocol = $this->force_https ? 'https://' : 'http://'; return $protocol.$this->custom_domain; } return url('/status/'.$this->path); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/TelemetryPing.php
app/Models/TelemetryPing.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class TelemetryPing extends Model { protected $fillable = [ 'instance_id', 'app_version', 'php_version', 'laravel_version', 'monitors_total', 'monitors_public', 'users_total', 'status_pages_total', 'os_family', 'os_type', 'database_driver', 'queue_driver', 'cache_driver', 'install_date', 'first_seen_at', 'last_ping_at', 'ping_count', 'raw_data', ]; protected function casts(): array { return [ 'install_date' => 'date', 'first_seen_at' => 'datetime', 'last_ping_at' => 'datetime', 'ping_count' => 'integer', 'monitors_total' => 'integer', 'monitors_public' => 'integer', 'users_total' => 'integer', 'status_pages_total' => 'integer', 'raw_data' => 'array', ]; } /** * Scope to get active instances (pinged within last N days). */ public function scopeActive($query, int $days = 7) { return $query->where('last_ping_at', '>=', now()->subDays($days)); } /** * Scope to get instances first seen within date range. */ public function scopeFirstSeenBetween($query, $start, $end) { return $query->whereBetween('first_seen_at', [$start, $end]); } /** * Get statistics for dashboard. */ public static function getStatistics(): array { $total = self::count(); $activeLastWeek = self::active(7)->count(); $activeLastMonth = self::active(30)->count(); $newThisMonth = self::firstSeenBetween(now()->startOfMonth(), now())->count(); $newLastMonth = self::firstSeenBetween(now()->subMonth()->startOfMonth(), now()->subMonth()->endOfMonth())->count(); return [ 'total_instances' => $total, 'active_last_7_days' => $activeLastWeek, 'active_last_30_days' => $activeLastMonth, 'new_this_month' => $newThisMonth, 'new_last_month' => $newLastMonth, ]; } /** * Get version distribution. */ public static function getVersionDistribution(): array { return [ 'app' => self::query() ->selectRaw('app_version, COUNT(*) as count') ->whereNotNull('app_version') ->groupBy('app_version') ->orderByDesc('count') ->limit(10) ->pluck('count', 'app_version') ->toArray(), 'php' => self::query() ->selectRaw('php_version, COUNT(*) as count') ->whereNotNull('php_version') ->groupBy('php_version') ->orderByDesc('count') ->limit(10) ->pluck('count', 'php_version') ->toArray(), 'laravel' => self::query() ->selectRaw('laravel_version, COUNT(*) as count') ->whereNotNull('laravel_version') ->groupBy('laravel_version') ->orderByDesc('count') ->limit(10) ->pluck('count', 'laravel_version') ->toArray(), ]; } /** * Get OS distribution. */ public static function getOsDistribution(): array { return self::query() ->selectRaw('os_type, COUNT(*) as count') ->whereNotNull('os_type') ->groupBy('os_type') ->orderByDesc('count') ->pluck('count', 'os_type') ->toArray(); } /** * Get growth data for chart. */ public static function getGrowthData(int $months = 12): array { $data = []; for ($i = $months - 1; $i >= 0; $i--) { $date = now()->subMonths($i); $count = self::where('first_seen_at', '<=', $date->endOfMonth())->count(); $data[] = [ 'month' => $date->format('M Y'), 'count' => $count, ]; } return $data; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/NotificationChannel.php
app/Models/NotificationChannel.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class NotificationChannel extends Model { use HasFactory; protected $fillable = [ 'user_id', 'type', 'destination', 'is_enabled', 'metadata', ]; protected $casts = [ 'is_enabled' => 'boolean', 'metadata' => 'array', ]; public function user() { return $this->belongsTo(User::class); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Models/MonitorHistory.php
app/Models/MonitorHistory.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Prunable; class MonitorHistory extends Model { use HasFactory, Prunable; protected $fillable = [ 'monitor_id', 'uptime_status', 'message', 'response_time', 'status_code', 'checked_at', 'created_at', 'updated_at', ]; protected $casts = [ 'response_time' => 'integer', 'status_code' => 'integer', 'checked_at' => 'datetime', ]; public function monitor() { return $this->belongsTo(Monitor::class); } public function scopeLatestByMonitorId($query, $monitorId) { return $query->where('monitor_id', $monitorId) ->latest(); } public function scopeLatestByMonitorIds($query, $monitorIds) { return $query->whereIn('monitor_id', $monitorIds) ->latest(); } /** * Get unique history records per minute for a specific monitor * Returns only one record per monitor per minute (the latest one) */ public static function getUniquePerMinute($monitorId, $limit = null, $orderBy = 'created_at', $orderDirection = 'desc') { $sql = " SELECT id FROM ( SELECT id, created_at, ROW_NUMBER() OVER ( PARTITION BY monitor_id, strftime('%Y-%m-%d %H:%M', created_at) ORDER BY created_at DESC, id DESC ) as rn FROM monitor_histories WHERE monitor_id = ? ) ranked WHERE rn = 1 ORDER BY {$orderBy} {$orderDirection} "; if ($limit) { $sql .= " LIMIT {$limit}"; } $uniqueIds = \DB::select($sql, [$monitorId]); $ids = array_column($uniqueIds, 'id'); return static::whereIn('id', $ids)->orderBy($orderBy, $orderDirection); } public function prunable(): \Illuminate\Database\Eloquent\Builder { return static::where('created_at', '<', now()->subDays(30)); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Providers/TelescopeServiceProvider.php
app/Providers/TelescopeServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\Facades\Gate; use Laravel\Telescope\IncomingEntry; use Laravel\Telescope\Telescope; use Laravel\Telescope\TelescopeApplicationServiceProvider; class TelescopeServiceProvider extends TelescopeApplicationServiceProvider { /** * Register any application services. */ public function register(): void { Telescope::night(); $this->hideSensitiveRequestDetails(); $isLocal = $this->app->environment('local') || $this->app->environment('dev'); Telescope::filter(function (IncomingEntry $entry) use ($isLocal) { // return true; return $isLocal || $entry->isReportableException() || $entry->isFailedRequest() || $entry->isFailedJob() || $entry->isScheduledTask() || $entry->hasMonitoredTag(); }); } /** * Prevent sensitive request details from being logged by Telescope. */ protected function hideSensitiveRequestDetails(): void { if ($this->app->environment('local')) { return; } Telescope::hideRequestParameters(['_token']); Telescope::hideRequestHeaders([ 'cookie', 'x-csrf-token', 'x-xsrf-token', ]); } /** * Register the Telescope gate. * * This gate determines who can access Telescope in non-local environments. */ protected function gate(): void { Gate::define('viewTelescope', function ($user) { return in_array($user->email, [ 'mail@syofyanzuhad.dev', ]); }); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Providers/HorizonServiceProvider.php
app/Providers/HorizonServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\Facades\Gate; use Laravel\Horizon\Horizon; use Laravel\Horizon\HorizonApplicationServiceProvider; class HorizonServiceProvider extends HorizonApplicationServiceProvider { /** * Bootstrap any application services. */ public function boot(): void { parent::boot(); // Horizon::routeSmsNotificationsTo('15556667777'); // Horizon::routeMailNotificationsTo('example@example.com'); // Horizon::routeSlackNotificationsTo('slack-webhook-url', '#channel'); } /** * Register the Horizon gate. * * This gate determines who can access Horizon in non-local environments. */ protected function gate(): void { Gate::define('viewHorizon', function ($user = null) { return in_array(optional($user)->email, [ 'mail@syofyanzuhad.dev', ]); }); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Providers/AppServiceProvider.php
app/Providers/AppServiceProvider.php
<?php namespace App\Providers; use App\Listeners\BroadcastMonitorStatusChange; use App\Listeners\DispatchConfirmationCheck; use App\Listeners\SendCustomMonitorNotification; use App\Listeners\StoreMonitorCheckData; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; use Opcodes\LogViewer\Facades\LogViewer; use Spatie\CpuLoadHealthCheck\CpuLoadCheck; use Spatie\Health\Checks\Checks\CacheCheck; use Spatie\Health\Checks\Checks\DatabaseCheck; use Spatie\Health\Checks\Checks\OptimizedAppCheck; use Spatie\Health\Checks\Checks\QueueCheck; use Spatie\Health\Checks\Checks\RedisCheck; use Spatie\Health\Checks\Checks\RedisMemoryUsageCheck; use Spatie\Health\Checks\Checks\ScheduleCheck; use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck; use Spatie\Health\Facades\Health; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; use Spatie\UptimeMonitor\Events\UptimeCheckRecovered; use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded; class AppServiceProvider extends ServiceProvider { /** * Register any application services. */ public function register(): void { // Override Inertia page paths to use lowercase 'pages' directory after package loads $this->app->booted(function () { config([ 'inertia.page_paths' => [resource_path('js/pages')], 'inertia.testing.page_paths' => [resource_path('js/pages')], ]); // Rebind the testing view finder with correct paths $this->app->bind('inertia.testing.view-finder', function ($app) { return new \Illuminate\View\FileViewFinder( $app['files'], [resource_path('js/pages')], ['js', 'jsx', 'svelte', 'ts', 'tsx', 'vue'] ); }); }); } /** * Bootstrap any application services. */ public function boot(): void { Model::shouldBeStrict(! app()->isProduction()); if (config('app.env') !== 'local') { URL::forceScheme('https'); } LogViewer::auth(fn ($request) => auth()->id() === 1); // Register confirmation check listener FIRST to intercept initial failures // This listener will dispatch a delayed confirmation job to reduce false positives Event::listen(UptimeCheckFailed::class, DispatchConfirmationCheck::class); // Register uptime monitor event listeners for notifications Event::listen(UptimeCheckFailed::class, SendCustomMonitorNotification::class); Event::listen(UptimeCheckRecovered::class, SendCustomMonitorNotification::class); // Register monitor data storage listeners Event::listen(UptimeCheckSucceeded::class, StoreMonitorCheckData::class); Event::listen(UptimeCheckFailed::class, StoreMonitorCheckData::class); Event::listen(UptimeCheckRecovered::class, StoreMonitorCheckData::class); // Register SSE broadcast listener for public monitor status changes Event::listen(UptimeCheckFailed::class, BroadcastMonitorStatusChange::class); Event::listen(UptimeCheckRecovered::class, BroadcastMonitorStatusChange::class); Health::checks([ CacheCheck::new(), OptimizedAppCheck::new(), DatabaseCheck::new(), UsedDiskSpaceCheck::new() ->warnWhenUsedSpaceIsAbovePercentage(70) ->failWhenUsedSpaceIsAbovePercentage(90), RedisCheck::new(), RedisMemoryUsageCheck::new() ->warnWhenAboveMb(900) ->failWhenAboveMb(1000), CpuLoadCheck::new() ->failWhenLoadIsHigherInTheLast5Minutes(2.0) ->failWhenLoadIsHigherInTheLast5Minutes(5.0) ->failWhenLoadIsHigherInTheLast15Minutes(3.0), ScheduleCheck::new() ->heartbeatMaxAgeInMinutes(2), QueueCheck::new(), // HorizonCheck::new(), // DatabaseSizeCheck::new() // ->failWhenSizeAboveGb(errorThresholdGb: 5.0), // DatabaseTableSizeCheck::new() // ->table('monitor_histories', maxSizeInMb: 1_000) // ->table('monitor_uptime_dailies', maxSizeInMb: 5_00) // ->table('health_check_result_history_items', maxSizeInMb: 5_00), ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Providers/AuthServiceProvider.php
app/Providers/AuthServiceProvider.php
<?php namespace App\Providers; use App\Models\Monitor; use App\Models\StatusPage; use App\Models\User; use App\Policies\MonitorPolicy; use App\Policies\StatusPagePolicy; use App\Policies\UserPolicy; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * The model to policy mappings for the application. * * @var array<class-string, class-string> */ protected $policies = [ Monitor::class => MonitorPolicy::class, StatusPage::class => StatusPagePolicy::class, User::class => UserPolicy::class, ]; /** * Register services. */ public function register(): void { // } /** * Bootstrap services. */ public function boot(): void { $this->registerPolicies(); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Policies/UserPolicy.php
app/Policies/UserPolicy.php
<?php namespace App\Policies; use App\Models\User; class UserPolicy { /** * Grant all abilities to admin users. */ public function before(User $user, $ability) { return $user->is_admin ? true : null; } public function viewAny(User $user) { return false; } public function view(User $user) { return false; } public function create(User $user) { return false; } public function update(User $user) { return false; } public function delete(User $user) { return false; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Policies/StatusPagePolicy.php
app/Policies/StatusPagePolicy.php
<?php namespace App\Policies; use App\Models\StatusPage; use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; class StatusPagePolicy { use HandlesAuthorization; /** * Determine whether the user can view any models. */ public function viewAny(User $user): bool { return true; } /** * Determine whether the user can view the model. */ public function view(User $user, StatusPage $statusPage): bool { return $user->id === $statusPage->user_id; } /** * Determine whether the user can create models. */ public function create(User $user): bool { return true; } /** * Determine whether the user can update the model. */ public function update(User $user, StatusPage $statusPage): bool { return $user->id === $statusPage->user_id; } /** * Determine whether the user can delete the model. */ public function delete(User $user, StatusPage $statusPage): bool { return $user->id === $statusPage->user_id; } /** * Determine whether the user can restore the model. */ public function restore(User $user, StatusPage $statusPage): bool { return $user->id === $statusPage->user_id; } /** * Determine whether the user can permanently delete the model. */ public function forceDelete(User $user, StatusPage $statusPage): bool { return $user->id === $statusPage->user_id; } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/app/Policies/MonitorPolicy.php
app/Policies/MonitorPolicy.php
<?php namespace App\Policies; use App\Models\Monitor; use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; class MonitorPolicy { use HandlesAuthorization; /** * Determine whether the user can view any models. */ public function viewAny(User $user): bool { return true; } /** * Determine whether the user can view the model. */ public function view(User $user, Monitor $monitor): bool { // User can view if they are subscribed to the monitor return $monitor->users()->where('user_id', $user->id)->exists(); } /** * Determine whether the user can create models. */ public function create(User $user): bool { return true; } /** * Determine whether the user can update the model. */ public function update(User $user, Monitor $monitor): bool { if ($user->is_admin) { return true; } // For public monitors, only admins can update if ($monitor->is_public) { return false; } // For private monitors, only the owner can update return $monitor->isOwnedBy($user); } /** * Determine whether the user can delete the model. */ public function delete(User $user, Monitor $monitor): bool { if ($user->is_admin) { return true; } // For public monitors, only admins can delete if ($monitor->is_public) { return false; } // For private monitors, only the owner can delete return $monitor->isOwnedBy($user); } /** * Determine whether the user can restore the model. */ public function restore(User $user, Monitor $monitor): bool { if ($user->is_admin) { return true; } return $monitor->isOwnedBy($user); } /** * Determine whether the user can permanently delete the model. */ public function forceDelete(User $user, Monitor $monitor): bool { if ($user->is_admin) { return true; } return $monitor->isOwnedBy($user); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/bootstrap/app.php
bootstrap/app.php
<?php use App\Http\Middleware\CustomDomainMiddleware; use App\Http\Middleware\HandleAppearance; use App\Http\Middleware\HandleInertiaRequests; use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets; use Sentry\Laravel\Integration; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware->encryptCookies(except: ['appearance', 'sidebar_state']); $middleware->web(prepend: [ CustomDomainMiddleware::class, ], append: [ HandleAppearance::class, HandleInertiaRequests::class, AddLinkHeadersForPreloadedAssets::class, ]); $middleware->validateCsrfTokens(except: [ '/webhook/*', ]); }) ->withExceptions(function (Exceptions $exceptions) { Integration::handles($exceptions); })->create();
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/bootstrap/providers.php
bootstrap/providers.php
<?php return [ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, App\Providers\HorizonServiceProvider::class, App\Providers\TelescopeServiceProvider::class, ];
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Pest.php
tests/Pest.php
<?php /* |-------------------------------------------------------------------------- | Test Case |-------------------------------------------------------------------------- | | The closure you provide to your test functions is always bound to a specific PHPUnit test | case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may | need to change it using the "pest()" function to bind a different classes or traits. | */ pest()->extend(Tests\TestCase::class) ->in('Feature'); pest()->extend(Tests\TestCase::class) ->in('Unit'); /* |-------------------------------------------------------------------------- | Expectations |-------------------------------------------------------------------------- | | When you're writing tests, you often need to check that values meet certain conditions. The | "expect()" function gives you access to a set of "expectations" methods that you can use | to assert different things. Of course, you may extend the Expectation API at any time. | */ expect()->extend('toBeOne', function () { return $this->toBe(1); }); /* |-------------------------------------------------------------------------- | Functions |-------------------------------------------------------------------------- | | While Pest is very powerful out-of-the-box, you may have some testing code specific to your | project that you don't want to repeat in every file. Here you can also expose helpers as | global functions to help you to reduce the number of lines of code in your test files. | */ function something() { // .. }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/TestCase.php
tests/TestCase.php
<?php namespace Tests; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use RefreshDatabase; protected function setUp(): void { parent::setUp(); // Disable CSRF verification for tests $this->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/UserCrudTest.php
tests/Feature/UserCrudTest.php
<?php use App\Models\Monitor; use App\Models\NotificationChannel; use App\Models\StatusPage; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\assertDatabaseMissing; use function Pest\Laravel\deleteJson; use function Pest\Laravel\get; use function Pest\Laravel\postJson; use function Pest\Laravel\putJson; beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); }); describe('User CRUD Operations', function () { describe('Index', function () { it('can list all users for authenticated user', function () { User::factory()->count(5)->create(); $response = actingAs($this->user)->get('/users'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Index') ->has('users.data') ); }); it('includes monitor and status page counts', function () { $testUser = User::factory()->create(); $monitor = Monitor::factory()->create(); $monitor->users()->attach($testUser->id); StatusPage::factory()->create(['user_id' => $testUser->id]); NotificationChannel::factory()->count(2)->create(['user_id' => $testUser->id]); $response = actingAs($this->user)->get('/users'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Index') ->has('users.data') ); }); it('paginates users', function () { User::factory()->count(15)->create(); $response = actingAs($this->user)->get('/users'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Index') ->has('users.data', 15) ->has('users.links') ); }); it('can search users by name', function () { User::factory()->create(['name' => 'John Doe']); User::factory()->create(['name' => 'Jane Smith']); $response = actingAs($this->user)->get('/users?search=john'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Index') ->where('search', 'john') ->has('users.data', 1) ); }); it('can search users by email', function () { User::factory()->create(['email' => 'johntest@example.com', 'name' => 'Test User']); User::factory()->create(['email' => 'jane@example.com', 'name' => 'Another User']); $response = actingAs($this->user)->get('/users?search=johntest'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Index') ->where('search', 'johntest') ->has('users.data', 1) ); }); it('respects per_page parameter', function () { User::factory()->count(20)->create(); $response = actingAs($this->user)->get('/users?per_page=10'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Index') ->where('perPage', 10) ->has('users.data', 10) ); }); it('requires authentication', function () { $response = get('/users'); $response->assertRedirect('/login'); }); }); describe('Create', function () { it('can show create form for authenticated user', function () { $response = actingAs($this->user)->get('/users/create'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Create') ); }); it('requires authentication to show create form', function () { $response = get('/users/create'); $response->assertRedirect('/login'); }); }); describe('Store', function () { it('can create a new user', function () { $userData = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'password123', 'password_confirmation' => 'password123', ]; $response = actingAs($this->admin)->postJson('/users', $userData); $response->assertRedirect('/users'); assertDatabaseHas('users', [ 'name' => 'John Doe', 'email' => 'john@example.com', ]); $newUser = User::where('email', 'john@example.com')->first(); expect(password_verify('password123', $newUser->password))->toBeTrue(); }); it('validates required fields when creating user', function () { $response = actingAs($this->admin)->postJson('/users', []); $response->assertStatus(422); $response->assertJsonValidationErrors(['name', 'email', 'password']); }); it('validates email format', function () { $userData = [ 'name' => 'John Doe', 'email' => 'not-an-email', 'password' => 'password123', 'password_confirmation' => 'password123', ]; $response = actingAs($this->admin)->postJson('/users', $userData); $response->assertStatus(422); $response->assertJsonValidationErrors(['email']); }); it('validates unique email', function () { $existingUser = User::factory()->create(['email' => 'existing@example.com']); $userData = [ 'name' => 'John Doe', 'email' => 'existing@example.com', 'password' => 'password123', 'password_confirmation' => 'password123', ]; $response = actingAs($this->admin)->postJson('/users', $userData); $response->assertStatus(422); $response->assertJsonValidationErrors(['email']); }); it('validates password confirmation', function () { $userData = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'password123', 'password_confirmation' => 'different-password', ]; $response = actingAs($this->admin)->postJson('/users', $userData); $response->assertStatus(422); $response->assertJsonValidationErrors(['password']); }); it('validates minimum password length', function () { $userData = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'short', 'password_confirmation' => 'short', ]; $response = actingAs($this->admin)->postJson('/users', $userData); $response->assertStatus(422); $response->assertJsonValidationErrors(['password']); }); it('requires authentication to create user', function () { $userData = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'password123', 'password_confirmation' => 'password123', ]; $response = postJson('/users', $userData); $response->assertUnauthorized(); }); }); describe('Show', function () { it('can view a user', function () { $viewUser = User::factory()->create(); $response = actingAs($this->user)->get("/users/{$viewUser->id}"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Show') ->has('user') ->where('user.id', $viewUser->id) ); }); it('includes all related data for user', function () { $viewUser = User::factory()->create(); // Create related data $monitor = Monitor::factory()->create(); $monitor->users()->attach($viewUser->id, ['is_active' => true, 'is_pinned' => false]); StatusPage::factory()->create(['user_id' => $viewUser->id]); NotificationChannel::factory()->count(2)->create(['user_id' => $viewUser->id]); $response = actingAs($this->user)->get("/users/{$viewUser->id}"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Show') ->has('user') ->has('user.monitors') ->has('user.status_pages') ->has('user.notification_channels') ->where('user.id', $viewUser->id) ); }); it('requires authentication to view user', function () { $viewUser = User::factory()->create(); $response = get("/users/{$viewUser->id}"); $response->assertRedirect('/login'); }); }); describe('Edit', function () { it('can show edit form for user', function () { $editUser = User::factory()->create(); $response = actingAs($this->admin)->get("/users/{$editUser->id}/edit"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('users/Edit') ->has('user') ->where('user.id', $editUser->id) ); }); it('cannot edit default admin user', function () { // User with ID 1 is the first user created and is treated as default admin $response = actingAs($this->admin)->get('/users/1/edit'); $response->assertRedirect('/users'); $response->assertSessionHas('error', 'Cannot edit the default admin user.'); }); it('requires authentication to show edit form', function () { $editUser = User::factory()->create(); $response = get("/users/{$editUser->id}/edit"); $response->assertRedirect('/login'); }); }); describe('Update', function () { it('can update a user', function () { $updateUser = User::factory()->create([ 'name' => 'Old Name', 'email' => 'old@example.com', ]); $updateData = [ 'name' => 'New Name', 'email' => 'new@example.com', ]; $response = actingAs($this->admin)->putJson("/users/{$updateUser->id}", $updateData); $response->assertRedirect('/users'); assertDatabaseHas('users', [ 'id' => $updateUser->id, 'name' => 'New Name', 'email' => 'new@example.com', ]); }); it('can update user with password', function () { $updateUser = User::factory()->create(); $updateData = [ 'name' => $updateUser->name, 'email' => $updateUser->email, 'password' => 'newpassword123', 'password_confirmation' => 'newpassword123', ]; $response = actingAs($this->admin)->putJson("/users/{$updateUser->id}", $updateData); $response->assertRedirect('/users'); $updateUser->refresh(); expect(password_verify('newpassword123', $updateUser->password))->toBeTrue(); }); it('can update user without changing password', function () { $updateUser = User::factory()->create(); $oldPassword = $updateUser->password; $updateData = [ 'name' => 'Updated Name', 'email' => $updateUser->email, ]; $response = actingAs($this->admin)->putJson("/users/{$updateUser->id}", $updateData); $response->assertRedirect('/users'); $updateUser->refresh(); expect($updateUser->password)->toBe($oldPassword); expect($updateUser->name)->toBe('Updated Name'); }); it('cannot update default admin user', function () { // User with ID 1 is the first user created and is treated as default admin $updateData = [ 'name' => 'Hacked Admin', 'email' => 'hacked@example.com', ]; $response = actingAs($this->admin)->putJson('/users/1', $updateData); $response->assertRedirect('/users'); $response->assertSessionHas('error', 'Cannot edit the default admin user.'); }); it('validates unique email on update', function () { $existingUser = User::factory()->create(['email' => 'existing@example.com']); $updateUser = User::factory()->create(); $updateData = [ 'name' => 'Updated Name', 'email' => 'existing@example.com', ]; $response = actingAs($this->admin)->putJson("/users/{$updateUser->id}", $updateData); $response->assertStatus(422); $response->assertJsonValidationErrors(['email']); }); it('allows user to keep their own email on update', function () { $updateUser = User::factory()->create(['email' => 'myemail@example.com']); $updateData = [ 'name' => 'Updated Name', 'email' => 'myemail@example.com', ]; $response = actingAs($this->admin)->putJson("/users/{$updateUser->id}", $updateData); $response->assertRedirect('/users'); assertDatabaseHas('users', [ 'id' => $updateUser->id, 'email' => 'myemail@example.com', ]); }); it('validates password confirmation on update', function () { $updateUser = User::factory()->create(); $updateData = [ 'name' => $updateUser->name, 'email' => $updateUser->email, 'password' => 'newpassword123', 'password_confirmation' => 'different-password', ]; $response = actingAs($this->admin)->putJson("/users/{$updateUser->id}", $updateData); $response->assertStatus(422); $response->assertJsonValidationErrors(['password']); }); it('requires authentication to update user', function () { $updateUser = User::factory()->create(); $updateData = [ 'name' => 'New Name', 'email' => 'new@example.com', ]; $response = putJson("/users/{$updateUser->id}", $updateData); $response->assertUnauthorized(); }); }); describe('Delete', function () { it('can delete a user', function () { $deleteUser = User::factory()->create(); $response = actingAs($this->admin)->deleteJson("/users/{$deleteUser->id}"); $response->assertRedirect('/users'); assertDatabaseMissing('users', ['id' => $deleteUser->id]); }); it('cannot delete default admin user', function () { // User with ID 1 is the first user created and is treated as default admin $response = actingAs($this->admin)->deleteJson('/users/1'); $response->assertRedirect('/users'); assertDatabaseHas('users', ['id' => 1]); }); it('cannot delete user with associated monitors', function () { $userWithMonitor = User::factory()->create(); $monitor = Monitor::factory()->create(['uptime_check_enabled' => true]); $monitor->users()->attach($userWithMonitor->id); $response = actingAs($this->admin)->deleteJson("/users/{$userWithMonitor->id}"); $response->assertRedirect('/users'); assertDatabaseHas('users', ['id' => $userWithMonitor->id]); }); it('cannot delete user with associated status pages', function () { $userWithStatusPage = User::factory()->create(); StatusPage::factory()->create(['user_id' => $userWithStatusPage->id]); $response = actingAs($this->admin)->deleteJson("/users/{$userWithStatusPage->id}"); $response->assertRedirect('/users'); assertDatabaseHas('users', ['id' => $userWithStatusPage->id]); }); it('requires authentication to delete user', function () { $deleteUser = User::factory()->create(); $response = deleteJson("/users/{$deleteUser->id}"); $response->assertUnauthorized(); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/SubscribeMonitorControllerTest.php
tests/Feature/SubscribeMonitorControllerTest.php
<?php use App\Models\Monitor; use App\Models\User; use Illuminate\Support\Facades\Cache; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\postJson; describe('SubscribeMonitorController', function () { beforeEach(function () { $this->user = User::factory()->create(); $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); }); it('allows authenticated user to subscribe to public monitor', function () { $response = actingAs($this->user) ->postJson("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertOk(); $response->assertJson(['message' => 'Subscribed to monitor successfully']); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->publicMonitor->id, 'user_id' => $this->user->id, 'is_active' => true, ]); }); it('prevents duplicate subscription', function () { // First subscription $this->user->monitors()->attach($this->publicMonitor->id, ['is_active' => true]); $response = actingAs($this->user) ->postJson("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertStatus(400); $response->assertJson(['message' => 'Already subscribed to this monitor']); }); it('prevents subscription to private monitor by non-owner', function () { $otherUser = User::factory()->create(); $response = actingAs($otherUser) ->postJson("/monitor/{$this->privateMonitor->id}/subscribe"); $response->assertStatus(403); $response->assertJson(['message' => 'Cannot subscribe to private monitor']); }); it('allows owner to subscribe to their private monitor', function () { // Make user the owner $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true]); $response = actingAs($this->user) ->postJson("/monitor/{$this->privateMonitor->id}/subscribe"); $response->assertOk(); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->privateMonitor->id, 'user_id' => $this->user->id, 'is_active' => true, ]); }); it('prevents subscription to non-existent monitor', function () { $response = actingAs($this->user) ->postJson('/monitor/999999/subscribe'); $response->assertNotFound(); }); it('requires authentication', function () { $response = postJson("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertUnauthorized(); }); it('prevents subscription to disabled monitor', function () { $disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); $response = actingAs($this->user) ->postJson("/monitor/{$disabledMonitor->id}/subscribe"); $response->assertStatus(403); $response->assertJson(['message' => 'Cannot subscribe to disabled monitor']); }); it('maintains owner status when subscribing', function () { // User is owner but not subscriber $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true]); $response = actingAs($this->user) ->postJson("/monitor/{$this->privateMonitor->id}/subscribe"); $response->assertOk(); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->privateMonitor->id, 'user_id' => $this->user->id, 'is_active' => true, ]); }); describe('non-JSON requests (redirect responses)', function () { it('returns redirect response for successful public monitor subscription', function () { $response = actingAs($this->user) ->post("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); $response->assertSessionHas('flash.message', 'Berhasil berlangganan monitor: '.$this->publicMonitor->url); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->publicMonitor->id, 'user_id' => $this->user->id, 'is_active' => true, ]); }); it('returns redirect response for private monitor error', function () { $otherUser = User::factory()->create(); $response = actingAs($otherUser) ->post("/monitor/{$this->privateMonitor->id}/subscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message', 'Cannot subscribe to private monitor'); }); it('returns redirect response for disabled monitor error', function () { $disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); $response = actingAs($this->user) ->post("/monitor/{$disabledMonitor->id}/subscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message', 'Cannot subscribe to disabled monitor'); }); it('returns redirect response for duplicate subscription error', function () { // First subscription $this->user->monitors()->attach($this->publicMonitor->id, ['is_active' => true]); $response = actingAs($this->user) ->post("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message', 'Already subscribed to this monitor'); }); it('returns redirect success for private monitor idempotent subscription', function () { // User is already subscribed to private monitor $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true]); $response = actingAs($this->user) ->post("/monitor/{$this->privateMonitor->id}/subscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); $response->assertSessionHas('flash.message', 'Berhasil berlangganan monitor: '.$this->privateMonitor->url); }); it('returns redirect error for monitor not found', function () { $response = actingAs($this->user) ->post('/monitor/999999/subscribe'); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message', 'Monitor tidak ditemukan'); }); }); describe('cache management', function () { it('clears user cache after successful subscription', function () { // Set cache to verify it gets cleared Cache::put('public_monitors_authenticated_'.$this->user->id, 'cached_data'); $response = actingAs($this->user) ->postJson("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertOk(); // Verify cache is cleared expect(Cache::get('public_monitors_authenticated_'.$this->user->id))->toBeNull(); }); }); describe('exception handling', function () { it('handles database integrity violations gracefully', function () { // Test that the controller handles unique constraint violations // when trying to create duplicate user-monitor relationships $this->user->monitors()->attach($this->publicMonitor->id, ['is_active' => true]); // Try to subscribe again - should be caught by the controller logic $response = actingAs($this->user) ->postJson("/monitor/{$this->publicMonitor->id}/subscribe"); $response->assertStatus(400); $response->assertJson(['message' => 'Already subscribed to this monitor']); }); }); describe('edge cases', function () { it('handles monitors with null URL gracefully', function () { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => '', ]); $response = actingAs($this->user) ->post("/monitor/{$monitor->id}/subscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); // Should handle empty URL gracefully in message $flashMessage = session('flash.message'); expect($flashMessage)->toContain('Berhasil berlangganan monitor:'); }); it('works with monitors using withoutGlobalScopes', function () { $monitor = Monitor::withoutGlobalScopes()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://scoped-example.com', 'uptime_status' => 'up', 'uptime_last_check_date' => now(), 'uptime_status_last_change_date' => now(), 'certificate_status' => 'not applicable', ]); $response = actingAs($this->user) ->postJson("/monitor/{$monitor->id}/subscribe"); $response->assertOk(); $response->assertJson(['message' => 'Subscribed to monitor successfully']); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/TelegramRateLimitTest.php
tests/Feature/TelegramRateLimitTest.php
<?php use App\Models\NotificationChannel; use App\Models\User; use App\Services\TelegramRateLimitService; use Carbon\Carbon; use Illuminate\Support\Facades\Cache; beforeEach(function () { // Clear any existing cache Cache::flush(); // Reset time to current time Carbon::setTestNow(); }); afterEach(function () { // Reset time after each test Carbon::setTestNow(); }); it('allows notifications within rate limits', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Should allow first notification expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeTrue(); // Track successful notification $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); // Should still allow notifications within limits expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeTrue(); }); it('blocks notifications when minute limit is reached', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Simulate 20 notifications in the same minute for ($i = 0; $i < 20; $i++) { $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); } // Should block the 21st notification expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeFalse(); }); it('blocks notifications when hour limit is reached', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Simulate 100 notifications in the same hour for ($i = 0; $i < 100; $i++) { $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); } // Should block the 101st notification expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeFalse(); // Check stats $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['hour_count'])->toBe(100); expect($stats['minute_count'])->toBe(100); }); it('resets minute counter after one minute window', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Simulate hitting minute limit for ($i = 0; $i < 20; $i++) { $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); } // Should be blocked expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeFalse(); // Advance time by 61 seconds to simulate minute window passing Carbon::setTestNow(now()->addSeconds(61)); // Should allow notifications again expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeTrue(); // Track a new notification to reset the counter $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); // Check stats $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['minute_count'])->toBe(1); // Should be reset to 1 expect($stats['hour_count'])->toBe(21); // Hour count should include the new notification }); it('resets hour counter after one hour window', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Simulate hitting hour limit for ($i = 0; $i < 100; $i++) { $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); } // Should be blocked expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeFalse(); // Advance time by 3601 seconds to simulate hour window passing Carbon::setTestNow(now()->addSeconds(3601)); // Should allow notifications again expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeTrue(); // Track a new notification to reset the counter $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); // Check stats $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['hour_count'])->toBe(1); // Should be reset to 1 expect($stats['minute_count'])->toBe(1); // Minute count should also be reset }); it('implements exponential backoff on 429 errors', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Track a failed notification (429 error) $rateLimitService->trackFailedNotification($user, $telegramChannel); // Should block notifications during backoff period expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeFalse(); // Check stats $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['backoff_count'])->toBe(1); expect($stats['is_in_backoff'])->toBeTrue(); }); it('increases backoff duration with consecutive failures', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // First failure - should have 2 minute backoff (2^1) $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats1 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats1['backoff_count'])->toBe(1); // Advance time by 3 minutes to clear backoff period Carbon::setTestNow(now()->addMinutes(3)); // Second failure - backoff count resets to 1 $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats2 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats2['backoff_count'])->toBe(1); // Advance time by 5 minutes to clear backoff period Carbon::setTestNow(now()->addMinutes(5)); // Third failure - backoff count resets to 1 $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats3 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats3['backoff_count'])->toBe(1); // Advance time by 10 minutes to clear backoff period Carbon::setTestNow(now()->addMinutes(10)); // Fourth failure - backoff count resets to 1 $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats4 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats4['backoff_count'])->toBe(1); // Advance time by 20 minutes to clear backoff period Carbon::setTestNow(now()->addMinutes(20)); // Fifth failure - backoff count resets to 1 $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats5 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats5['backoff_count'])->toBe(1); // Advance time by 35 minutes to clear backoff period Carbon::setTestNow(now()->addMinutes(35)); // Sixth failure - backoff count resets to 1 $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats6 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats6['backoff_count'])->toBe(1); // Advance time by 65 minutes to clear backoff period Carbon::setTestNow(now()->addMinutes(65)); $rateLimitService->trackFailedNotification($user, $telegramChannel); $stats7 = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats7['backoff_count'])->toBe(1); }); it('resets backoff after successful notification', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Track a failed notification $rateLimitService->trackFailedNotification($user, $telegramChannel); // Should be in backoff expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeFalse(); // Advance time by 3 minutes to clear backoff Carbon::setTestNow(now()->addMinutes(3)); // Track successful notification $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); // Should allow notifications again expect($rateLimitService->shouldSendNotification($user, $telegramChannel))->toBeTrue(); // Check stats $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['is_in_backoff'])->toBeFalse(); }); it('provides accurate rate limit statistics', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Track a few notifications $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['minute_count'])->toBe(2); expect($stats['hour_count'])->toBe(2); expect($stats['backoff_count'])->toBe(0); expect($stats['is_in_backoff'])->toBeFalse(); expect($stats['minute_limit'])->toBe(20); expect($stats['hour_limit'])->toBe(100); }); it('handles multiple users and channels independently', function () { $user1 = User::factory()->create(); $user2 = User::factory()->create(); $telegramChannel1 = NotificationChannel::create([ 'user_id' => $user1->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $telegramChannel2 = NotificationChannel::create([ 'user_id' => $user2->id, 'type' => 'telegram', 'destination' => '987654321', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Hit minute limit for user1 for ($i = 0; $i < 20; $i++) { $rateLimitService->trackSuccessfulNotification($user1, $telegramChannel1); } // User1 should be blocked expect($rateLimitService->shouldSendNotification($user1, $telegramChannel1))->toBeFalse(); // User2 should still be allowed expect($rateLimitService->shouldSendNotification($user2, $telegramChannel2))->toBeTrue(); // Check stats for both users $stats1 = $rateLimitService->getRateLimitStats($user1, $telegramChannel1); $stats2 = $rateLimitService->getRateLimitStats($user2, $telegramChannel2); expect($stats1['minute_count'])->toBe(20); expect($stats2['minute_count'])->toBe(0); }); it('can reset rate limits using the service method', function () { $user = User::factory()->create(); $telegramChannel = NotificationChannel::create([ 'user_id' => $user->id, 'type' => 'telegram', 'destination' => '123456789', 'is_enabled' => true, ]); $rateLimitService = app(TelegramRateLimitService::class); // Track some notifications $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); $rateLimitService->trackSuccessfulNotification($user, $telegramChannel); // Verify notifications are tracked $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['minute_count'])->toBe(2); expect($stats['hour_count'])->toBe(2); // Reset rate limits $rateLimitService->resetRateLimit($user, $telegramChannel); // Verify rate limits are reset $stats = $rateLimitService->getRateLimitStats($user, $telegramChannel); expect($stats['minute_count'])->toBe(0); expect($stats['hour_count'])->toBe(0); expect($stats['backoff_count'])->toBe(0); expect($stats['is_in_backoff'])->toBeFalse(); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/TwitterNotificationTest.php
tests/Feature/TwitterNotificationTest.php
<?php use App\Models\Monitor; use App\Models\NotificationChannel; use App\Models\User; use App\Notifications\MonitorStatusChanged; use App\Services\TwitterRateLimitService; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Notification; use NotificationChannels\Twitter\TwitterChannel; beforeEach(function () { // Clear cache before each test Cache::flush(); }); it('sends twitter notification when monitor goes down', function () { // Configure Twitter credentials for testing config([ 'services.twitter.consumer_key' => 'test_key', 'services.twitter.consumer_secret' => 'test_secret', 'services.twitter.access_token' => 'test_token', 'services.twitter.access_secret' => 'test_access_secret', ]); Notification::fake(); $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_check_enabled' => true, 'uptime_status' => 'DOWN', ]); // Associate user with monitor $monitor->users()->attach($user->id, ['is_active' => true]); // Create Twitter notification channel for the user $twitterChannel = NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'twitter', 'destination' => '@testuser', 'is_enabled' => true, ]); $notificationData = [ 'id' => $monitor->id, 'url' => $monitor->url, 'status' => 'DOWN', 'message' => 'Monitor is down', 'is_public' => false, ]; $user->notify(new MonitorStatusChanged($notificationData)); Notification::assertSentTo( [$user], MonitorStatusChanged::class, function ($notification, $channels) { return in_array(TwitterChannel::class, $channels); } ); }); it('respects twitter rate limits', function () { $user = User::factory()->create(); $channel = NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'twitter', 'destination' => '@testuser', 'is_enabled' => true, ]); $service = new TwitterRateLimitService; // Initially should be able to send expect($service->shouldSendNotification($user, $channel))->toBeTrue(); // Simulate sending 30 notifications (hourly limit) for ($i = 0; $i < 30; $i++) { $service->trackSuccessfulNotification($user, $channel); } // Should not be able to send after hitting hourly limit expect($service->shouldSendNotification($user, $channel))->toBeFalse(); // Check remaining tweets $remaining = $service->getRemainingTweets($user, $channel); expect($remaining['hourly_remaining'])->toBe(0); expect($remaining['daily_remaining'])->toBe(170); // 200 - 30 }); it('tracks twitter notifications in cache', function () { $user = User::factory()->create(); $channel = NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'twitter', 'destination' => '@testuser', 'is_enabled' => true, ]); $service = new TwitterRateLimitService; // Track a successful notification $service->trackSuccessfulNotification($user, $channel); // Check cache keys exist $hourlyKey = sprintf('twitter_rate_limit:hourly:%d:%d', $user->id, $channel->id); $dailyKey = sprintf('twitter_rate_limit:daily:%d:%d', $user->id, $channel->id); expect(Cache::has($hourlyKey))->toBeTrue(); expect(Cache::has($dailyKey))->toBeTrue(); expect(Cache::get($hourlyKey))->toBe(1); expect(Cache::get($dailyKey))->toBe(1); }); it('always sends twitter notification for DOWN events regardless of channel settings', function () { // Configure Twitter credentials for testing config([ 'services.twitter.consumer_key' => 'test_key', 'services.twitter.consumer_secret' => 'test_secret', 'services.twitter.access_token' => 'test_token', 'services.twitter.access_secret' => 'test_access_secret', ]); Notification::fake(); $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_check_enabled' => true, 'uptime_status' => 'DOWN', ]); // Associate user with monitor $monitor->users()->attach($user->id, ['is_active' => true]); // Create disabled Twitter notification channel $twitterChannel = NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'twitter', 'destination' => '@testuser', 'is_enabled' => false, ]); // Also create an enabled email channel so notification is still sent NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'email', 'destination' => $user->email, 'is_enabled' => true, ]); $notificationData = [ 'id' => $monitor->id, 'url' => $monitor->url, 'status' => 'DOWN', 'message' => 'Monitor is down', 'is_public' => false, ]; $user->notify(new MonitorStatusChanged($notificationData)); Notification::assertSentTo( [$user], MonitorStatusChanged::class, function ($notification, $channels) { // Twitter channel should always be included for DOWN events return in_array(TwitterChannel::class, $channels); } ); }); it('includes public monitor link in tweet when monitor is public', function () { // Configure Twitter credentials for testing config([ 'services.twitter.consumer_key' => 'test_key', 'services.twitter.consumer_secret' => 'test_secret', 'services.twitter.access_token' => 'test_token', 'services.twitter.access_secret' => 'test_access_secret', ]); $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_check_enabled' => true, 'uptime_status' => 'DOWN', 'is_public' => true, ]); // Associate user with monitor $monitor->users()->attach($user->id, ['is_active' => true]); $twitterChannel = NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'twitter', 'destination' => '@testuser', 'is_enabled' => true, ]); $notificationData = [ 'id' => $monitor->id, 'url' => $monitor->url, 'status' => 'DOWN', 'message' => 'Monitor is down', 'is_public' => true, ]; $notification = new MonitorStatusChanged($notificationData); $twitterUpdate = $notification->toTwitter($user); expect($twitterUpdate)->not->toBeNull(); expect($twitterUpdate->getContent())->toContain('Monitor Alert'); expect($twitterUpdate->getContent())->toContain(parse_url($monitor->url, PHP_URL_HOST)); expect($twitterUpdate->getContent())->toContain('#UptimeKita'); expect($twitterUpdate->getContent())->toContain('Details:'); }); it('excludes twitter channel when rate limited', function () { Notification::fake(); $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_check_enabled' => true, 'uptime_status' => 'DOWN', ]); // Associate user with monitor $monitor->users()->attach($user->id, ['is_active' => true]); // Create email channel to ensure notification still sends NotificationChannel::factory()->create([ 'user_id' => $user->id, 'type' => 'email', 'destination' => $user->email, 'is_enabled' => true, ]); // Simulate hitting Twitter rate limit $service = new TwitterRateLimitService; for ($i = 0; $i < 30; $i++) { $service->trackSuccessfulNotification($user, null); } $notificationData = [ 'id' => $monitor->id, 'url' => $monitor->url, 'status' => 'DOWN', 'message' => 'Monitor is down', 'is_public' => false, ]; $user->notify(new MonitorStatusChanged($notificationData)); Notification::assertSentTo( [$user], MonitorStatusChanged::class, function ($notification, $channels) { // Twitter channel should NOT be included when rate limited return ! in_array(TwitterChannel::class, $channels) && in_array('mail', $channels); } ); }); it('returns empty TwitterStatusUpdate from toTwitter when rate limited', function () { $user = User::factory()->create(); // Simulate hitting Twitter rate limit $service = new TwitterRateLimitService; for ($i = 0; $i < 30; $i++) { $service->trackSuccessfulNotification($user, null); } $notificationData = [ 'id' => 1, 'url' => 'https://example.com', 'status' => 'DOWN', 'message' => 'Monitor is down', 'is_public' => true, ]; $notification = new MonitorStatusChanged($notificationData); $twitterUpdate = $notification->toTwitter($user); expect($twitterUpdate)->toBeInstanceOf(\NotificationChannels\Twitter\TwitterStatusUpdate::class); expect($twitterUpdate->getContent())->toBe(''); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/PrivateMonitorControllerTest.php
tests/Feature/PrivateMonitorControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; describe('PrivateMonitorController', function () { beforeEach(function () { $this->user = User::factory()->create(); $this->otherUser = User::factory()->create(); // Create owned private monitors $this->ownedPrivateMonitor1 = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $this->ownedPrivateMonitor2 = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // Create subscribed private monitor $this->subscribedPrivateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // Create other user's private monitor $this->otherPrivateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // Create public monitor $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); // Set up relationships with explicit is_pinned = false for private monitors $this->ownedPrivateMonitor1->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => false]); $this->ownedPrivateMonitor2->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => false]); $this->subscribedPrivateMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => false]); $this->otherPrivateMonitor->users()->attach($this->otherUser->id, ['is_active' => true, 'is_pinned' => false]); // Create history for monitors MonitorHistory::factory()->create([ 'monitor_id' => $this->ownedPrivateMonitor1->id, 'uptime_status' => 'up', 'response_time' => 200, 'created_at' => now(), ]); MonitorHistory::factory()->create([ 'monitor_id' => $this->ownedPrivateMonitor2->id, 'uptime_status' => 'down', 'created_at' => now(), ]); MonitorHistory::factory()->create([ 'monitor_id' => $this->subscribedPrivateMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); }); it('returns private monitors for authenticated user', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $response->assertJsonStructure([ 'data' => [ '*' => [ 'id', 'name', 'url', 'is_public', 'uptime_status', ], ], ]); }); it('includes owned private monitors', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $monitorIds = collect($monitors)->pluck('id'); expect($monitorIds)->toContain($this->ownedPrivateMonitor1->id); expect($monitorIds)->toContain($this->ownedPrivateMonitor2->id); }); it('includes subscribed private monitors', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $monitorIds = collect($monitors)->pluck('id'); expect($monitorIds)->toContain($this->subscribedPrivateMonitor->id); }); it('excludes other users private monitors', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $monitorIds = collect($monitors)->pluck('id'); expect($monitorIds)->not->toContain($this->otherPrivateMonitor->id); }); it('excludes public monitors', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $monitorIds = collect($monitors)->pluck('id'); expect($monitorIds)->not->toContain($this->publicMonitor->id); }); it('requires authentication', function () { $response = get('/private-monitors'); $response->assertRedirect('/login'); }); it('includes monitor status information', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $upMonitor = collect($monitors)->firstWhere('id', $this->ownedPrivateMonitor1->id); expect($upMonitor['uptime_status'])->toBe('up'); // Response time would be in latest_history if loaded, but let's just check the status expect($upMonitor)->toHaveKey('uptime_status'); }); it('excludes disabled private monitors', function () { $disabledMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => false, ]); $disabledMonitor->users()->attach($this->user->id, ['is_active' => true]); MonitorHistory::factory()->create([ 'monitor_id' => $disabledMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $monitorIds = collect($monitors)->pluck('id'); expect($monitorIds)->not->toContain($disabledMonitor->id); }); it('orders monitors by created date descending', function () { $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); // Verify we have monitors and they have the expected structure expect($monitors)->not->toBeEmpty(); // Verify monitors are properly structured and ordered if (count($monitors) > 0) { expect($monitors[0])->toHaveKey('id'); expect($monitors[0])->toHaveKey('created_at'); } }); it('handles user with no private monitors', function () { $newUser = User::factory()->create(); $response = actingAs($newUser)->get('/private-monitors'); $response->assertOk(); $response->assertJson([]); }); it('returns both owned and subscribed monitors', function () { // User is both owner and subscriber $bothMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $bothMonitor->users()->attach($this->user->id, [ 'is_active' => true, ]); MonitorHistory::factory()->create([ 'monitor_id' => $bothMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = actingAs($this->user)->get('/private-monitors'); $response->assertOk(); $monitors = $response->json('data'); $monitorIds = collect($monitors)->pluck('id'); expect($monitorIds)->toContain($bothMonitor->id); expect($monitors)->toHaveCount(4); // 2 owned + 1 subscribed + 1 both }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/StatusPageCrudTest.php
tests/Feature/StatusPageCrudTest.php
<?php use App\Models\Monitor; use App\Models\StatusPage; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseCount; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\assertDatabaseMissing; use function Pest\Laravel\get; use function Pest\Laravel\postJson; beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); }); describe('StatusPage CRUD Operations', function () { describe('Index', function () { it('can list all status pages for authenticated user', function () { $statusPage1 = StatusPage::factory()->create(['user_id' => $this->user->id]); $statusPage2 = StatusPage::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->get('/status-pages'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('status-pages/Index') ->has('statusPages.data', 2) ); }); it('only shows status pages belonging to the user', function () { $myStatusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $otherUser = User::factory()->create(); $otherStatusPage = StatusPage::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->get('/status-pages'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('status-pages/Index') ->has('statusPages.data', 1) ->where('statusPages.data.0.id', $myStatusPage->id) ); }); it('admin sees only their own status pages', function () { $adminStatusPage = StatusPage::factory()->create(['user_id' => $this->admin->id]); $otherStatusPage = StatusPage::factory()->create(); $response = actingAs($this->admin)->get('/status-pages'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('status-pages/Index') ->has('statusPages.data', 1) ); }); it('requires authentication', function () { $response = get('/status-pages'); $response->assertRedirect('/login'); }); }); describe('Create', function () { it('can show create form for authenticated user', function () { $response = actingAs($this->user)->get('/status-pages/create'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('status-pages/Create') ); }); it('requires authentication to show create form', function () { $response = get('/status-pages/create'); $response->assertRedirect('/login'); }); }); describe('Store', function () { it('can create a new status page', function () { $statusPageData = [ 'title' => 'My Status Page', 'description' => 'A description of my status page', 'path' => 'my-status-page', 'icon' => 'default-icon.svg', 'force_https' => true, ]; $response = actingAs($this->user)->postJson('/status-pages', $statusPageData); $response->assertRedirect(); assertDatabaseHas('status_pages', [ 'user_id' => $this->user->id, 'title' => 'My Status Page', 'description' => 'A description of my status page', 'path' => 'my-status-page', 'force_https' => true, ]); }); it('validates required fields when creating status page', function () { $response = actingAs($this->user)->postJson('/status-pages', []); $response->assertStatus(422); $response->assertJsonValidationErrors(['title']); }); it('validates unique path', function () { StatusPage::factory()->create(['path' => 'existing-path']); $statusPageData = [ 'title' => 'New Status Page', 'path' => 'existing-path', ]; $response = actingAs($this->user)->postJson('/status-pages', $statusPageData); $response->assertStatus(422); $response->assertJsonValidationErrors(['path']); }); it('requires authentication to create status page', function () { $statusPageData = [ 'title' => 'My Status Page', 'path' => 'my-status-page', ]; $response = postJson('/status-pages', $statusPageData); $response->assertUnauthorized(); }); }); describe('Show', function () { it('can view a status page belonging to user', function () { $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->get("/status-pages/{$statusPage->id}"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('status-pages/Show') ->has('statusPage') ->where('statusPage.id', $statusPage->id) ); }); it('cannot view status page not belonging to user', function () { $otherUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->get("/status-pages/{$statusPage->id}"); $response->assertForbidden(); }); it('admin cannot view other users status page', function () { $regularUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $regularUser->id]); $response = actingAs($this->admin)->get("/status-pages/{$statusPage->id}"); $response->assertForbidden(); }); it('requires authentication to view status page', function () { $statusPage = StatusPage::factory()->create(); $response = get("/status-pages/{$statusPage->id}"); $response->assertRedirect('/login'); }); }); describe('Edit', function () { it('can show edit form for owned status page', function () { $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->get("/status-pages/{$statusPage->id}/edit"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('status-pages/Edit') ->has('statusPage') ->where('statusPage.id', $statusPage->id) ); }); it('cannot edit status page not owned by user', function () { $otherUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->get("/status-pages/{$statusPage->id}/edit"); $response->assertForbidden(); }); it('admin cannot edit other users status page', function () { $regularUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $regularUser->id]); $response = actingAs($this->admin)->get("/status-pages/{$statusPage->id}/edit"); $response->assertForbidden(); }); }); describe('Update', function () { it('can update owned status page', function () { $statusPage = StatusPage::factory()->create([ 'user_id' => $this->user->id, 'title' => 'Old Title', 'description' => 'Old Description', ]); $updateData = [ 'title' => 'New Title', 'description' => 'New Description', 'path' => 'new-path', 'icon' => 'default-icon.svg', ]; $response = actingAs($this->user)->putJson("/status-pages/{$statusPage->id}", $updateData); $response->assertRedirect(); assertDatabaseHas('status_pages', [ 'id' => $statusPage->id, 'title' => 'New Title', 'description' => 'New Description', 'path' => 'new-path', ]); }); it('cannot update status page not owned by user', function () { $otherUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $otherUser->id]); $updateData = [ 'title' => 'Hacked Title', ]; $response = actingAs($this->user)->putJson("/status-pages/{$statusPage->id}", $updateData); $response->assertForbidden(); }); it('admin cannot update other users status page', function () { $regularUser = User::factory()->create(); $statusPage = StatusPage::factory()->create([ 'user_id' => $regularUser->id, 'title' => 'User Title', ]); $updateData = [ 'title' => 'Admin Updated Title', 'description' => 'Admin updated this', 'icon' => 'default-icon.svg', ]; $response = actingAs($this->admin)->putJson("/status-pages/{$statusPage->id}", $updateData); $response->assertForbidden(); assertDatabaseHas('status_pages', [ 'id' => $statusPage->id, 'title' => 'User Title', ]); }); it('validates unique path on update', function () { $existingPage = StatusPage::factory()->create(['path' => 'taken-path']); $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $updateData = [ 'title' => 'Updated Title', 'path' => 'taken-path', ]; $response = actingAs($this->user)->putJson("/status-pages/{$statusPage->id}", $updateData); $response->assertStatus(422); $response->assertJsonValidationErrors(['path']); }); }); describe('Delete', function () { it('can delete owned status page', function () { $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->deleteJson("/status-pages/{$statusPage->id}"); $response->assertRedirect(); assertDatabaseMissing('status_pages', ['id' => $statusPage->id]); }); it('cannot delete status page not owned by user', function () { $otherUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->deleteJson("/status-pages/{$statusPage->id}"); $response->assertForbidden(); assertDatabaseHas('status_pages', ['id' => $statusPage->id]); }); it('admin cannot delete other users status page', function () { $regularUser = User::factory()->create(); $statusPage = StatusPage::factory()->create(['user_id' => $regularUser->id]); $response = actingAs($this->admin)->deleteJson("/status-pages/{$statusPage->id}"); $response->assertForbidden(); assertDatabaseHas('status_pages', ['id' => $statusPage->id]); }); it('deleting status page removes monitor associations', function () { $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $monitor1 = Monitor::factory()->create(); $monitor2 = Monitor::factory()->create(); $statusPage->monitors()->attach([$monitor1->id, $monitor2->id]); assertDatabaseCount('status_page_monitor', 2); actingAs($this->user)->deleteJson("/status-pages/{$statusPage->id}"); assertDatabaseCount('status_page_monitor', 0); // But monitors should still exist assertDatabaseHas('monitors', ['id' => $monitor1->id]); assertDatabaseHas('monitors', ['id' => $monitor2->id]); }); }); describe('Monitor Association', function () { it('can associate monitors with status page', function () { $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); $monitor = Monitor::factory()->create(); $monitor->users()->attach($this->user->id); $response = actingAs($this->user)->postJson("/status-pages/{$statusPage->id}/monitors", [ 'monitor_ids' => [$monitor->id], ]); // The endpoint returns a redirect, not a success $response->assertRedirect(); assertDatabaseHas('status_page_monitor', [ 'status_page_id' => $statusPage->id, 'monitor_id' => $monitor->id, ]); }); it('can disassociate monitors from status page', function () { $statusPage = StatusPage::factory()->create(['user_id' => $this->user->id]); // Create monitor with uptime_check_enabled = true (required by global scope) $monitor = Monitor::factory()->create(['uptime_check_enabled' => true]); $monitor->users()->attach($this->user->id); $statusPage->monitors()->attach($monitor->id); $response = actingAs($this->user)->deleteJson("/status-pages/{$statusPage->id}/monitors/{$monitor->id}"); // The endpoint returns a redirect, not a success $response->assertRedirect(); assertDatabaseMissing('status_page_monitor', [ 'status_page_id' => $statusPage->id, 'monitor_id' => $monitor->id, ]); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/BookmarkTest.php
tests/Feature/BookmarkTest.php
<?php use App\Models\Monitor; use App\Models\User; it('can pin a monitor', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // Attach user to monitor $monitor->users()->attach($user->id, [ 'is_active' => true, 'is_pinned' => false, ]); $this->actingAs($user) ->postJson("/monitor/{$monitor->id}/toggle-pin", [ 'is_pinned' => true, ]) ->assertSuccessful() ->assertJson([ 'success' => true, 'is_pinned' => true, ]); $this->assertDatabaseHas('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor->id, 'is_pinned' => true, ]); }); it('can unpin a monitor', function () { // Clear any cached data from previous tests cache()->flush(); $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => false, ]); // Attach user to monitor and pin it $monitor->users()->attach($user->id, [ 'is_active' => true, 'is_pinned' => true, ]); $response = $this->actingAs($user) ->postJson("/monitor/{$monitor->id}/toggle-pin", [ 'is_pinned' => false, ]) ->assertSuccessful() ->assertJson([ 'success' => true, 'is_pinned' => false, ]); // Debug: Let's check what's actually in the database $pivotRecord = \DB::table('user_monitor') ->where('user_id', $user->id) ->where('monitor_id', $monitor->id) ->first(); // The is_pinned should be false (0 in database) expect($pivotRecord->is_pinned)->toBe(0); }); it('cannot pin a monitor if not subscribed', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => false, ]); $this->actingAs($user) ->postJson("/monitor/{$monitor->id}/toggle-pin", [ 'is_pinned' => true, ]) ->assertStatus(403) ->assertJson([ 'success' => false, 'message' => 'You must be subscribed to this monitor to pin it.', ]); }); it('requires authentication to pin a monitor', function () { $monitor = Monitor::factory()->create(); $this->postJson("/monitor/{$monitor->id}/toggle-pin", [ 'is_pinned' => true, ]) ->assertStatus(401); }); it('requires is_pinned parameter', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create(); $monitor->users()->attach($user->id, [ 'is_active' => true, 'is_pinned' => false, ]); $this->actingAs($user) ->postJson("/monitor/{$monitor->id}/toggle-pin", []) ->assertStatus(422); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/ToggleMonitorPinControllerTest.php
tests/Feature/ToggleMonitorPinControllerTest.php
<?php use App\Models\Monitor; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\postJson; describe('ToggleMonitorPinController', function () { beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $this->pinnedMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); // User owns the private monitor $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => false]); }); it('allows admin to pin a monitor', function () { // Admin must be subscribed to the monitor $this->publicMonitor->users()->attach($this->admin->id, ['is_active' => true, 'is_pinned' => false]); $response = actingAs($this->admin) ->postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertOk(); $response->assertJson(['is_pinned' => true]); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->publicMonitor->id, 'user_id' => $this->admin->id, 'is_pinned' => true, ]); }); it('allows admin to unpin a monitor', function () { // Admin must be subscribed with pinned status $this->pinnedMonitor->users()->attach($this->admin->id, ['is_active' => true, 'is_pinned' => true]); $response = actingAs($this->admin) ->postJson("/monitor/{$this->pinnedMonitor->id}/toggle-pin", [ 'is_pinned' => false, ]); $response->assertOk(); $response->assertJson(['is_pinned' => false]); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->pinnedMonitor->id, 'user_id' => $this->admin->id, 'is_pinned' => false, ]); }); it('allows owner to toggle pin on their private monitor', function () { $response = actingAs($this->user) ->postJson("/monitor/{$this->privateMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertOk(); $response->assertJson(['is_pinned' => true]); assertDatabaseHas('user_monitor', [ 'monitor_id' => $this->privateMonitor->id, 'user_id' => $this->user->id, 'is_pinned' => true, ]); }); it('prevents non-owner from toggling pin on private monitor', function () { $otherUser = User::factory()->create(); $response = actingAs($otherUser) ->postJson("/monitor/{$this->privateMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertForbidden(); assertDatabaseHas('monitors', [ 'id' => $this->privateMonitor->id, ]); }); it('prevents regular user from toggling pin on public monitor', function () { $response = actingAs($this->user) ->postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertForbidden(); assertDatabaseHas('monitors', [ 'id' => $this->publicMonitor->id, ]); }); it('handles non-existent monitor', function () { $response = actingAs($this->admin) ->postJson('/monitor/999999/toggle-pin', [ 'is_pinned' => true, ]); $response->assertNotFound(); }); it('requires authentication', function () { $response = postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertUnauthorized(); }); it('toggles pin state correctly', function () { // Admin must be subscribed to the monitor $this->publicMonitor->users()->attach($this->admin->id, ['is_active' => true, 'is_pinned' => false]); // First toggle - should pin $response = actingAs($this->admin) ->postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertOk(); $response->assertJson(['is_pinned' => true]); // Second toggle - should unpin $response = actingAs($this->admin) ->postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => false, ]); $response->assertOk(); $response->assertJson(['is_pinned' => false]); // Third toggle - should pin again $response = actingAs($this->admin) ->postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertOk(); $response->assertJson(['is_pinned' => true]); }); it('works with disabled monitors', function () { $disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); // Admin must be subscribed to the monitor $disabledMonitor->users()->attach($this->admin->id, ['is_active' => true, 'is_pinned' => false]); $response = actingAs($this->admin) ->postJson("/monitor/{$disabledMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertOk(); $response->assertJson(['is_pinned' => true]); assertDatabaseHas('user_monitor', [ 'monitor_id' => $disabledMonitor->id, 'user_id' => $this->admin->id, 'is_pinned' => true, ]); }); it('returns updated pin status in response', function () { // Admin must be subscribed to the monitor $this->publicMonitor->users()->attach($this->admin->id, ['is_active' => true, 'is_pinned' => false]); $response = actingAs($this->admin) ->postJson("/monitor/{$this->publicMonitor->id}/toggle-pin", [ 'is_pinned' => true, ]); $response->assertOk(); $response->assertJsonStructure(['is_pinned']); $isPinned = $response->json('is_pinned'); expect($isPinned)->toBeTrue(); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/TelemetryTest.php
tests/Feature/TelemetryTest.php
<?php use App\Models\TelemetryPing; use App\Models\User; use App\Services\InstanceIdService; use App\Services\TelemetryService; beforeEach(function () { // Clean up instance ID file before each test $path = config('telemetry.instance_id_path'); if (file_exists($path)) { unlink($path); } }); // === Settings Page Tests === test('telemetry settings page requires authentication', function () { $response = $this->get('/settings/telemetry'); $response->assertRedirect('/login'); }); test('non-admin user cannot access telemetry settings page', function () { $user = User::factory()->create(['is_admin' => false]); $response = $this->actingAs($user)->get('/settings/telemetry'); $response->assertForbidden(); }); test('admin user can access telemetry settings page', function () { $user = User::factory()->create(['is_admin' => true]); $response = $this->actingAs($user)->get('/settings/telemetry'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('settings/Telemetry') ->has('settings') ->has('previewData') ); }); // === Instance ID Service Tests === test('instance id service generates valid SHA-256 hash', function () { $service = new InstanceIdService; $id = $service->getInstanceId(); expect($id)->toHaveLength(64); expect(ctype_xdigit($id))->toBeTrue(); }); test('instance id service returns same ID on subsequent calls', function () { $service = new InstanceIdService; $id1 = $service->getInstanceId(); $id2 = $service->getInstanceId(); expect($id1)->toBe($id2); }); test('instance id service can regenerate ID', function () { $service = new InstanceIdService; $id1 = $service->getInstanceId(); $id2 = $service->regenerateInstanceId(); expect($id1)->not->toBe($id2); expect($id2)->toHaveLength(64); }); test('instance id service returns install date', function () { $service = new InstanceIdService; $service->getInstanceId(); // Ensure ID exists $date = $service->getInstallDate(); expect($date)->toBe(date('Y-m-d')); }); // === Telemetry Service Tests === test('telemetry service collects valid data', function () { $service = app(TelemetryService::class); $data = $service->collectData(); expect($data)->toHaveKeys([ 'instance_id', 'versions', 'stats', 'system', 'ping', ]); expect($data['instance_id'])->toHaveLength(64); expect($data['versions'])->toHaveKeys(['app', 'php', 'laravel']); expect($data['stats'])->toHaveKeys(['monitors_total', 'monitors_public', 'users_total', 'status_pages_total', 'install_date']); expect($data['system'])->toHaveKeys(['os_family', 'os_type', 'database_driver', 'queue_driver', 'cache_driver']); expect($data['ping'])->toHaveKeys(['timestamp', 'timezone']); }); test('telemetry service respects enabled config', function () { config(['telemetry.enabled' => false]); $service = app(TelemetryService::class); expect($service->isEnabled())->toBeFalse(); config(['telemetry.enabled' => true]); expect($service->isEnabled())->toBeTrue(); }); // === Telemetry Receiver Tests === test('telemetry receiver returns 403 when disabled', function () { config(['telemetry.receiver_enabled' => false]); $response = $this->postJson('/api/telemetry/ping', [ 'instance_id' => str_repeat('a', 64), 'versions' => ['app' => '1.0', 'php' => '8.3', 'laravel' => '12.0'], 'stats' => ['monitors_total' => 5], 'system' => ['os_family' => 'Linux'], 'ping' => ['timestamp' => now()->toIso8601String()], ]); $response->assertForbidden(); }); test('telemetry receiver validates incoming data', function () { config(['telemetry.receiver_enabled' => true]); $response = $this->postJson('/api/telemetry/ping', [ 'instance_id' => 'invalid', // Too short ]); $response->assertStatus(422); }); test('telemetry receiver accepts valid ping', function () { config(['telemetry.receiver_enabled' => true]); $instanceId = str_repeat('a', 64); $response = $this->postJson('/api/telemetry/ping', [ 'instance_id' => $instanceId, 'versions' => ['app' => '2025-07-15', 'php' => '8.3.0', 'laravel' => '12.0.0'], 'stats' => [ 'monitors_total' => 10, 'monitors_public' => 5, 'users_total' => 3, 'status_pages_total' => 2, 'install_date' => '2025-01-01', ], 'system' => [ 'os_family' => 'Linux', 'os_type' => 'Ubuntu', 'database_driver' => 'sqlite', 'queue_driver' => 'database', 'cache_driver' => 'database', ], 'ping' => [ 'timestamp' => now()->toIso8601String(), 'timezone' => 'UTC', ], ]); $response->assertOk(); $response->assertJson(['success' => true]); // Verify data was stored $ping = TelemetryPing::where('instance_id', $instanceId)->first(); expect($ping)->not->toBeNull(); expect($ping->monitors_total)->toBe(10); expect($ping->php_version)->toBe('8.3.0'); expect($ping->os_type)->toBe('Ubuntu'); }); test('telemetry receiver updates existing instance on subsequent pings', function () { config(['telemetry.receiver_enabled' => true]); $instanceId = str_repeat('b', 64); // First ping $this->postJson('/api/telemetry/ping', [ 'instance_id' => $instanceId, 'versions' => ['app' => '1.0', 'php' => '8.2', 'laravel' => '11.0'], 'stats' => ['monitors_total' => 5], 'system' => ['os_family' => 'Linux'], 'ping' => ['timestamp' => now()->toIso8601String()], ]); // Second ping with updated data $this->postJson('/api/telemetry/ping', [ 'instance_id' => $instanceId, 'versions' => ['app' => '2.0', 'php' => '8.3', 'laravel' => '12.0'], 'stats' => ['monitors_total' => 10], 'system' => ['os_family' => 'Linux'], 'ping' => ['timestamp' => now()->toIso8601String()], ]); // Should only have one record expect(TelemetryPing::where('instance_id', $instanceId)->count())->toBe(1); // Data should be updated $ping = TelemetryPing::where('instance_id', $instanceId)->first(); expect($ping->monitors_total)->toBe(10); expect($ping->php_version)->toBe('8.3'); expect($ping->ping_count)->toBe(2); }); // === Dashboard Tests === test('telemetry dashboard requires authentication', function () { $response = $this->get('/admin/telemetry'); $response->assertRedirect('/login'); }); test('non-admin user cannot access telemetry dashboard', function () { $user = User::factory()->create(['is_admin' => false]); $response = $this->actingAs($user)->get('/admin/telemetry'); $response->assertForbidden(); }); test('admin user can access telemetry dashboard', function () { $user = User::factory()->create(['is_admin' => true]); $response = $this->actingAs($user)->get('/admin/telemetry'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('admin/TelemetryDashboard') ->has('receiverEnabled') ); }); // === Regenerate Instance ID Tests === test('non-admin cannot regenerate instance ID', function () { $user = User::factory()->create(['is_admin' => false]); $response = $this->actingAs($user)->postJson('/settings/telemetry/regenerate-id'); $response->assertForbidden(); }); test('admin can regenerate instance ID', function () { $user = User::factory()->create(['is_admin' => true]); // Create initial ID $service = new InstanceIdService; $oldId = $service->getInstanceId(); $response = $this->actingAs($user)->postJson('/settings/telemetry/regenerate-id'); $response->assertOk(); $response->assertJson(['success' => true]); // Verify ID changed $newId = $service->getInstanceId(); expect($newId)->not->toBe($oldId); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/PinnedMonitorControllerTest.php
tests/Feature/PinnedMonitorControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; describe('PinnedMonitorController', function () { beforeEach(function () { $this->user = User::factory()->create(); // Create monitors $this->pinnedPublicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $this->pinnedPrivateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // Create non-pinned monitors $this->unpinnedMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); // Set up pinned relationships through pivot table $this->pinnedPublicMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => true]); $this->pinnedPrivateMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => true]); $this->unpinnedMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => false]); // Create history for monitors MonitorHistory::factory()->create([ 'monitor_id' => $this->pinnedPublicMonitor->id, 'uptime_status' => 'up', 'response_time' => 200, 'created_at' => now(), ]); MonitorHistory::factory()->create([ 'monitor_id' => $this->pinnedPrivateMonitor->id, 'uptime_status' => 'down', 'response_time' => null, 'created_at' => now(), ]); }); it('returns pinned monitors for authenticated user', function () { $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $data = $response->json('data'); expect($data)->toHaveCount(2); // Both public and owned private pinned monitors }); it('includes public pinned monitors', function () { $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $response->assertJsonFragment([ 'id' => $this->pinnedPublicMonitor->id, 'is_pinned' => true, ]); }); it('includes owned private pinned monitors', function () { $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $response->assertJsonFragment([ 'id' => $this->pinnedPrivateMonitor->id, 'is_pinned' => true, ]); }); it('excludes non-owned private pinned monitors', function () { $otherUser = User::factory()->create(); $privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $privateMonitor->users()->attach($otherUser->id, ['is_active' => true, 'is_pinned' => true]); MonitorHistory::factory()->create([ 'monitor_id' => $privateMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $response->assertJsonMissing([ 'id' => $privateMonitor->id, ]); }); it('excludes unpinned monitors', function () { $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $response->assertJsonMissing([ 'id' => $this->unpinnedMonitor->id, ]); }); it('includes monitor status and metrics', function () { $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $monitors = $response->json('data'); expect($monitors[0])->toHaveKeys([ 'id', 'name', 'url', 'is_pinned', 'uptime_status', ]); }); it('requires authentication to view pinned monitors', function () { $response = get('/pinned-monitors'); $response->assertRedirect('/login'); }); it('excludes disabled pinned monitors', function () { $disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); $disabledMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => true]); MonitorHistory::factory()->create([ 'monitor_id' => $disabledMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $response->assertJsonMissing([ 'id' => $disabledMonitor->id, ]); }); it('orders monitors by created date', function () { $newerMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'created_at' => now()->addMinute(), ]); $newerMonitor->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => true]); MonitorHistory::factory()->create([ 'monitor_id' => $newerMonitor->id, 'uptime_status' => 'up', 'created_at' => now()->addMinute(), ]); $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $monitors = $response->json('data'); expect($monitors[0]['id'])->toBe($newerMonitor->id); }); it('handles monitors without history', function () { $monitorWithoutHistory = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitorWithoutHistory->users()->attach($this->user->id, ['is_active' => true, 'is_pinned' => true]); $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $data = $response->json('data'); $hasMonitor = collect($data)->contains('id', $monitorWithoutHistory->id); expect($hasMonitor)->toBeTrue(); }); it('returns empty array when no pinned monitors exist', function () { // Unpin all monitors by detaching user relationships $this->user->monitors()->detach(); $response = actingAs($this->user)->get('/pinned-monitors'); $response->assertOk(); $data = $response->json('data'); expect($data)->toBeEmpty(); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorListControllerTest.php
tests/Feature/MonitorListControllerTest.php
<?php use App\Models\Monitor; use App\Models\User; use Inertia\Testing\AssertableInertia as Assert; beforeEach(function () { $this->user = User::factory()->create(); $this->actingAs($this->user); }); describe('MonitorListController', function () { describe('index method with pinned type', function () { it('displays only pinned monitors for authenticated user', function () { // Create monitors $pinnedMonitor = Monitor::factory()->create(); $unpinnedMonitor = Monitor::factory()->create(); $otherUserPinnedMonitor = Monitor::factory()->create(); // Attach monitors to user with syncWithoutDetaching to avoid duplicates $this->user->monitors()->syncWithoutDetaching([ $pinnedMonitor->id => ['is_pinned' => true], $unpinnedMonitor->id => ['is_pinned' => false], ]); // Another user's pinned monitor $otherUser = User::factory()->create(); $otherUser->monitors()->syncWithoutDetaching([$otherUserPinnedMonitor->id => ['is_pinned' => true]]); $response = $this->get(route('monitors.list', ['type' => 'pinned'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->component('monitors/List') ->has('monitors.data', 1) ->where('monitors.data.0.id', $pinnedMonitor->id) ->where('type', 'pinned') ); }); it('returns empty list when user has no pinned monitors', function () { Monitor::factory()->count(3)->create(); $response = $this->get(route('monitors.list', ['type' => 'pinned'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->component('monitors/List') ->has('monitors.data', 0) ->where('type', 'pinned') ); }); }); describe('index method with private type', function () { it('displays only private monitors user is subscribed to', function () { $privateMonitor = Monitor::factory()->create(['is_public' => false]); $publicMonitor = Monitor::factory()->create(['is_public' => true]); $otherPrivateMonitor = Monitor::factory()->create(['is_public' => false]); // User subscribed to private and public monitors $this->user->monitors()->syncWithoutDetaching([$privateMonitor->id, $publicMonitor->id]); // Other user's private monitor $otherUser = User::factory()->create(); $otherUser->monitors()->syncWithoutDetaching([$otherPrivateMonitor->id]); $response = $this->get(route('monitors.list', ['type' => 'private'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->component('monitors/List') ->has('monitors.data') // Check that the returned monitors are only private ones that user is subscribed to ->where('type', 'private') ); }); }); describe('index method with public type', function () { it('displays all public monitors', function () { $publicMonitor1 = Monitor::factory()->create(['is_public' => true]); $publicMonitor2 = Monitor::factory()->create(['is_public' => true]); $privateMonitor = Monitor::factory()->create(['is_public' => false]); $response = $this->get(route('monitors.list', ['type' => 'public'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->component('monitors/List') ->has('monitors.data', 2) ->where('type', 'public') ); }); it('includes subscription status for authenticated users', function () { $publicMonitor = Monitor::factory()->create(['is_public' => true]); $this->user->monitors()->syncWithoutDetaching([$publicMonitor->id]); $response = $this->get(route('monitors.list', ['type' => 'public'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->component('monitors/List') ->where('monitors.data.0.id', $publicMonitor->id) ->where('monitors.data.0.is_subscribed', true) ); }); it('requires authentication to view any monitor list', function () { auth()->logout(); // Test that even public monitors require authentication $response = $this->get(route('monitors.list', ['type' => 'public'])); $response->assertRedirect('/login'); }); }); describe('invalid type parameter', function () { it('returns 404 for invalid monitor type', function () { $response = $this->get('/monitors/invalid-type'); $response->assertNotFound(); }); it('returns 404 for empty type', function () { $response = $this->get('/monitors/'); $response->assertNotFound(); }); }); describe('search functionality', function () { it('filters monitors by URL search term', function () { $matchingMonitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'is_public' => true, ]); $nonMatchingMonitor = Monitor::factory()->create([ 'url' => 'https://different.com', 'is_public' => true, ]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'search' => 'example', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 1) ->where('monitors.data.0.id', $matchingMonitor->id) ->where('search', 'example') ); }); it('requires minimum 3 characters for search', function () { Monitor::factory()->count(3)->create(['is_public' => true]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'search' => 'ab', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 3) ->where('search', 'ab') ); }); it('searches without protocol in URL', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://searchtest.com', 'is_public' => true, ]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'search' => 'searchtest', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 1) ->where('monitors.data.0.id', $monitor->id) ); }); }); describe('status filters', function () { it('filters disabled monitors for authenticated users', function () { $activeMonitor = Monitor::factory()->create(['is_public' => false]); $disabledMonitor = Monitor::factory()->create(['is_public' => false]); $this->user->monitors()->syncWithoutDetaching([ $activeMonitor->id => ['is_active' => true], $disabledMonitor->id => ['is_active' => false], ]); $response = $this->get(route('monitors.list', [ 'type' => 'pinned', 'status_filter' => 'disabled', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 0) // Should be 0 because they're not pinned ->where('statusFilter', 'disabled') ); }); it('filters globally enabled monitors', function () { Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => true, ]); Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => true, ]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'status_filter' => 'globally_enabled', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 1) ->where('statusFilter', 'globally_enabled') ); }); it('filters globally disabled monitors', function () { Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => true, ]); Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => true, ]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'status_filter' => 'globally_disabled', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 1) ->where('statusFilter', 'globally_disabled') ); }); it('filters monitors by uptime status', function () { Monitor::factory()->create([ 'uptime_status' => 'up', 'is_public' => true, ]); Monitor::factory()->create([ 'uptime_status' => 'down', 'is_public' => true, ]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'status_filter' => 'up', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 1) ->where('monitors.data.0.uptime_status', 'up') ->where('statusFilter', 'up') ); }); }); describe('visibility filters', function () { it('filters public monitors in non-type-specific views', function () { $publicMonitor = Monitor::factory()->create(['is_public' => true]); $privateMonitor = Monitor::factory()->create(['is_public' => false]); $this->user->monitors()->syncWithoutDetaching([ $publicMonitor->id => ['is_pinned' => true], $privateMonitor->id => ['is_pinned' => true], ]); $response = $this->get(route('monitors.list', [ 'type' => 'pinned', 'visibility_filter' => 'public', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 1) ->where('monitors.data.0.id', $publicMonitor->id) ->where('visibilityFilter', 'public') ); }); it('ignores visibility filter for type-specific views', function () { Monitor::factory()->count(2)->create(['is_public' => true]); Monitor::factory()->create(['is_public' => false]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'visibility_filter' => 'private', ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 2) ->where('visibilityFilter', 'private') ); }); }); describe('pagination', function () { it('paginates results with default per page', function () { Monitor::factory()->count(15)->create(['is_public' => true]); $response = $this->get(route('monitors.list', ['type' => 'public'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 12) ->has('monitors.meta') ->has('monitors.meta.total') ->where('perPage', 12) ); }); it('respects custom per page parameter', function () { Monitor::factory()->count(10)->create(['is_public' => true]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'per_page' => 5, ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 5) ->where('perPage', '5') ); }); it('navigates to specific page', function () { Monitor::factory()->count(15)->create(['is_public' => true]); $response = $this->get(route('monitors.list', [ 'type' => 'public', 'page' => 2, ])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data', 3) ->has('monitors.meta') ->has('monitors.meta.current_page') ); }); }); describe('ordering', function () { it('orders monitors by creation date descending', function () { $oldMonitor = Monitor::factory()->create([ 'is_public' => true, 'created_at' => now()->subDays(2), ]); $newMonitor = Monitor::factory()->create([ 'is_public' => true, 'created_at' => now(), ]); $response = $this->get(route('monitors.list', ['type' => 'public'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->where('monitors.data.0.id', $newMonitor->id) ->where('monitors.data.1.id', $oldMonitor->id) ); }); }); describe('relationships loading', function () { it('loads required relationships efficiently', function () { $monitor = Monitor::factory()->create(['is_public' => true]); $this->user->monitors()->syncWithoutDetaching([$monitor->id]); $response = $this->get(route('monitors.list', ['type' => 'public'])); $response->assertOk(); $response->assertInertia(fn (Assert $page) => $page ->has('monitors.data.0.id') ->has('monitors.data.0.url') ); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorStatusStreamControllerTest.php
tests/Feature/MonitorStatusStreamControllerTest.php
<?php use Illuminate\Support\Facades\Cache; use function Pest\Laravel\get; describe('MonitorStatusStreamController', function () { beforeEach(function () { Cache::flush(); }); afterEach(function () { Cache::flush(); }); it('returns SSE response with correct content type header', function () { $response = get('/api/monitor-status-stream'); $response->assertHeader('Content-Type', 'text/event-stream; charset=utf-8'); }); it('returns SSE response with cache control header', function () { $response = get('/api/monitor-status-stream'); $response->assertHeader('Cache-Control'); }); it('accepts monitor_ids query parameter', function () { $response = get('/api/monitor-status-stream?monitor_ids=1,2,3'); $response->assertHeader('Content-Type', 'text/event-stream; charset=utf-8'); }); it('accepts status_page_id query parameter', function () { $response = get('/api/monitor-status-stream?status_page_id=1'); $response->assertHeader('Content-Type', 'text/event-stream; charset=utf-8'); }); it('accepts last_event_id query parameter', function () { $response = get('/api/monitor-status-stream?last_event_id=msc_123'); $response->assertHeader('Content-Type', 'text/event-stream; charset=utf-8'); }); it('is rate limited', function () { // Make 10 requests (the limit) for ($i = 0; $i < 10; $i++) { get('/api/monitor-status-stream'); } // The 11th request should be rate limited $response = get('/api/monitor-status-stream'); $response->assertStatus(429); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/SmartRetryServiceTest.php
tests/Feature/SmartRetryServiceTest.php
<?php use App\Models\Monitor; use App\Services\SmartRetryAttempt; use App\Services\SmartRetryResult; use App\Services\SmartRetryService; beforeEach(function () { $this->service = new SmartRetryService; }); describe('SmartRetryService', function () { describe('getPreset', function () { it('returns low sensitivity preset', function () { $preset = SmartRetryService::getPreset('low'); expect($preset)->toBeArray() ->and($preset['confirmation_delay'])->toBe(60) ->and($preset['retries'])->toBe(5) ->and($preset['backoff_multiplier'])->toBe(2) ->and($preset['initial_delay_ms'])->toBe(200); }); it('returns medium sensitivity preset', function () { $preset = SmartRetryService::getPreset('medium'); expect($preset)->toBeArray() ->and($preset['confirmation_delay'])->toBe(30) ->and($preset['retries'])->toBe(3) ->and($preset['backoff_multiplier'])->toBe(2) ->and($preset['initial_delay_ms'])->toBe(100); }); it('returns high sensitivity preset', function () { $preset = SmartRetryService::getPreset('high'); expect($preset)->toBeArray() ->and($preset['confirmation_delay'])->toBe(15) ->and($preset['retries'])->toBe(2) ->and($preset['backoff_multiplier'])->toBe(1.5) ->and($preset['initial_delay_ms'])->toBe(50); }); it('returns medium preset for unknown sensitivity', function () { $preset = SmartRetryService::getPreset('unknown'); expect($preset)->toBeArray() ->and($preset['confirmation_delay'])->toBe(30); }); }); describe('performSmartCheck', function () { it('returns failure for a non-existent domain', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://this-domain-does-not-exist-12345.invalid', 'uptime_check_enabled' => true, ]); $result = $this->service->performSmartCheck($monitor, [ 'retries' => 1, 'initial_delay_ms' => 50, ]); expect($result)->toBeInstanceOf(SmartRetryResult::class) ->and($result->isSuccess())->toBeFalse() ->and($result->getAttemptCount())->toBeGreaterThanOrEqual(1); }); it('includes TCP ping attempt for failed HTTP checks', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://this-domain-does-not-exist-12345.invalid', 'uptime_check_enabled' => true, ]); $result = $this->service->performSmartCheck($monitor, [ 'retries' => 1, 'initial_delay_ms' => 50, ]); // Should have at least HTTP attempt and TCP attempt expect($result->getAttemptCount())->toBeGreaterThanOrEqual(2); }); }); }); describe('SmartRetryResult', function () { it('can be created with success state', function () { $result = new SmartRetryResult( success: true, attempts: [], message: 'Test message', statusCode: 200, responseTime: 100.5, ); expect($result->isSuccess())->toBeTrue() ->and($result->message)->toBe('Test message') ->and($result->statusCode)->toBe(200) ->and($result->responseTime)->toBe(100.5); }); it('can count attempts', function () { $attempts = [ new SmartRetryAttempt(success: false, attemptNumber: 1), new SmartRetryAttempt(success: false, attemptNumber: 2), new SmartRetryAttempt(success: true, attemptNumber: 3), ]; $result = new SmartRetryResult( success: true, attempts: $attempts, ); expect($result->getAttemptCount())->toBe(3); }); it('can get successful attempt', function () { $attempts = [ new SmartRetryAttempt(success: false, attemptNumber: 1), new SmartRetryAttempt(success: true, attemptNumber: 2, statusCode: 200), ]; $result = new SmartRetryResult( success: true, attempts: $attempts, ); $successfulAttempt = $result->getSuccessfulAttempt(); expect($successfulAttempt)->not->toBeNull() ->and($successfulAttempt->attemptNumber)->toBe(2) ->and($successfulAttempt->statusCode)->toBe(200); }); it('returns null when no successful attempt', function () { $attempts = [ new SmartRetryAttempt(success: false, attemptNumber: 1), new SmartRetryAttempt(success: false, attemptNumber: 2), ]; $result = new SmartRetryResult( success: false, attempts: $attempts, ); expect($result->getSuccessfulAttempt())->toBeNull(); }); }); describe('SmartRetryAttempt', function () { it('can identify timeout errors', function () { $attempt = new SmartRetryAttempt( success: false, errorType: SmartRetryAttempt::ERROR_TIMEOUT, ); expect($attempt->isTimeout())->toBeTrue() ->and($attempt->isConnectionRefused())->toBeFalse() ->and($attempt->isDnsError())->toBeFalse(); }); it('can identify connection refused errors', function () { $attempt = new SmartRetryAttempt( success: false, errorType: SmartRetryAttempt::ERROR_CONNECTION_REFUSED, ); expect($attempt->isConnectionRefused())->toBeTrue() ->and($attempt->isTimeout())->toBeFalse(); }); it('can identify DNS errors', function () { $attempt = new SmartRetryAttempt( success: false, errorType: SmartRetryAttempt::ERROR_DNS, ); expect($attempt->isDnsError())->toBeTrue() ->and($attempt->isTimeout())->toBeFalse(); }); it('can identify HTTP status errors', function () { $attempt = new SmartRetryAttempt( success: false, errorType: SmartRetryAttempt::ERROR_HTTP_STATUS, statusCode: 500, ); expect($attempt->isHttpStatusError())->toBeTrue() ->and($attempt->statusCode)->toBe(500); }); it('can convert to array', function () { $attempt = new SmartRetryAttempt( success: true, type: SmartRetryAttempt::TYPE_HTTP, method: 'HEAD', statusCode: 200, responseTime: 150.5, attemptNumber: 1, ); $array = $attempt->toArray(); expect($array)->toBeArray() ->and($array['success'])->toBeTrue() ->and($array['type'])->toBe('http') ->and($array['method'])->toBe('HEAD') ->and($array['status_code'])->toBe(200) ->and($array['response_time'])->toBe(150.5) ->and($array['attempt_number'])->toBe(1); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorPageViewsTest.php
tests/Feature/MonitorPageViewsTest.php
<?php use App\Jobs\IncrementMonitorPageViewJob; use App\Models\Monitor; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Queue; use function Pest\Laravel\get; beforeEach(function () { // Create a public monitor for testing $this->monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'is_public' => true, 'uptime_check_enabled' => true, 'page_views_count' => 0, ]); }); describe('Page View Job', function () { it('increments view count when job is processed', function () { $job = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.1'); $job->handle(); $this->monitor->refresh(); expect($this->monitor->page_views_count)->toBe(1); }); it('does not increment view count for same IP within cooldown period', function () { $job1 = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.1'); $job1->handle(); $job2 = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.1'); $job2->handle(); $this->monitor->refresh(); expect($this->monitor->page_views_count)->toBe(1); }); it('increments view count for different IPs', function () { $job1 = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.1'); $job1->handle(); $job2 = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.2'); $job2->handle(); $this->monitor->refresh(); expect($this->monitor->page_views_count)->toBe(2); }); it('allows increment after cooldown expires', function () { $job1 = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.1'); $job1->handle(); // Clear the cache to simulate cooldown expiry $cacheKey = 'monitor_view_'.$this->monitor->id.'_'.md5('192.168.1.1'); Cache::forget($cacheKey); $job2 = new IncrementMonitorPageViewJob($this->monitor->id, '192.168.1.1'); $job2->handle(); $this->monitor->refresh(); expect($this->monitor->page_views_count)->toBe(2); }); }); describe('Public Monitor Show Controller', function () { it('dispatches page view job when visiting public monitor page', function () { Queue::fake(); $domain = parse_url($this->monitor->url, PHP_URL_HOST); get("/m/{$domain}"); Queue::assertPushed(IncrementMonitorPageViewJob::class, function ($job) { return $job->monitorId === $this->monitor->id; }); }); it('does not dispatch job for non-existent monitors', function () { Queue::fake(); get('/m/non-existent-domain.com'); Queue::assertNotPushed(IncrementMonitorPageViewJob::class); }); }); describe('Monitor Model', function () { it('formats page views correctly for small numbers', function () { $this->monitor->update(['page_views_count' => 42]); expect($this->monitor->formatted_page_views)->toBe('42'); }); it('formats page views correctly for thousands', function () { $this->monitor->update(['page_views_count' => 1500]); expect($this->monitor->formatted_page_views)->toBe('1.5k'); }); it('formats page views correctly for millions', function () { $this->monitor->update(['page_views_count' => 2500000]); expect($this->monitor->formatted_page_views)->toBe('2.5M'); }); it('formats zero page views correctly', function () { expect($this->monitor->formatted_page_views)->toBe('0'); }); }); describe('Monitor Resource', function () { it('includes page views in API response', function () { $this->monitor->update(['page_views_count' => 1234]); $domain = parse_url($this->monitor->url, PHP_URL_HOST); $response = get("/m/{$domain}"); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShow') ->has('monitor.data.page_views_count') ->has('monitor.data.formatted_page_views') ->where('monitor.data.page_views_count', 1234) ->where('monitor.data.formatted_page_views', '1.2k') ); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/BadgeControllerTest.php
tests/Feature/BadgeControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorStatistic; use function Pest\Laravel\get; describe('BadgeController', function () { beforeEach(function () { $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://example.com', ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, 'url' => 'https://private.com', ]); $this->disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, 'url' => 'https://disabled.com', ]); }); it('returns SVG badge for public monitor', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 99.5, 'uptime_7d' => 99.8, 'uptime_30d' => 99.9, 'uptime_90d' => 99.95, ]); $response = get('/badge/example.com'); $response->assertOk(); $response->assertHeader('Content-Type', 'image/svg+xml'); expect($response->getContent())->toContain('<svg'); expect($response->getContent())->toContain('99.5%'); expect($response->getContent())->toContain('uptime'); }); it('returns not found badge for private monitor', function () { $response = get('/badge/private.com'); $response->assertOk(); $response->assertHeader('Content-Type', 'image/svg+xml'); expect($response->getContent())->toContain('<svg'); expect($response->getContent())->toContain('not found'); }); it('returns not found badge for disabled monitor', function () { $response = get('/badge/disabled.com'); $response->assertOk(); $response->assertHeader('Content-Type', 'image/svg+xml'); expect($response->getContent())->toContain('not found'); }); it('returns not found badge for non-existent domain', function () { $response = get('/badge/nonexistent.com'); $response->assertOk(); $response->assertHeader('Content-Type', 'image/svg+xml'); expect($response->getContent())->toContain('not found'); }); it('supports period query parameter for 7d', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 95.0, 'uptime_7d' => 98.5, 'uptime_30d' => 99.0, 'uptime_90d' => 99.5, ]); $response = get('/badge/example.com?period=7d'); $response->assertOk(); expect($response->getContent())->toContain('98.5%'); }); it('supports period query parameter for 30d', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 95.0, 'uptime_7d' => 98.5, 'uptime_30d' => 99.2, 'uptime_90d' => 99.5, ]); $response = get('/badge/example.com?period=30d'); $response->assertOk(); expect($response->getContent())->toContain('99.2%'); }); it('supports custom label query parameter', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 99.0, ]); $response = get('/badge/example.com?label=status'); $response->assertOk(); expect($response->getContent())->toContain('status'); }); it('supports flat-square style', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 99.0, ]); $response = get('/badge/example.com?style=flat-square'); $response->assertOk(); // flat-square has rx="0" (no rounded corners) expect($response->getContent())->toContain('rx="0"'); }); it('supports plastic style', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 99.0, ]); $response = get('/badge/example.com?style=plastic'); $response->assertOk(); // plastic style includes gradient definition expect($response->getContent())->toContain('id="gradient"'); }); it('shows green color for uptime >= 99%', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 99.5, ]); $response = get('/badge/example.com'); $response->assertOk(); expect($response->getContent())->toContain('#4c1'); // brightgreen }); it('shows yellow color for uptime between 90-95%', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 92.0, ]); $response = get('/badge/example.com'); $response->assertOk(); expect($response->getContent())->toContain('#dfb317'); // yellow }); it('shows red color for uptime below 80%', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 75.0, ]); $response = get('/badge/example.com'); $response->assertOk(); expect($response->getContent())->toContain('#e05d44'); // red }); it('sets proper cache headers', function () { MonitorStatistic::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_24h' => 99.0, ]); $response = get('/badge/example.com'); $response->assertOk(); $response->assertHeader('Cache-Control', 'max-age=300, public, s-maxage=300'); }); it('handles subdomain correctly', function () { $subdomainMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://api.example.com', ]); MonitorStatistic::factory()->create([ 'monitor_id' => $subdomainMonitor->id, 'uptime_24h' => 99.0, ]); $response = get('/badge/api.example.com'); $response->assertOk(); expect($response->getContent())->toContain('99.0%'); }); it('defaults to 100% uptime when no statistics exist', function () { // No statistics created for this monitor $response = get('/badge/example.com'); $response->assertOk(); expect($response->getContent())->toContain('100.0%'); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/ConfirmMonitorDowntimeJobTest.php
tests/Feature/ConfirmMonitorDowntimeJobTest.php
<?php use App\Jobs\ConfirmMonitorDowntimeJob; use App\Listeners\DispatchConfirmationCheck; use App\Models\Monitor; use App\Services\SmartRetryService; use Carbon\Carbon; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Queue; use Spatie\UptimeMonitor\Events\UptimeCheckFailed; use Spatie\UptimeMonitor\Helpers\Period; beforeEach(function () { // Disable global scopes for testing Monitor::withoutGlobalScopes(); $this->smartRetryService = new SmartRetryService; }); it('dispatches confirmation check job on first failure', function () { Queue::fake(); config(['uptime-monitor.confirmation_check.enabled' => true]); config(['uptime-monitor.confirmation_check.delay_seconds' => 30]); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_status' => 'down', 'uptime_check_times_failed_in_a_row' => 1, 'uptime_check_failure_reason' => 'Connection timeout', 'uptime_status_last_change_date' => now()->subMinutes(5), ]); $downtimePeriod = new Period(now()->subMinutes(5), now()); $event = new UptimeCheckFailed($monitor, $downtimePeriod); $listener = new DispatchConfirmationCheck; $result = $listener->handle($event); expect($result)->toBeFalse(); // Should stop propagation Queue::assertPushed(ConfirmMonitorDowntimeJob::class, function ($job) use ($monitor) { return $job->monitorId === $monitor->id && $job->failureReason === 'Connection timeout'; }); }); it('does not dispatch confirmation check when disabled', function () { Queue::fake(); config(['uptime-monitor.confirmation_check.enabled' => false]); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_status' => 'down', 'uptime_check_times_failed_in_a_row' => 1, 'uptime_status_last_change_date' => now()->subMinutes(5), ]); $downtimePeriod = new Period(now()->subMinutes(5), now()); $event = new UptimeCheckFailed($monitor, $downtimePeriod); $listener = new DispatchConfirmationCheck; $result = $listener->handle($event); expect($result)->toBeTrue(); // Should let event propagate Queue::assertNotPushed(ConfirmMonitorDowntimeJob::class); }); it('lets event propagate on subsequent failures', function () { Queue::fake(); config(['uptime-monitor.confirmation_check.enabled' => true]); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_status' => 'down', 'uptime_check_times_failed_in_a_row' => 2, // Not first failure 'uptime_status_last_change_date' => now()->subMinutes(10), ]); $downtimePeriod = new Period(now()->subMinutes(10), now()); $event = new UptimeCheckFailed($monitor, $downtimePeriod); $listener = new DispatchConfirmationCheck; $result = $listener->handle($event); expect($result)->toBeTrue(); // Should let event propagate Queue::assertNotPushed(ConfirmMonitorDowntimeJob::class); }); it('handles monitor that is still down', function () { Event::fake([UptimeCheckFailed::class]); // Create a monitor that will fail the confirmation check (unreachable URL) $monitor = Monitor::factory()->create([ 'url' => 'https://this-url-definitely-does-not-exist-12345.invalid', 'uptime_status' => 'down', 'uptime_check_times_failed_in_a_row' => 1, 'uptime_check_failure_reason' => 'Connection timeout', 'uptime_status_last_change_date' => now()->subMinutes(5), 'transient_failures_count' => 0, ]); $job = new ConfirmMonitorDowntimeJob( $monitor->id, 'Connection timeout', 1 ); $job->handle(); // Should fire UptimeCheckFailed event since the URL is unreachable Event::assertDispatched(UptimeCheckFailed::class); })->skip('Skipping test that requires actual HTTP request to unreachable URL'); it('skips confirmation if monitor already recovered', function () { Event::fake([UptimeCheckFailed::class]); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_status' => 'up', // Already recovered 'uptime_check_times_failed_in_a_row' => 0, 'uptime_status_last_change_date' => now(), ]); $job = new ConfirmMonitorDowntimeJob( $monitor->id, 'Connection timeout', 1 ); $job->handle($this->smartRetryService); Event::assertNotDispatched(UptimeCheckFailed::class); }); it('skips confirmation if monitor is disabled', function () { Event::fake([UptimeCheckFailed::class]); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_check_enabled' => false, 'uptime_status' => 'down', 'uptime_status_last_change_date' => now()->subMinutes(5), ]); $job = new ConfirmMonitorDowntimeJob( $monitor->id, 'Connection timeout', 1 ); $job->handle($this->smartRetryService); Event::assertNotDispatched(UptimeCheckFailed::class); }); it('skips confirmation if monitor not found', function () { Event::fake([UptimeCheckFailed::class]); $job = new ConfirmMonitorDowntimeJob( 99999, // Non-existent monitor ID 'Connection timeout', 1 ); $job->handle($this->smartRetryService); Event::assertNotDispatched(UptimeCheckFailed::class); }); it('logs transient failure when already recovered', function () { Carbon::setTestNow(now()); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_status' => 'up', // Already recovered 'uptime_check_times_failed_in_a_row' => 0, 'transient_failures_count' => 5, 'uptime_status_last_change_date' => now(), ]); $job = new ConfirmMonitorDowntimeJob( $monitor->id, 'Connection timeout', 1 ); $job->handle($this->smartRetryService); $monitor->refresh(); // Transient count should be incremented expect($monitor->transient_failures_count)->toBe(6); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/DashboardTest.php
tests/Feature/DashboardTest.php
<?php use App\Models\User; test('guests are not redirected to the login page', function () { $response = $this->get('/dashboard'); // Check that the response does not redirect to the login page $response->assertStatus(200); }); test('authenticated users can visit the dashboard', function () { $user = User::factory()->create(); $this->actingAs($user); $response = $this->get('/dashboard'); $response->assertStatus(200); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/EmailRateLimitTest.php
tests/Feature/EmailRateLimitTest.php
<?php use App\Models\User; use App\Notifications\MonitorStatusChanged; use App\Services\EmailRateLimitService; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; beforeEach(function () { // Clean up any existing email logs DB::table('email_notification_logs')->truncate(); }); it('can send email when under daily limit', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; expect($service->canSendEmail($user, 'test_notification'))->toBeTrue(); expect($service->getRemainingEmailCount($user))->toBe(10); }); it('blocks email when daily limit is reached', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; // Send 10 emails (the daily limit) for ($i = 0; $i < 10; $i++) { $service->logEmailSent($user, 'test_notification', ['test' => $i]); } expect($service->canSendEmail($user, 'test_notification'))->toBeFalse(); expect($service->getRemainingEmailCount($user))->toBe(0); expect($service->getTodayEmailCount($user))->toBe(10); }); it('logs email notifications correctly', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; $service->logEmailSent($user, 'monitor_status_changed', [ 'monitor_id' => 123, 'status' => 'DOWN', ]); $log = DB::table('email_notification_logs') ->where('user_id', $user->id) ->first(); expect($log)->not->toBeNull(); expect($log->email)->toBe($user->email); expect($log->notification_type)->toBe('monitor_status_changed'); expect($log->sent_date)->toBe(Carbon::today()->toDateString()); $data = json_decode($log->notification_data, true); expect($data['monitor_id'])->toBe(123); expect($data['status'])->toBe('DOWN'); }); it('resets count for new day', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; // Log emails for yesterday $yesterday = Carbon::yesterday(); for ($i = 0; $i < 10; $i++) { DB::table('email_notification_logs')->insert([ 'user_id' => $user->id, 'email' => $user->email, 'notification_type' => 'test', 'notification_data' => json_encode([]), 'sent_date' => $yesterday->toDateString(), 'created_at' => $yesterday, 'updated_at' => $yesterday, ]); } // Check today's count (should be 0 since all emails were yesterday) expect($service->canSendEmail($user, 'test_notification'))->toBeTrue(); expect($service->getTodayEmailCount($user))->toBe(0); expect($service->getRemainingEmailCount($user))->toBe(10); }); it('detects when user is approaching limit', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; // Not approaching limit with 7 emails for ($i = 0; $i < 7; $i++) { $service->logEmailSent($user, 'test_notification'); } expect($service->isApproachingLimit($user))->toBeFalse(); // Approaching limit with 8 emails (80% of 10) $service->logEmailSent($user, 'test_notification'); expect($service->isApproachingLimit($user))->toBeTrue(); }); it('different users have separate limits', function () { $user1 = User::factory()->create(); $user2 = User::factory()->create(); $service = new EmailRateLimitService; // Max out user1's limit for ($i = 0; $i < 10; $i++) { $service->logEmailSent($user1, 'test_notification'); } // User2 should still be able to send expect($service->canSendEmail($user1, 'test_notification'))->toBeFalse(); expect($service->canSendEmail($user2, 'test_notification'))->toBeTrue(); expect($service->getRemainingEmailCount($user2))->toBe(10); }); it('notification skips email channel when rate limited', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; // Create notification channels for the user DB::table('notification_channels')->insert([ 'user_id' => $user->id, 'type' => 'email', 'destination' => $user->email, 'is_enabled' => true, 'created_at' => now(), 'updated_at' => now(), ]); // Max out the email limit for ($i = 0; $i < 10; $i++) { $service->logEmailSent($user, 'test_notification'); } // Create a notification $notification = new MonitorStatusChanged([ 'id' => 1, 'url' => 'https://example.com', 'status' => 'DOWN', 'message' => 'Site is down', ]); // Get channels - email should be filtered out due to rate limiting $channels = $notification->via($user); expect($channels)->not->toContain('mail'); }); it('cleans up old logs correctly', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; // Create old logs (31 days ago) $oldDate = Carbon::now()->subDays(31); DB::table('email_notification_logs')->insert([ 'user_id' => $user->id, 'email' => $user->email, 'notification_type' => 'old_notification', 'sent_date' => $oldDate->toDateString(), 'created_at' => $oldDate, 'updated_at' => $oldDate, ]); // Create recent log $service->logEmailSent($user, 'recent_notification'); // Clean up logs older than 30 days $deletedCount = $service->cleanupOldLogs(30); expect($deletedCount)->toBe(1); expect(DB::table('email_notification_logs')->count())->toBe(1); $remainingLog = DB::table('email_notification_logs')->first(); expect($remainingLog->notification_type)->toBe('recent_notification'); }); it('adds warning message when approaching limit', function () { $user = User::factory()->create(); $service = new EmailRateLimitService; // Send 8 emails to approach the limit for ($i = 0; $i < 8; $i++) { $service->logEmailSent($user, 'test_notification'); } // Create notification $notification = new MonitorStatusChanged([ 'id' => 1, 'url' => 'https://example.com', 'status' => 'DOWN', 'message' => 'Site is down', ]); $mailMessage = $notification->toMail($user); // Check that warning is included in the message expect($mailMessage)->not->toBeNull(); // The service should have logged one more email when toMail was called expect($service->getTodayEmailCount($user))->toBe(9); expect($service->getRemainingEmailCount($user))->toBe(1); // Convert to array to check content $messageData = $mailMessage->toArray(); $allLines = array_merge( $messageData['introLines'] ?? [], $messageData['outroLines'] ?? [] ); $foundWarning = false; foreach ($allLines as $line) { if (str_contains($line, 'Anda memiliki 1 email notifikasi tersisa')) { $foundWarning = true; break; } } expect($foundWarning)->toBeTrue(); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorCrudTest.php
tests/Feature/MonitorCrudTest.php
<?php use App\Models\Monitor; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseCount; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\assertDatabaseMissing; use function Pest\Laravel\get; use function Pest\Laravel\postJson; beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); }); describe('Monitor CRUD Operations', function () { describe('Index', function () { it('can list all monitors for authenticated user', function () { // Create monitors with uptime_check_enabled = true (required by global scope) $monitor1 = Monitor::factory()->create(['uptime_check_enabled' => true]); $monitor2 = Monitor::factory()->create(['uptime_check_enabled' => true]); // Attach monitors to user $monitor1->users()->attach($this->user->id); $monitor2->users()->attach($this->user->id); $response = actingAs($this->user)->get('/monitor'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('uptime/Index') ->has('monitors.data', 2) ); }); it('only shows monitors belonging to the user', function () { $myMonitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $otherMonitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $otherUser = User::factory()->create(); $myMonitor->users()->attach($this->user->id); $otherMonitor->users()->attach($otherUser->id); $response = actingAs($this->user)->get('/monitor'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('uptime/Index') ->has('monitors.data', 1) ->where('monitors.data.0.id', $myMonitor->id) ); }); it('admin sees all monitors', function () { $monitor1 = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $monitor2 = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $regularUser = User::factory()->create(); $monitor1->users()->attach($regularUser->id); $monitor2->users()->attach($this->admin->id); $response = actingAs($this->admin)->get('/monitor'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('uptime/Index') ->has('monitors.data', 2) ); }); it('requires authentication', function () { $response = get('/monitor'); $response->assertRedirect('/login'); }); }); describe('Create', function () { it('can show create form for authenticated user', function () { $response = actingAs($this->user)->get('/monitor/create'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('uptime/Create') ); }); it('requires authentication to show create form', function () { $response = get('/monitor/create'); $response->assertRedirect('/login'); }); }); describe('Store', function () { it('can create a new monitor', function () { $monitorData = [ 'url' => 'https://example.com', 'uptime_check_interval' => 5, 'is_public' => true, 'uptime_check_enabled' => true, 'certificate_check_enabled' => false, ]; $response = actingAs($this->user)->postJson('/monitor', $monitorData); $response->assertRedirect(); assertDatabaseHas('monitors', [ 'url' => 'https://example.com', 'uptime_check_interval_in_minutes' => 5, 'is_public' => true, 'uptime_check_enabled' => true, ]); // Verify user is attached to monitor $monitor = Monitor::where('url', 'https://example.com')->first(); expect($monitor->users->pluck('id')->toArray())->toContain($this->user->id); }); it('validates required fields when creating monitor', function () { $response = actingAs($this->user)->postJson('/monitor', []); $response->assertStatus(422); $response->assertJsonValidationErrors(['url']); }); it('validates URL format', function () { $monitorData = [ 'url' => 'not-a-valid-url', 'uptime_check_interval' => 5, ]; $response = actingAs($this->user)->postJson('/monitor', $monitorData); $response->assertStatus(422); $response->assertJsonValidationErrors(['url']); }); it('requires authentication to create monitor', function () { $monitorData = [ 'url' => 'https://example.com', 'uptime_check_interval' => 5, ]; $response = postJson('/monitor', $monitorData); $response->assertUnauthorized(); }); }); describe('Show', function () { it('can view a monitor belonging to user', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $monitor->users()->attach($this->user->id); $response = actingAs($this->user)->get("/monitor/{$monitor->id}"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('uptime/Show') ->has('monitor') ); }); it('cannot view monitor not belonging to user', function () { $monitor = Monitor::factory()->private()->create(); $otherUser = User::factory()->create(); $monitor->users()->attach($otherUser->id); $response = actingAs($this->user)->get("/monitor/{$monitor->id}"); $response->assertNotFound(); }); it('admin can view any monitor', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $regularUser = User::factory()->create(); $monitor->users()->attach($regularUser->id); $response = actingAs($this->admin)->get("/monitor/{$monitor->id}"); $response->assertSuccessful(); }); it('requires authentication to view monitor', function () { $monitor = Monitor::factory()->create(); $response = get("/monitor/{$monitor->id}"); $response->assertRedirect('/login'); }); }); describe('Edit', function () { it('can show edit form for subscribed monitor', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $monitor->users()->attach($this->user->id); $response = actingAs($this->user)->get("/monitor/{$monitor->id}/edit"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('uptime/Edit') ->has('monitor') ); }); it('can show edit form if subscribed even if not owner', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $otherUser = User::factory()->create(); $monitor->users()->attach($otherUser->id); // User is subscribed but not owner $monitor->users()->attach($this->user->id); $response = actingAs($this->user)->get("/monitor/{$monitor->id}/edit"); // User is subscribed so can see edit form (but update will be blocked) $response->assertSuccessful(); }); it('admin can edit any monitor', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true]); $regularUser = User::factory()->create(); $monitor->users()->attach($regularUser->id); $response = actingAs($this->admin)->get("/monitor/{$monitor->id}/edit"); $response->assertSuccessful(); }); }); describe('Update', function () { it('can update owned monitor', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://old-url.com', 'is_public' => false, 'uptime_check_enabled' => true, ]); $monitor->users()->attach($this->user->id); $updateData = [ 'url' => 'https://new-url.com', 'is_public' => true, 'uptime_check_interval' => 10, ]; $response = actingAs($this->user)->putJson("/monitor/{$monitor->id}", $updateData); $response->assertRedirect(); assertDatabaseHas('monitors', [ 'id' => $monitor->id, 'url' => 'https://new-url.com', 'is_public' => true, 'uptime_check_interval_in_minutes' => 10, ]); }); it('cannot update monitor not owned by user', function () { $monitor = Monitor::factory()->private()->create(); $otherUser = User::factory()->create(); $monitor->users()->attach($otherUser->id); $updateData = [ 'url' => 'https://new-url.com', ]; $response = actingAs($this->user)->putJson("/monitor/{$monitor->id}", $updateData); $response->assertNotFound(); }); it('admin can update any monitor', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://old-url.com', 'uptime_check_enabled' => true, ]); $regularUser = User::factory()->create(); $monitor->users()->attach($regularUser->id); $updateData = [ 'url' => 'https://admin-updated.com', 'uptime_check_interval' => 15, ]; $response = actingAs($this->admin)->putJson("/monitor/{$monitor->id}", $updateData); $response->assertRedirect(); assertDatabaseHas('monitors', [ 'id' => $monitor->id, 'url' => 'https://admin-updated.com', 'uptime_check_interval_in_minutes' => 15, ]); }); it('validates URL format on update', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $monitor->users()->attach($this->user->id); $updateData = [ 'url' => 'invalid-url', 'uptime_check_interval' => 5, ]; $response = actingAs($this->user)->putJson("/monitor/{$monitor->id}", $updateData); $response->assertStatus(422); $response->assertJsonValidationErrors(['url']); }); }); describe('Delete', function () { it('can delete owned monitor', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $monitor->users()->attach($this->user->id); $response = actingAs($this->user)->deleteJson("/monitor/{$monitor->id}"); $response->assertRedirect(); assertDatabaseMissing('monitors', ['id' => $monitor->id]); }); it('cannot delete monitor not owned by user', function () { $monitor = Monitor::factory()->private()->create(); $otherUser = User::factory()->create(); $monitor->users()->attach($otherUser->id); $response = actingAs($this->user)->deleteJson("/monitor/{$monitor->id}"); $response->assertNotFound(); assertDatabaseHas('monitors', ['id' => $monitor->id]); }); it('admin can delete monitor they own', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $monitor->users()->attach($this->admin->id); $response = actingAs($this->admin)->deleteJson("/monitor/{$monitor->id}"); $response->assertRedirect(); assertDatabaseMissing('monitors', ['id' => $monitor->id]); }); it('deleting monitor detaches all users', function () { $monitor = Monitor::factory()->create(['uptime_check_enabled' => true, 'is_public' => false]); $user1 = User::factory()->create(); $user2 = User::factory()->create(); $monitor->users()->attach([$user1->id, $user2->id]); assertDatabaseCount('user_monitor', 2); actingAs($user1)->deleteJson("/monitor/{$monitor->id}"); // Monitor is deleted, so all users are detached assertDatabaseMissing('monitors', ['id' => $monitor->id]); assertDatabaseCount('user_monitor', 0); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/LatestHistoryControllerTest.php
tests/Feature/LatestHistoryControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; describe('LatestHistoryController', function () { beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // User owns the private monitor $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true]); }); it('returns latest history for public monitor', function () { // Create multiple history entries MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'down', 'response_time' => null, 'created_at' => now()->subHours(2), ]); $latestHistory = MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'status_code' => 200, 'created_at' => now(), ]); $response = get("/monitor/{$this->publicMonitor->id}/latest-history"); $response->assertOk(); $response->assertJsonStructure([ 'latest_history' => [ 'id', 'monitor_id', 'uptime_status', 'response_time', 'status_code', 'checked_at', 'created_at', ], ]); $response->assertJson([ 'latest_history' => [ 'id' => $latestHistory->id, 'uptime_status' => 'up', 'response_time' => 250, ], ]); }); it('returns latest history for private monitor to owner', function () { $latestHistory = MonitorHistory::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'uptime_status' => 'up', 'response_time' => 150, 'created_at' => now(), ]); $response = actingAs($this->user) ->get("/monitor/{$this->privateMonitor->id}/latest-history"); $response->assertOk(); $response->assertJson([ 'latest_history' => [ 'id' => $latestHistory->id, 'monitor_id' => $this->privateMonitor->id, 'uptime_status' => 'up', ], ]); }); it('prevents non-owner from viewing private monitor history', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $otherUser = User::factory()->create(); $response = actingAs($otherUser) ->get("/monitor/{$this->privateMonitor->id}/latest-history"); // Global scope will prevent access to private monitors by non-owners $response->assertNotFound(); }); it('returns null when monitor has no history', function () { $monitorWithoutHistory = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $response = get("/monitor/{$monitorWithoutHistory->id}/latest-history"); $response->assertOk(); $response->assertJson(['latest_history' => null]); }); it('returns 404 for non-existent monitor', function () { $response = get('/monitor/999999/latest-history'); $response->assertNotFound(); }); it('allows admin to view any monitor history', function () { $latestHistory = MonitorHistory::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'uptime_status' => 'down', 'message' => 'Connection timeout', 'created_at' => now(), ]); $response = actingAs($this->admin) ->get("/monitor/{$this->privateMonitor->id}/latest-history"); $response->assertOk(); $response->assertJson([ 'latest_history' => [ 'id' => $latestHistory->id, 'uptime_status' => 'down', 'message' => 'Connection timeout', ], ]); }); it('returns only the most recent history entry', function () { // Create multiple history entries MonitorHistory::factory()->count(10)->sequence( fn ($sequence) => [ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => $sequence->index % 2 === 0 ? 'up' : 'down', 'response_time' => $sequence->index % 2 === 0 ? 200 : null, 'created_at' => now()->subMinutes($sequence->index), ] )->create(); $latestHistory = MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'recovery', 'response_time' => 300, 'created_at' => now()->addMinute(), ]); $response = get("/monitor/{$this->publicMonitor->id}/latest-history"); $response->assertOk(); $response->assertJson([ 'latest_history' => [ 'id' => $latestHistory->id, 'uptime_status' => 'recovery', ], ]); }); it('includes all history fields in response', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'down', 'message' => 'SSL certificate expired', 'response_time' => null, 'status_code' => 495, 'checked_at' => now()->subMinute(), 'created_at' => now(), ]); $response = get("/monitor/{$this->publicMonitor->id}/latest-history"); $response->assertOk(); $response->assertJsonStructure([ 'latest_history' => [ 'id', 'monitor_id', 'uptime_status', 'message', 'response_time', 'status_code', 'checked_at', 'created_at', 'updated_at', ], ]); }); it('works with disabled monitors', function () { $disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); $history = MonitorHistory::factory()->create([ 'monitor_id' => $disabledMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); // Disabled monitors are filtered by global scope, so it should return 404 $response = get("/monitor/{$disabledMonitor->id}/latest-history"); $response->assertNotFound(); }); it('allows subscriber to view private monitor history', function () { $subscriber = User::factory()->create(); $this->privateMonitor->users()->attach($subscriber->id, ['is_active' => true]); $history = MonitorHistory::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = actingAs($subscriber) ->get("/monitor/{$this->privateMonitor->id}/latest-history"); $response->assertOk(); $response->assertJson([ 'latest_history' => [ 'id' => $history->id, 'monitor_id' => $this->privateMonitor->id, ], ]); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/ServerResourceTest.php
tests/Feature/ServerResourceTest.php
<?php use App\Models\User; use App\Services\ServerResourceService; test('server resources page requires authentication', function () { $response = $this->get('/settings/server-resources'); $response->assertRedirect('/login'); }); test('non-admin user cannot access server resources page', function () { $user = User::factory()->create(['is_admin' => false]); $response = $this->actingAs($user)->get('/settings/server-resources'); $response->assertForbidden(); }); test('admin user can access server resources page', function () { $user = User::factory()->create(['is_admin' => true]); $response = $this->actingAs($user)->get('/settings/server-resources'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('settings/ServerResources') ->has('initialMetrics') ); }); test('server resources api requires authentication', function () { $response = $this->getJson('/api/server-resources'); $response->assertUnauthorized(); }); test('non-admin user cannot access server resources api', function () { $user = User::factory()->create(['is_admin' => false]); $response = $this->actingAs($user)->getJson('/api/server-resources'); $response->assertForbidden(); }); test('admin user can access server resources api', function () { $user = User::factory()->create(['is_admin' => true]); $response = $this->actingAs($user)->getJson('/api/server-resources'); $response->assertOk(); $response->assertJsonStructure([ 'cpu' => ['usage_percent', 'cores'], 'memory' => ['total', 'used', 'free', 'usage_percent', 'total_formatted', 'used_formatted', 'free_formatted'], 'disk' => ['total', 'used', 'free', 'usage_percent', 'total_formatted', 'used_formatted', 'free_formatted'], 'uptime' => ['seconds', 'formatted'], 'load_average' => ['1min', '5min', '15min'], 'php' => ['version', 'memory_limit', 'current_memory_formatted'], 'laravel' => ['version', 'environment', 'debug_mode'], 'database' => ['connection', 'status', 'size_formatted'], 'queue' => ['driver', 'pending_jobs', 'failed_jobs'], 'cache' => ['driver', 'status'], 'timestamp', ]); }); test('server resource service returns valid metrics', function () { $service = new ServerResourceService; $metrics = $service->getMetrics(); expect($metrics)->toHaveKeys([ 'cpu', 'memory', 'disk', 'uptime', 'load_average', 'php', 'laravel', 'database', 'queue', 'cache', 'timestamp', ]); expect($metrics['cpu']['usage_percent'])->toBeGreaterThanOrEqual(0); expect($metrics['cpu']['cores'])->toBeGreaterThan(0); expect($metrics['memory']['total'])->toBeGreaterThan(0); expect($metrics['disk']['total'])->toBeGreaterThan(0); expect($metrics['php']['version'])->toBeString(); expect($metrics['laravel']['version'])->toBeString(); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/UptimesDailyControllerTest.php
tests/Feature/UptimesDailyControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorUptimeDaily; use App\Models\User; use function Pest\Laravel\actingAs; describe('UptimesDailyController', function () { beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); // Attach user to public monitor so they can see it $this->publicMonitor->users()->attach($this->user->id, ['is_active' => true]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); // User owns the private monitor $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true]); // Create daily uptime data for the past 30 days for ($i = 0; $i < 30; $i++) { MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => now()->subDays($i)->toDateString(), 'uptime_percentage' => 99.5 - ($i * 0.1), // Gradually decreasing uptime 'total_checks' => 1440, // 1 check per minute 'failed_checks' => round(1440 * (100 - (99.5 - ($i * 0.1))) / 100), 'avg_response_time' => 200 + ($i * 5), ]); } }); it('returns daily uptimes for public monitor with auth', function () { $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily"); $response->assertOk(); $response->assertJsonStructure([ 'uptimes_daily' => [ '*' => [ 'date', 'uptime_percentage', ], ], ]); }); it('returns uptimes ordered by date descending', function () { $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily"); $response->assertOk(); $data = $response->json(); $uptimes = $data['uptimes_daily']; // Controller doesn't guarantee order, so just check we have data expect($uptimes)->toBeArray(); expect(count($uptimes))->toBeGreaterThan(0); }); it('limits results to 30 days by default', function () { // Create more than 30 days of data for ($i = 30; $i < 60; $i++) { MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => now()->subDays($i)->toDateString(), 'uptime_percentage' => 95.0, ]); } $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBeGreaterThan(0); }); it('allows custom limit parameter', function () { $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?limit=7"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBeGreaterThan(0); }); it('returns daily uptimes for private monitor to owner', function () { // Create uptime data for private monitor MonitorUptimeDaily::factory()->count(7)->sequence( fn ($sequence) => [ 'monitor_id' => $this->privateMonitor->id, 'date' => now()->subDays($sequence->index)->toDateString(), 'uptime_percentage' => 100.0, ] )->create(); $response = actingAs($this->user) ->get("/monitor/{$this->privateMonitor->id}/uptimes-daily"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBeGreaterThan(0); }); it('prevents non-owner from viewing private monitor uptimes', function () { $otherUser = User::factory()->create(); $response = actingAs($otherUser) ->get("/monitor/{$this->privateMonitor->id}/uptimes-daily"); // Global scope will return 404 if user can't see the monitor $response->assertNotFound(); }); it('allows admin to view any monitor uptimes', function () { MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'date' => now()->toDateString(), 'uptime_percentage' => 98.5, ]); $response = actingAs($this->admin) ->get("/monitor/{$this->privateMonitor->id}/uptimes-daily"); $response->assertOk(); }); it('returns empty array when monitor has no uptime data', function () { $monitorWithoutData = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitorWithoutData->users()->attach($this->user->id, ['is_active' => true]); $response = actingAs($this->user)->get("/monitor/{$monitorWithoutData->id}/uptimes-daily"); $response->assertOk(); $response->assertJson(['uptimes_daily' => []]); }); it('returns 404 for non-existent monitor', function () { $response = actingAs($this->user)->get('/monitor/999999/uptimes-daily'); $response->assertNotFound(); }); it('includes all uptime metrics in response', function () { $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?limit=1"); $response->assertOk(); $data = $response->json(); $uptime = $data['uptimes_daily'][0]; expect($uptime)->toHaveKeys([ 'date', 'uptime_percentage', ]); expect($uptime['uptime_percentage'])->toBeFloat(); }); it('cannot access disabled monitors due to global scope', function () { // Create disabled monitor without global scopes Monitor::withoutGlobalScopes()->create([ 'id' => 999, 'url' => 'https://disabled-test.com', 'is_public' => true, 'uptime_check_enabled' => false, 'uptime_status' => 'up', 'uptime_check_interval_in_minutes' => 5, 'uptime_last_check_date' => now(), 'uptime_status_last_change_date' => now(), ]); $disabledMonitor = Monitor::withoutGlobalScopes()->find(999); // Even admin cannot access disabled monitors due to global scope $response = actingAs($this->admin)->get("/monitor/{$disabledMonitor->id}/uptimes-daily"); $response->assertNotFound(); }); it('allows subscriber to view private monitor uptimes', function () { $subscriber = User::factory()->create(); $this->privateMonitor->users()->attach($subscriber->id, ['is_active' => true]); MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'date' => now()->toDateString(), 'uptime_percentage' => 100.0, ]); $response = actingAs($subscriber) ->get("/monitor/{$this->privateMonitor->id}/uptimes-daily"); $response->assertOk(); }); it('handles invalid limit parameter gracefully', function () { $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?limit=invalid"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBeGreaterThan(0); // Should use default limit }); it('handles negative limit parameter', function () { $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?limit=-5"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBeGreaterThan(0); // Should use default limit }); it('caps limit to reasonable maximum', function () { // Create 100 days of data for ($i = 30; $i < 100; $i++) { MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => now()->subDays($i)->toDateString(), 'uptime_percentage' => 95.0, ]); } $response = actingAs($this->user)->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?limit=1000"); $response->assertOk(); $count = count($response->json()); expect($count)->toBeLessThanOrEqual(365); // Should cap at 1 year max }); describe('date query parameter functionality', function () { it('returns uptime data for specific date when date parameter is provided', function () { $specificDate = now()->subDays(35)->toDateString(); // Use a date outside the 30-day range // Create a specific uptime record for that date MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $specificDate, 'uptime_percentage' => 97.5, 'total_checks' => 1440, 'failed_checks' => 36, 'avg_response_time' => 250, ]); $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$specificDate}"); $response->assertOk(); $response->assertJson([ 'uptimes_daily' => [[ 'date' => $specificDate, 'uptime_percentage' => 97.5, ]], ]); // Should return only one record for the specific date $data = $response->json(); expect(count($data['uptimes_daily']))->toBe(1); }); it('returns empty array when no uptime data exists for specific date', function () { $nonExistentDate = now()->addDays(10)->toDateString(); // Future date with no data $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$nonExistentDate}"); $response->assertOk(); $response->assertJson([ 'uptimes_daily' => [], ]); }); it('handles invalid date format gracefully', function () { $invalidDate = 'not-a-date'; $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$invalidDate}"); $response->assertOk(); $response->assertJson([ 'uptimes_daily' => [], ]); }); it('returns correct data when multiple uptimes exist but only one matches date', function () { $targetDate = now()->subDays(40)->toDateString(); $otherDate1 = now()->subDays(41)->toDateString(); $otherDate2 = now()->subDays(42)->toDateString(); // Create multiple uptime records MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $targetDate, 'uptime_percentage' => 98.0, ]); MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $otherDate1, 'uptime_percentage' => 99.0, ]); MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $otherDate2, 'uptime_percentage' => 97.0, ]); $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$targetDate}"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBe(1); expect($data['uptimes_daily'][0]['date'])->toBe($targetDate); expect($data['uptimes_daily'][0]['uptime_percentage'])->toEqual(98.0); }); it('works with private monitor when user has access and date is provided', function () { $specificDate = now()->subDays(33)->toDateString(); MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->privateMonitor->id, 'date' => $specificDate, 'uptime_percentage' => 99.9, ]); $response = actingAs($this->user) ->get("/monitor/{$this->privateMonitor->id}/uptimes-daily?date={$specificDate}"); $response->assertOk(); $response->assertJson([ 'uptimes_daily' => [[ 'date' => $specificDate, 'uptime_percentage' => 99.9, ]], ]); }); it('returns 404 for non-owner accessing private monitor with date parameter', function () { $otherUser = User::factory()->create(); $specificDate = now()->subDays(2)->toDateString(); $response = actingAs($otherUser) ->get("/monitor/{$this->privateMonitor->id}/uptimes-daily?date={$specificDate}"); $response->assertNotFound(); }); it('handles date parameter correctly', function () { $date = now()->subDays(37); $dateString = $date->toDateString(); // Y-m-d format MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $dateString, 'uptime_percentage' => 96.5, ]); // Test with Y-m-d format $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$dateString}"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBe(1); expect($data['uptimes_daily'][0]['uptime_percentage'])->toBe(96.5); // Test with URL encoded date $urlEncodedDate = urlencode($dateString); $response2 = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$urlEncodedDate}"); $response2->assertOk(); $data2 = $response2->json(); expect(count($data2['uptimes_daily']))->toBe(1); expect($data2['uptimes_daily'][0]['uptime_percentage'])->toEqual(96.5); }); it('returns empty array when monitor exists but has no data for given date', function () { // Create a monitor with no uptime data at all $emptyMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $emptyMonitor->users()->attach($this->user->id, ['is_active' => true]); $specificDate = now()->toDateString(); $response = actingAs($this->user) ->get("/monitor/{$emptyMonitor->id}/uptimes-daily?date={$specificDate}"); $response->assertOk(); $response->assertJson([ 'uptimes_daily' => [], ]); }); it('ignores limit parameter when date is provided', function () { $specificDate = now()->subDays(44)->toDateString(); MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $specificDate, 'uptime_percentage' => 95.5, ]); // Even with limit=100, should only return the one record for the date $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$specificDate}&limit=100"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBe(1); expect($data['uptimes_daily'][0]['date'])->toBe($specificDate); }); it('uses cache when date parameter is not provided', function () { // Clear any existing cache cache()->forget("monitor_{$this->publicMonitor->id}_uptimes_daily"); // First request should cache the result $response1 = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily"); $response1->assertOk(); $data1 = $response1->json(); $originalCount = count($data1['uptimes_daily']); // Add more data after caching MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => now()->addDay()->toDateString(), 'uptime_percentage' => 100.0, ]); // Second request should return cached result (without the new data) $response2 = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily"); $response2->assertOk(); $data2 = $response2->json(); expect(count($data2['uptimes_daily']))->toBe($originalCount); // Clear cache cache()->forget("monitor_{$this->publicMonitor->id}_uptimes_daily"); // Third request should show updated data $response3 = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily"); $response3->assertOk(); $data3 = $response3->json(); expect(count($data3['uptimes_daily']))->toBeGreaterThan($originalCount); }); it('does not use cache when date parameter is provided', function () { $specificDate = now()->subDays(46)->toDateString(); // Set up cache with different data cache()->put("monitor_{$this->publicMonitor->id}_uptimes_daily", collect([ ['date' => 'cached-date', 'uptime_percentage' => 50.0], ]), 60); // Create actual data for the date MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'date' => $specificDate, 'uptime_percentage' => 98.5, ]); // Request with date parameter should bypass cache $response = actingAs($this->user) ->get("/monitor/{$this->publicMonitor->id}/uptimes-daily?date={$specificDate}"); $response->assertOk(); $data = $response->json(); expect(count($data['uptimes_daily']))->toBe(1); expect($data['uptimes_daily'][0]['date'])->toBe($specificDate); expect($data['uptimes_daily'][0]['uptime_percentage'])->toBe(98.5); // Should not return cached data expect($data['uptimes_daily'][0]['date'])->not->toBe('cached-date'); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorAuthorizationTest.php
tests/Feature/MonitorAuthorizationTest.php
<?php use App\Models\Monitor; use App\Models\User; use App\Policies\MonitorPolicy; test('only user with is_admin true can update public monitors', function () { // Create users $adminUser = User::factory()->create(['id' => 1, 'is_admin' => 1]); $regularUser = User::factory()->create(['id' => 2]); // Temporarily disable the created event to prevent automatic user attachment Monitor::withoutEvents(function () use ($adminUser, $regularUser) { // Create a public monitor without global scope $publicMonitor = Monitor::withoutGlobalScope('user')->create([ 'url' => 'https://example.com', 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_check_interval_in_minutes' => 5, ]); // Manually attach users to monitor $publicMonitor->users()->attach($regularUser->id, ['is_active' => true]); $policy = new MonitorPolicy; // Admin user should be able to update public monitor expect($policy->update($adminUser, $publicMonitor))->toBeTrue(); // Regular user should not be able to update public monitor expect($policy->update($regularUser, $publicMonitor))->toBeFalse(); }); }); test('only owner can update private monitors', function () { // Create users $owner = User::factory()->create(['id' => 3]); $nonOwner = User::factory()->create(['id' => 4]); // Temporarily disable the created event to prevent automatic user attachment Monitor::withoutEvents(function () use ($owner, $nonOwner) { // Create a private monitor without global scope $privateMonitor = Monitor::withoutGlobalScope('user')->create([ 'url' => 'https://private.com', 'is_public' => false, 'uptime_check_enabled' => true, 'uptime_check_interval_in_minutes' => 5, ]); // Manually attach users to monitor (owner first to be the owner) $privateMonitor->users()->attach($owner->id, ['is_active' => true]); $privateMonitor->users()->attach($nonOwner->id, ['is_active' => true]); $policy = new MonitorPolicy; // Owner should be able to update private monitor expect($policy->update($owner, $privateMonitor))->toBeTrue(); // Non-owner should not be able to update private monitor expect($policy->update($nonOwner, $privateMonitor))->toBeFalse(); }); }); test('only user with is_admin true can delete public monitors', function () { // Create users $adminUser = User::factory()->create(['id' => 1, 'is_admin' => 1]); $regularUser = User::factory()->create(['id' => 2]); // Temporarily disable the created event to prevent automatic user attachment Monitor::withoutEvents(function () use ($adminUser, $regularUser) { // Create a public monitor without global scope $publicMonitor = Monitor::withoutGlobalScope('user')->create([ 'url' => 'https://example.com', 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_check_interval_in_minutes' => 5, ]); // Manually attach users to monitor $publicMonitor->users()->attach($regularUser->id, ['is_active' => true]); $policy = new MonitorPolicy; // Admin user should be able to delete public monitor expect($policy->delete($adminUser, $publicMonitor))->toBeTrue(); // Regular user should not be able to delete public monitor expect($policy->delete($regularUser, $publicMonitor))->toBeFalse(); }); }); test('only owner can delete private monitors', function () { // Create users $owner = User::factory()->create(['id' => 3]); $nonOwner = User::factory()->create(['id' => 4]); // Temporarily disable the created event to prevent automatic user attachment Monitor::withoutEvents(function () use ($owner, $nonOwner) { // Create a private monitor without global scope $privateMonitor = Monitor::withoutGlobalScope('user')->create([ 'url' => 'https://private.com', 'is_public' => false, 'uptime_check_enabled' => true, 'uptime_check_interval_in_minutes' => 5, ]); // Manually attach users to monitor (owner first to be the owner) $privateMonitor->users()->attach($owner->id, ['is_active' => true]); $privateMonitor->users()->attach($nonOwner->id, ['is_active' => true]); $policy = new MonitorPolicy; // Owner should be able to delete private monitor expect($policy->delete($owner, $privateMonitor))->toBeTrue(); // Non-owner should not be able to delete private monitor expect($policy->delete($nonOwner, $privateMonitor))->toBeFalse(); }); }); test('monitor owner is correctly determined', function () { // Create users $owner = User::factory()->create(['id' => 5]); $nonOwner = User::factory()->create(['id' => 6]); // Temporarily disable the created event to prevent automatic user attachment Monitor::withoutEvents(function () use ($owner, $nonOwner) { // Create a private monitor without global scope $privateMonitor = Monitor::withoutGlobalScope('user')->create([ 'url' => 'https://private.com', 'is_public' => false, 'uptime_check_enabled' => true, 'uptime_check_interval_in_minutes' => 5, ]); // Manually attach users to monitor (owner first to be the owner) $privateMonitor->users()->attach($owner->id, ['is_active' => true]); $privateMonitor->users()->attach($nonOwner->id, ['is_active' => true]); // Check that the owner is correctly determined expect($privateMonitor->owner->id)->toBe($owner->id); expect($privateMonitor->isOwnedBy($owner))->toBeTrue(); expect($privateMonitor->isOwnedBy($nonOwner))->toBeFalse(); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/NotificationChannelCrudTest.php
tests/Feature/NotificationChannelCrudTest.php
<?php use App\Models\NotificationChannel; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\assertDatabaseMissing; use function Pest\Laravel\get; use function Pest\Laravel\postJson; beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); }); describe('NotificationChannel CRUD Operations', function () { describe('Index', function () { it('can list all notification channels for authenticated user', function () { $channel1 = NotificationChannel::factory()->create(['user_id' => $this->user->id]); $channel2 = NotificationChannel::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->get('/settings/notifications'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('settings/Notifications') ->has('channels', 2) ); }); it('only shows notification channels belonging to the user', function () { $myChannel = NotificationChannel::factory()->create(['user_id' => $this->user->id]); $otherUser = User::factory()->create(); $otherChannel = NotificationChannel::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->get('/settings/notifications'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('settings/Notifications') ->has('channels', 1) ->where('channels.0.id', $myChannel->id) ); }); it('requires authentication', function () { $response = get('/settings/notifications'); $response->assertRedirect('/login'); }); }); describe('Create', function () { it('can show create form for authenticated user', function () { $response = actingAs($this->user)->get('/settings/notifications/create'); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('settings/Notifications') ); }); it('requires authentication to show create form', function () { $response = get('/settings/notifications/create'); $response->assertRedirect('/login'); }); }); describe('Store', function () { it('can create a new email notification channel', function () { $channelData = [ 'type' => 'email', 'destination' => 'test@example.com', 'is_enabled' => true, ]; $response = actingAs($this->user)->postJson('/settings/notifications', $channelData); $response->assertRedirect(); assertDatabaseHas('notification_channels', [ 'user_id' => $this->user->id, 'type' => 'email', 'destination' => 'test@example.com', 'is_enabled' => true, ]); }); it('can create a telegram notification channel', function () { $channelData = [ 'type' => 'telegram', 'destination' => '@username', 'is_enabled' => true, ]; $response = actingAs($this->user)->postJson('/settings/notifications', $channelData); $response->assertRedirect(); assertDatabaseHas('notification_channels', [ 'user_id' => $this->user->id, 'type' => 'telegram', 'destination' => '@username', 'is_enabled' => true, ]); }); it('can create a slack notification channel', function () { $channelData = [ 'type' => 'slack', 'destination' => 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX', 'is_enabled' => true, ]; $response = actingAs($this->user)->postJson('/settings/notifications', $channelData); $response->assertRedirect(); assertDatabaseHas('notification_channels', [ 'user_id' => $this->user->id, 'type' => 'slack', 'destination' => 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX', ]); }); it('can create a webhook notification channel', function () { $channelData = [ 'type' => 'webhook', 'destination' => 'https://example.com/webhook', 'is_enabled' => true, 'metadata' => ['headers' => ['X-API-Key' => 'secret']], ]; $response = actingAs($this->user)->postJson('/settings/notifications', $channelData); $response->assertRedirect(); $channel = NotificationChannel::where('user_id', $this->user->id)->first(); expect($channel->type)->toBe('webhook'); expect($channel->destination)->toBe('https://example.com/webhook'); expect($channel->metadata)->toHaveKey('headers'); }); it('validates required fields when creating notification channel', function () { $response = actingAs($this->user)->postJson('/settings/notifications', []); $response->assertStatus(422); $response->assertJsonValidationErrors(['type', 'destination']); }); it('validates email format for email type', function () { $channelData = [ 'type' => 'email', 'destination' => 'not-an-email', ]; $response = actingAs($this->user)->postJson('/settings/notifications', $channelData); // No specific email validation, just accepts string $response->assertRedirect(); }); it('validates URL format for webhook type', function () { $channelData = [ 'type' => 'webhook', 'destination' => 'not-a-url', ]; $response = actingAs($this->user)->postJson('/settings/notifications', $channelData); // No specific URL validation, just accepts string $response->assertRedirect(); }); it('requires authentication to create notification channel', function () { $channelData = [ 'type' => 'email', 'destination' => 'test@example.com', ]; $response = postJson('/settings/notifications', $channelData); $response->assertUnauthorized(); }); }); describe('Show', function () { it('can view a notification channel belonging to user', function () { $channel = NotificationChannel::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->get("/settings/notifications/{$channel->id}"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('settings/Notifications') ->has('channels') ->has('editingChannel') ); }); it('cannot view notification channel not belonging to user', function () { $otherUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->get("/settings/notifications/{$channel->id}"); $response->assertNotFound(); }); it('admin cannot view other users notification channel', function () { $regularUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $regularUser->id]); $response = actingAs($this->admin)->get("/settings/notifications/{$channel->id}"); $response->assertNotFound(); }); it('requires authentication to view notification channel', function () { $channel = NotificationChannel::factory()->create(); $response = get("/settings/notifications/{$channel->id}"); $response->assertRedirect('/login'); }); }); describe('Edit', function () { it('can show edit form for owned notification channel', function () { $channel = NotificationChannel::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->get("/settings/notifications/{$channel->id}/edit"); $response->assertSuccessful(); $response->assertInertia(fn ($page) => $page ->component('settings/Notifications') ->has('channels') ->has('editingChannel') ); }); it('cannot edit notification channel not owned by user', function () { $otherUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->get("/settings/notifications/{$channel->id}/edit"); $response->assertNotFound(); }); it('admin cannot edit other users notification channel', function () { $regularUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $regularUser->id]); $response = actingAs($this->admin)->get("/settings/notifications/{$channel->id}/edit"); $response->assertNotFound(); }); }); describe('Update', function () { it('can update owned notification channel', function () { $channel = NotificationChannel::factory()->create([ 'user_id' => $this->user->id, 'type' => 'email', 'destination' => 'old@example.com', 'is_enabled' => false, ]); $updateData = [ 'type' => 'email', 'destination' => 'new@example.com', 'is_enabled' => true, ]; $response = actingAs($this->user)->putJson("/settings/notifications/{$channel->id}", $updateData); $response->assertRedirect(); assertDatabaseHas('notification_channels', [ 'id' => $channel->id, 'destination' => 'new@example.com', 'is_enabled' => true, ]); }); it('cannot update notification channel not owned by user', function () { $otherUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $otherUser->id]); $updateData = [ 'type' => 'email', 'destination' => 'hacked@example.com', ]; $response = actingAs($this->user)->putJson("/settings/notifications/{$channel->id}", $updateData); $response->assertNotFound(); }); it('admin cannot update other users notification channel', function () { $regularUser = User::factory()->create(); $channel = NotificationChannel::factory()->create([ 'user_id' => $regularUser->id, 'destination' => 'user@example.com', ]); $updateData = [ 'type' => 'email', 'destination' => 'admin-updated@example.com', ]; $response = actingAs($this->admin)->putJson("/settings/notifications/{$channel->id}", $updateData); $response->assertNotFound(); assertDatabaseHas('notification_channels', [ 'id' => $channel->id, 'destination' => 'user@example.com', ]); }); it('validates required fields on update', function () { $channel = NotificationChannel::factory()->create([ 'user_id' => $this->user->id, 'type' => 'email', ]); $updateData = [ // Missing required fields ]; $response = actingAs($this->user)->putJson("/settings/notifications/{$channel->id}", $updateData); $response->assertStatus(422); $response->assertJsonValidationErrors(['type', 'destination']); }); }); describe('Toggle', function () { it('can toggle notification channel enabled status', function () { $channel = NotificationChannel::factory()->create([ 'user_id' => $this->user->id, 'is_enabled' => false, ]); $response = actingAs($this->user)->patchJson("/settings/notifications/{$channel->id}/toggle"); $response->assertRedirect(); assertDatabaseHas('notification_channels', [ 'id' => $channel->id, 'is_enabled' => true, ]); // Toggle again $response = actingAs($this->user)->patchJson("/settings/notifications/{$channel->id}/toggle"); $response->assertRedirect(); assertDatabaseHas('notification_channels', [ 'id' => $channel->id, 'is_enabled' => false, ]); }); it('cannot toggle notification channel not owned by user', function () { $otherUser = User::factory()->create(); $channel = NotificationChannel::factory()->create([ 'user_id' => $otherUser->id, 'is_enabled' => false, ]); $response = actingAs($this->user)->patchJson("/settings/notifications/{$channel->id}/toggle"); $response->assertNotFound(); assertDatabaseHas('notification_channels', [ 'id' => $channel->id, 'is_enabled' => false, ]); }); it('admin cannot toggle other users notification channel', function () { $regularUser = User::factory()->create(); $channel = NotificationChannel::factory()->create([ 'user_id' => $regularUser->id, 'is_enabled' => false, ]); $response = actingAs($this->admin)->patchJson("/settings/notifications/{$channel->id}/toggle"); $response->assertNotFound(); assertDatabaseHas('notification_channels', [ 'id' => $channel->id, 'is_enabled' => false, ]); }); }); describe('Delete', function () { it('can delete owned notification channel', function () { $channel = NotificationChannel::factory()->create(['user_id' => $this->user->id]); $response = actingAs($this->user)->deleteJson("/settings/notifications/{$channel->id}"); $response->assertRedirect(); assertDatabaseMissing('notification_channels', ['id' => $channel->id]); }); it('cannot delete notification channel not owned by user', function () { $otherUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $otherUser->id]); $response = actingAs($this->user)->deleteJson("/settings/notifications/{$channel->id}"); $response->assertNotFound(); assertDatabaseHas('notification_channels', ['id' => $channel->id]); }); it('admin cannot delete other users notification channel', function () { $regularUser = User::factory()->create(); $channel = NotificationChannel::factory()->create(['user_id' => $regularUser->id]); $response = actingAs($this->admin)->deleteJson("/settings/notifications/{$channel->id}"); $response->assertNotFound(); assertDatabaseHas('notification_channels', ['id' => $channel->id]); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/GlobalEnabledDisabledFilterTest.php
tests/Feature/GlobalEnabledDisabledFilterTest.php
<?php use App\Models\Monitor; use App\Models\User; test('statistics endpoint includes global enabled and disabled monitors count', function () { $user = User::factory()->create(); $this->actingAs($user); // Create globally enabled and disabled monitors $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => false, ]); $enabledMonitor->users()->detach($user->id); $enabledMonitor->users()->attach($user->id, ['is_active' => true]); $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => false, ]); $disabledMonitor->users()->detach($user->id); $disabledMonitor->users()->attach($user->id, ['is_active' => true]); $response = $this->get('/statistic-monitor'); $response->assertStatus(200); $data = $response->json(); $this->assertArrayHasKey('globally_enabled_monitors', $data); $this->assertArrayHasKey('globally_disabled_monitors', $data); $this->assertEquals(1, $data['globally_enabled_monitors']); $this->assertEquals(1, $data['globally_disabled_monitors']); }); test('private monitors endpoint supports globally enabled filter', function () { $user = User::factory()->create(); $this->actingAs($user); // Create enabled and disabled monitors $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => false, ]); $enabledMonitor->users()->detach($user->id); $enabledMonitor->users()->attach($user->id, ['is_active' => true]); $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => false, ]); $disabledMonitor->users()->detach($user->id); $disabledMonitor->users()->attach($user->id, ['is_active' => true]); // Test globally enabled filter $response = $this->get('/private-monitors?status_filter=globally_enabled'); $response->assertStatus(200); $data = $response->json(); $this->assertCount(1, $data['data']); $this->assertEquals($enabledMonitor->id, $data['data'][0]['id']); }); test('private monitors endpoint supports globally disabled filter', function () { $user = User::factory()->create(); $this->actingAs($user); // Create enabled and disabled monitors $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => false, ]); $enabledMonitor->users()->detach($user->id); $enabledMonitor->users()->attach($user->id, ['is_active' => true]); $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => false, ]); $disabledMonitor->users()->detach($user->id); $disabledMonitor->users()->attach($user->id, ['is_active' => true]); // Test globally disabled filter $response = $this->get('/private-monitors?status_filter=globally_disabled'); $response->assertStatus(200); $data = $response->json(); $this->assertCount(1, $data['data']); $this->assertEquals($disabledMonitor->id, $data['data'][0]['id']); }); test('public monitors endpoint supports globally enabled filter', function () { $user = User::factory()->create(); $this->actingAs($user); // Create enabled and disabled public monitors $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => true, ]); $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => true, ]); // Test globally enabled filter $response = $this->getJson('/public-monitors?status_filter=globally_enabled'); $response->assertStatus(200); $data = $response->json(); $this->assertCount(1, $data['data']); $this->assertEquals($enabledMonitor->id, $data['data'][0]['id']); }); test('public monitors endpoint supports globally disabled filter', function () { $user = User::factory()->create(); $this->actingAs($user); // Create enabled and disabled public monitors $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => true, ]); $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => true, ]); // Test globally disabled filter $response = $this->getJson('/public-monitors?status_filter=globally_disabled'); $response->assertStatus(200); $data = $response->json(); $this->assertCount(1, $data['data']); $this->assertEquals($disabledMonitor->id, $data['data'][0]['id']); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/StatisticMonitorControllerTest.php
tests/Feature/StatisticMonitorControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; use function Pest\Laravel\get; describe('StatisticMonitorController', function () { beforeEach(function () { // Create monitors with different statuses $this->upMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_status' => 'up', 'uptime_last_check_date' => now(), ]); $this->downMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_status' => 'down', 'uptime_last_check_date' => now(), ]); $this->recoveryMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_status' => 'up', // recovery counts as up 'uptime_last_check_date' => now(), ]); // Create history for up monitor MonitorHistory::factory()->create([ 'monitor_id' => $this->upMonitor->id, 'uptime_status' => 'up', 'response_time' => 200, 'created_at' => now(), ]); // Create history for down monitor MonitorHistory::factory()->create([ 'monitor_id' => $this->downMonitor->id, 'uptime_status' => 'down', 'response_time' => null, 'created_at' => now(), ]); // Create history for recovery monitor MonitorHistory::factory()->create([ 'monitor_id' => $this->recoveryMonitor->id, 'uptime_status' => 'recovery', 'response_time' => 300, 'created_at' => now(), ]); }); it('returns monitor statistics', function () { $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 3, 'online_monitors' => 2, // upMonitor and recoveryMonitor 'offline_monitors' => 1, // downMonitor ]); }); it('counts only public and enabled monitors', function () { // Create private monitor $privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); MonitorHistory::factory()->create([ 'monitor_id' => $privateMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); // Create disabled monitor $disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); MonitorHistory::factory()->create([ 'monitor_id' => $disabledMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 4, // Includes the disabled monitor in total count 'online_monitors' => 3, // All the public enabled ones are up 'offline_monitors' => 1, // downMonitor ]); }); it('counts up monitors correctly', function () { // Create additional up monitors $additionalUpMonitors = Monitor::factory()->count(3)->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); foreach ($additionalUpMonitors as $monitor) { MonitorHistory::factory()->create([ 'monitor_id' => $monitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); } $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 6, 'online_monitors' => 5, // 2 from beforeEach + 3 new ones that default to up 'offline_monitors' => 1, // Only downMonitor from beforeEach ]); }); it('counts down monitors correctly', function () { // Create additional down monitors $additionalDownMonitors = Monitor::factory()->count(2)->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); foreach ($additionalDownMonitors as $monitor) { MonitorHistory::factory()->create([ 'monitor_id' => $monitor->id, 'uptime_status' => 'down', 'created_at' => now(), ]); } $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 5, ]); expect($response->json())->toHaveKeys(['online_monitors', 'offline_monitors']); }); it('treats recovery status as up', function () { // Create monitor with recovery status $recoveryMonitor2 = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); MonitorHistory::factory()->create([ 'monitor_id' => $recoveryMonitor2->id, 'uptime_status' => 'recovery', 'created_at' => now(), ]); $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 4, ]); expect($response->json())->toHaveKeys(['online_monitors', 'offline_monitors']); }); it('handles monitors without history', function () { // Create monitor without history Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 4, ]); expect($response->json())->toHaveKeys(['online_monitors', 'offline_monitors']); }); it('uses latest history for each monitor', function () { // Create monitor with multiple history entries $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); // Old history - down MonitorHistory::factory()->create([ 'monitor_id' => $monitor->id, 'uptime_status' => 'down', 'created_at' => now()->subHours(2), ]); // Latest history - up MonitorHistory::factory()->create([ 'monitor_id' => $monitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 4, ]); expect($response->json())->toHaveKeys(['online_monitors', 'offline_monitors']); }); it('returns zero counts when no monitors exist', function () { // Delete all monitors Monitor::query()->delete(); $response = get('/statistic-monitor'); $response->assertOk(); $response->assertJson([ 'total_monitors' => 0, 'online_monitors' => 0, 'offline_monitors' => 0, ]); }); it('handles mixed monitor statuses', function () { // Create monitors with various statuses $statuses = ['up', 'down', 'recovery', 'maintenance']; foreach ($statuses as $status) { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); MonitorHistory::factory()->create([ 'monitor_id' => $monitor->id, 'uptime_status' => $status, 'created_at' => now(), ]); } $response = get('/statistic-monitor'); $response->assertOk(); $data = $response->json(); expect($data['total_monitors'])->toBe(7); // 3 from beforeEach + 4 new expect($data['online_monitors'] + $data['offline_monitors'])->toBeLessThanOrEqual($data['total_monitors']); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/PublicServerStatsTest.php
tests/Feature/PublicServerStatsTest.php
<?php use function Pest\Laravel\get; describe('Public Server Stats API', function () { it('returns server stats when enabled', function () { config(['app.show_public_server_stats' => true]); $response = get('/api/server-stats'); $response->assertOk() ->assertJsonStructure([ 'enabled', 'cpu_percent', 'memory_percent', 'uptime', 'uptime_seconds', 'response_time', 'timestamp', ]) ->assertJson(['enabled' => true]); }); it('returns disabled response when feature is disabled', function () { config(['app.show_public_server_stats' => false]); $response = get('/api/server-stats'); $response->assertOk() ->assertJson(['enabled' => false]) ->assertJsonMissing(['cpu_percent']); }); it('is rate limited', function () { config(['app.show_public_server_stats' => true]); // Make 30 requests (the limit) for ($i = 0; $i < 30; $i++) { get('/api/server-stats')->assertOk(); } // The 31st request should be rate limited get('/api/server-stats')->assertStatus(429); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/PublicMonitorDailyChecksTest.php
tests/Feature/PublicMonitorDailyChecksTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; it('displays daily checks count for public monitors', function () { // Create public monitors $publicMonitor1 = Monitor::factory()->create(['is_public' => true]); $publicMonitor2 = Monitor::factory()->create(['is_public' => true]); $privateMonitor = Monitor::factory()->create(['is_public' => false]); // Create monitor histories for today MonitorHistory::factory()->count(5)->create([ 'monitor_id' => $publicMonitor1->id, 'checked_at' => now(), ]); MonitorHistory::factory()->count(3)->create([ 'monitor_id' => $publicMonitor2->id, 'checked_at' => now(), ]); // This shouldn't be counted (private monitor) MonitorHistory::factory()->count(2)->create([ 'monitor_id' => $privateMonitor->id, 'checked_at' => now(), ]); // This shouldn't be counted (yesterday) MonitorHistory::factory()->count(4)->create([ 'monitor_id' => $publicMonitor1->id, 'checked_at' => now()->subDay(), ]); $response = $this->get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicIndex') ->has('stats.daily_checks') ->where('stats.daily_checks', 8) // 5 + 3 from public monitors today ); }); it('returns zero when no checks exist for today', function () { // Create public monitors without any histories Monitor::factory()->count(2)->create(['is_public' => true]); $response = $this->get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicIndex') ->has('stats.daily_checks') ->where('stats.daily_checks', 0) ); }); it('uses monitor_statistics table when available', function () { // Create public monitors $publicMonitor1 = Monitor::factory()->create(['is_public' => true]); $publicMonitor2 = Monitor::factory()->create(['is_public' => true]); // Create monitor statistics with total_checks_24h DB::table('monitor_statistics')->insert([ 'monitor_id' => $publicMonitor1->id, 'total_checks_24h' => 100, 'calculated_at' => now(), 'created_at' => now(), 'updated_at' => now(), ]); DB::table('monitor_statistics')->insert([ 'monitor_id' => $publicMonitor2->id, 'total_checks_24h' => 50, 'calculated_at' => now(), 'created_at' => now(), 'updated_at' => now(), ]); $response = $this->get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicIndex') ->has('stats.daily_checks') ->where('stats.daily_checks', 150) // 100 + 50 from statistics ); }); it('caches daily checks count for performance', function () { $publicMonitor = Monitor::factory()->create(['is_public' => true]); MonitorHistory::factory()->count(5)->create([ 'monitor_id' => $publicMonitor->id, 'checked_at' => now(), ]); // First request $response1 = $this->get('/public-monitors'); $response1->assertOk(); // Add more histories MonitorHistory::factory()->count(3)->create([ 'monitor_id' => $publicMonitor->id, 'checked_at' => now(), ]); // Second request should still show cached value $response2 = $this->get('/public-monitors'); $response2->assertInertia(fn ($page) => $page ->where('stats.daily_checks', 5) // Still 5 due to cache ); // Clear cache and check again cache()->forget('public_monitors_daily_checks'); $response3 = $this->get('/public-monitors'); $response3->assertInertia(fn ($page) => $page ->where('stats.daily_checks', 8) // Now shows updated count ); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/PublicMonitorShowControllerTest.php
tests/Feature/PublicMonitorShowControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; use function Pest\Laravel\get; describe('PublicMonitorShowController', function () { beforeEach(function () { $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://example.com', ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, 'url' => 'https://private.com', ]); $this->disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, 'url' => 'https://disabled.com', ]); }); it('displays public monitor by domain', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'created_at' => now(), ]); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShow') ->has('monitor') ->has('histories') ->has('uptimeStats') ->has('responseTimeStats') ->has('latestIncidents') ); }); it('returns monitor with correct data structure', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'created_at' => now(), ]); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('monitor') ->has('histories') ->has('uptimeStats') ->has('responseTimeStats') ); }); it('includes monitor histories', function () { // Create 5 histories with different timestamps within the last 100 minutes MonitorHistory::factory()->count(5)->sequence( fn ($sequence) => [ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'created_at' => now()->subMinutes($sequence->index * 10), ] )->create(); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('histories', 5) ); }); it('includes uptime statistics', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('uptimeStats.24h') ->has('uptimeStats.7d') ->has('uptimeStats.30d') ->has('uptimeStats.90d') ); }); it('includes response time statistics', function () { MonitorHistory::factory()->count(10)->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'created_at' => now(), ]); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('responseTimeStats.average') ->has('responseTimeStats.min') ->has('responseTimeStats.max') ); }); it('returns not found for private monitor', function () { $response = get('/m/private.com'); $response->assertOk(); // It renders PublicShowNotFound component $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShowNotFound') ); }); it('returns not found for disabled monitor', function () { $response = get('/m/disabled.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShowNotFound') ); }); it('returns not found for non-existent domain', function () { $response = get('/m/nonexistent.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShowNotFound') ); }); it('includes histories with proper limit', function () { MonitorHistory::factory()->count(100)->sequence( fn ($sequence) => [ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => $sequence->index % 10 === 0 ? 'down' : 'up', 'response_time' => $sequence->index % 10 === 0 ? null : rand(100, 500), 'created_at' => now()->subMinutes($sequence->index), ] )->create(); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('histories') // Histories from last 100 minutes ); }); it('includes latest incidents data', function () { // Create an incident (down period) MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'down', 'response_time' => null, 'message' => 'Connection timeout', 'created_at' => now()->subHours(2), ]); // Recovery MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'created_at' => now()->subHour(), ]); $response = get('/m/example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('latestIncidents') ); }); it('handles monitor with www subdomain', function () { $wwwMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://www.example.com', ]); MonitorHistory::factory()->create([ 'monitor_id' => $wwwMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/m/www.example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShow') ->has('monitor') ); }); it('handles monitor with subdomain', function () { $subdomainMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://api.example.com', ]); MonitorHistory::factory()->create([ 'monitor_id' => $subdomainMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/m/api.example.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShow') ->has('monitor') ); }); it('handles monitor with port in URL', function () { $portMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'url' => 'https://portexample.com:8080', ]); MonitorHistory::factory()->create([ 'monitor_id' => $portMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); // The route matches domain without port - but controller won't find it // since it's looking for 'https://portexample.com' not 'https://portexample.com:8080' $response = get('/m/portexample.com'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicShowNotFound') ); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/ExternalLinkTest.php
tests/Feature/ExternalLinkTest.php
<?php use function Pest\Laravel\get; it('returns successful response for public monitors page', function () { $response = get('/public-monitors'); $response->assertSuccessful(); }); it('returns JSON data for public monitors', function () { $response = get('/public-monitors'); $response->assertSuccessful(); // For Inertia apps, we should get a successful response // The actual rendering happens on the frontend $this->assertTrue($response->status() === 200); }); it('returns proper response structure', function () { $response = get('/public-monitors'); $response->assertSuccessful(); // Check that we get a proper response $this->assertTrue($response->status() === 200); }); it('includes monitor data with external links', function () { $response = get('/public-monitors'); $response->assertSuccessful(); // Check that the response contains monitor data $this->assertTrue($response->status() === 200); // For Inertia apps, the actual link rendering happens on the frontend // but we can verify the route works and returns data });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorImportTest.php
tests/Feature/MonitorImportTest.php
<?php use App\Models\Monitor; use App\Models\User; use App\Services\MonitorImportService; use Illuminate\Http\UploadedFile; beforeEach(function () { $this->user = User::factory()->create(['email_verified_at' => now()]); }); // ========================================== // Authentication Tests // ========================================== it('requires authentication to access import page', function () { $this->get(route('monitor.import.index')) ->assertRedirect(route('login')); }); it('requires authentication to preview import', function () { $this->postJson(route('monitor.import.preview')) ->assertUnauthorized(); }); it('requires authentication to process import', function () { $this->postJson(route('monitor.import.process')) ->assertUnauthorized(); }); it('can access import page when authenticated', function () { $this->actingAs($this->user) ->get(route('monitor.import.index')) ->assertSuccessful(); }); // ========================================== // File Validation Tests // ========================================== it('requires an import file', function () { $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), []) ->assertStatus(422) ->assertJsonValidationErrors(['import_file']); }); it('rejects invalid file types', function () { $file = UploadedFile::fake()->create('monitors.pdf', 100, 'application/pdf'); $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertStatus(422) ->assertJsonValidationErrors(['import_file']); }); it('accepts csv files', function () { $csvContent = "url,display_name\nhttps://example.com,Example Site\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful() ->assertJsonStructure([ 'rows', 'valid_count', 'error_count', 'duplicate_count', ]); }); it('accepts json files', function () { $jsonContent = json_encode([ 'monitors' => [ ['url' => 'https://example.com', 'display_name' => 'Example Site'], ], ]); $file = UploadedFile::fake()->createWithContent('monitors.json', $jsonContent); $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful() ->assertJsonStructure([ 'rows', 'valid_count', 'error_count', 'duplicate_count', ]); }); // ========================================== // CSV Parsing Tests // ========================================== it('parses csv file with headers correctly', function () { $csvContent = "url,display_name,uptime_check_enabled,is_public\nhttps://test1.com,Test Site 1,true,true\nhttps://test2.com,Test Site 2,false,false\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('valid_count'))->toBe(2); expect($response->json('rows.0.url'))->toBe('https://test1.com'); expect($response->json('rows.0.display_name'))->toBe('Test Site 1'); expect($response->json('rows.1.url'))->toBe('https://test2.com'); }); it('normalizes http urls to https', function () { $csvContent = "url\nhttp://example.com\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('rows.0.url'))->toBe('https://example.com'); }); it('parses comma-separated tags in csv', function () { $csvContent = "url,tags\nhttps://example.com,\"api,production,critical\"\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('rows.0.tags'))->toBe(['api', 'production', 'critical']); }); // ========================================== // JSON Parsing Tests // ========================================== it('parses json array format', function () { $jsonContent = json_encode([ ['url' => 'https://test1.com', 'display_name' => 'Test 1'], ['url' => 'https://test2.com', 'display_name' => 'Test 2'], ]); $file = UploadedFile::fake()->createWithContent('monitors.json', $jsonContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('valid_count'))->toBe(2); }); it('parses json monitors wrapper format', function () { $jsonContent = json_encode([ 'monitors' => [ ['url' => 'https://test1.com', 'display_name' => 'Test 1'], ], ]); $file = UploadedFile::fake()->createWithContent('monitors.json', $jsonContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('valid_count'))->toBe(1); expect($response->json('rows.0.url'))->toBe('https://test1.com'); }); it('handles invalid json gracefully', function () { $file = UploadedFile::fake()->createWithContent('monitors.json', 'invalid json content'); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('rows'))->toBeEmpty(); expect($response->json('valid_count'))->toBe(0); }); // ========================================== // Validation Tests // ========================================== it('marks rows with invalid url as error', function () { $csvContent = "url,display_name\nnot-a-valid-url,Invalid\nhttps://valid.com,Valid\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('error_count'))->toBe(1); expect($response->json('valid_count'))->toBe(1); expect($response->json('rows.0._status'))->toBe('error'); expect($response->json('rows.1._status'))->toBe('valid'); }); it('marks rows without url as error', function () { $csvContent = "display_name\nNo URL Row\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('error_count'))->toBe(1); expect($response->json('rows.0._status'))->toBe('error'); expect($response->json('rows.0._errors'))->toContain('The url field is required.'); }); it('validates sensitivity field values', function () { $csvContent = "url,sensitivity\nhttps://example.com,invalid_sensitivity\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('error_count'))->toBe(1); expect($response->json('rows.0._status'))->toBe('error'); }); // ========================================== // Duplicate Detection Tests // ========================================== it('detects duplicate urls', function () { Monitor::factory()->create(['url' => 'https://existing.com']); $csvContent = "url\nhttps://existing.com\nhttps://new-site.com\n"; $file = UploadedFile::fake()->createWithContent('monitors.csv', $csvContent); $response = $this->actingAs($this->user) ->postJson(route('monitor.import.preview'), [ 'import_file' => $file, ]) ->assertSuccessful(); expect($response->json('duplicate_count'))->toBe(1); expect($response->json('valid_count'))->toBe(1); expect($response->json('rows.0._status'))->toBe('duplicate'); expect($response->json('rows.1._status'))->toBe('valid'); }); // ========================================== // Import Process Tests // ========================================== it('imports valid monitors', function () { $rows = [ [ 'url' => 'https://newsite1.com', 'display_name' => 'New Site 1', '_row_number' => 1, '_status' => 'valid', ], [ 'url' => 'https://newsite2.com', 'display_name' => 'New Site 2', '_row_number' => 2, '_status' => 'valid', ], ]; $this->actingAs($this->user) ->postJson(route('monitor.import.process'), [ 'rows' => $rows, 'duplicate_action' => 'skip', ]) ->assertRedirect(route('monitor.index')); $this->assertDatabaseHas('monitors', ['url' => 'https://newsite1.com']); $this->assertDatabaseHas('monitors', ['url' => 'https://newsite2.com']); }); it('skips duplicates when action is skip', function () { $existingMonitor = Monitor::factory()->create(['url' => 'https://existing.com', 'display_name' => 'Original']); $rows = [ [ 'url' => 'https://existing.com', 'display_name' => 'Updated Name', '_row_number' => 1, '_status' => 'duplicate', ], ]; $this->actingAs($this->user) ->postJson(route('monitor.import.process'), [ 'rows' => $rows, 'duplicate_action' => 'skip', ]) ->assertRedirect(route('monitor.index')); $existingMonitor->refresh(); expect($existingMonitor->display_name)->toBe('Original'); }); it('updates duplicates when action is update', function () { $existingMonitor = Monitor::factory()->create([ 'url' => 'https://existing.com', 'display_name' => 'Original Name', 'is_public' => false, ]); $rows = [ [ 'url' => 'https://existing.com', 'display_name' => 'Updated Name', 'is_public' => true, '_row_number' => 1, '_status' => 'duplicate', ], ]; $this->actingAs($this->user) ->postJson(route('monitor.import.process'), [ 'rows' => $rows, 'duplicate_action' => 'update', ]) ->assertRedirect(route('monitor.index')); $existingMonitor->refresh(); expect($existingMonitor->display_name)->toBe('Updated Name'); expect((bool) $existingMonitor->is_public)->toBeTrue(); }); it('handles create action for duplicates by redirecting with error', function () { // First create a monitor outside the import $existingMonitor = Monitor::factory()->create(['url' => 'https://existing.com']); $rows = [ [ 'url' => 'https://existing.com', 'display_name' => 'New Copy', '_row_number' => 1, '_status' => 'duplicate', ], ]; // Creating a duplicate with 'create' action will fail due to unique URL constraint // The controller catches the exception and redirects back with an error $response = $this->actingAs($this->user) ->from(route('monitor.import.index')) ->postJson(route('monitor.import.process'), [ 'rows' => $rows, 'duplicate_action' => 'create', ]); // Should redirect (either back with error or success if somehow it worked) $response->assertRedirect(); }); it('skips error rows during import', function () { $rows = [ [ 'url' => 'https://valid.com', '_row_number' => 1, '_status' => 'valid', ], [ 'url' => 'invalid-url', '_row_number' => 2, '_status' => 'error', '_errors' => ['Invalid URL'], ], ]; $this->actingAs($this->user) ->postJson(route('monitor.import.process'), [ 'rows' => $rows, 'duplicate_action' => 'skip', ]) ->assertRedirect(route('monitor.index')); $this->assertDatabaseHas('monitors', ['url' => 'https://valid.com']); $this->assertDatabaseMissing('monitors', ['url' => 'invalid-url']); }); it('attaches tags during import', function () { $rows = [ [ 'url' => 'https://tagged-site.com', 'display_name' => 'Tagged Site', 'tags' => ['api', 'production'], '_row_number' => 1, '_status' => 'valid', ], ]; $this->actingAs($this->user) ->postJson(route('monitor.import.process'), [ 'rows' => $rows, 'duplicate_action' => 'skip', ]) ->assertRedirect(route('monitor.index')); $monitor = Monitor::where('url', 'https://tagged-site.com')->first(); expect($monitor)->not->toBeNull(); expect($monitor->tags->pluck('name')->toArray())->toContain('api', 'production'); }); // ========================================== // Sample Template Download Tests // ========================================== it('can download csv template', function () { $response = $this->actingAs($this->user) ->get(route('monitor.import.sample.csv')) ->assertSuccessful(); expect($response->headers->get('content-type'))->toContain('text/csv'); }); it('can download json template', function () { $response = $this->actingAs($this->user) ->get(route('monitor.import.sample.json')) ->assertSuccessful(); expect($response->headers->get('content-type'))->toContain('application/json'); }); // ========================================== // Service Unit Tests // ========================================== it('service generates valid csv sample', function () { $service = new MonitorImportService; $csv = $service->generateSampleCsv(); expect($csv)->toContain('url,display_name'); expect($csv)->toContain('https://example.com'); }); it('service generates valid json sample', function () { $service = new MonitorImportService; $json = $service->generateSampleJson(); $data = json_decode($json, true); expect($data)->toHaveKey('monitors'); expect($data['monitors'])->toBeArray(); expect($data['monitors'][0])->toHaveKey('url'); }); it('service detects csv format from extension', function () { $service = new MonitorImportService; $file = UploadedFile::fake()->create('monitors.csv', 100, 'text/csv'); expect($service->detectFormat($file))->toBe('csv'); }); it('service detects json format from extension', function () { $service = new MonitorImportService; $file = UploadedFile::fake()->create('monitors.json', 100, 'application/json'); expect($service->detectFormat($file))->toBe('json'); }); it('service defaults to csv for unknown extensions', function () { $service = new MonitorImportService; $file = UploadedFile::fake()->create('monitors.txt', 100, 'text/plain'); expect($service->detectFormat($file))->toBe('csv'); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/UnsubscribeMonitorTest.php
tests/Feature/UnsubscribeMonitorTest.php
<?php use App\Models\Monitor; use App\Models\User; use Illuminate\Support\Facades\Cache; // No global beforeEach - create users per test to avoid constraint violations function testSuccessfulUnsubscription() { describe('successful unsubscription', function () { it('successfully unsubscribes user from public monitor', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://example.com', ]); // Subscribe user to monitor first $monitor->users()->attach($user->id); // Set cache to verify it gets cleared Cache::put('public_monitors_authenticated_'.$user->id, 'cached_data'); $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); $response->assertSessionHas('flash.message', 'Berhasil berhenti berlangganan monitor: '.$monitor->url); // Verify user is unsubscribed $this->assertDatabaseMissing('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor->id, ]); // Verify cache is cleared $this->assertNull(Cache::get('public_monitors_authenticated_'.$user->id)); }); it('successfully unsubscribes user and displays correct URL in message', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://example-custom.com', ]); // Subscribe user to monitor first $monitor->users()->attach($user->id); $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.message', 'Berhasil berhenti berlangganan monitor: https://example-custom.com'); }); }); } function testValidationAndErrorHandling() { describe('validation and error handling', function () { it('prevents unsubscribing from private monitor', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => false, 'url' => 'https://private-example.com', ]); $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message', 'Monitor tidak tersedia untuk berlangganan'); // Verify no subscription exists $this->assertDatabaseMissing('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor->id, ]); }); it('prevents unsubscribing when user is not subscribed', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://not-subscribed-example.com', ]); // User is not subscribed to this monitor $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message', 'Anda tidak berlangganan monitor ini'); // Verify still no subscription $this->assertDatabaseMissing('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor->id, ]); }); it('handles monitor not found gracefully', function () { $user = User::factory()->create(); $nonExistentMonitorId = 99999; $response = $this->actingAs($user)->delete("/monitor/{$nonExistentMonitorId}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'error'); $response->assertSessionHas('flash.message'); // Verify error message contains helpful information $flashMessage = session('flash.message'); $this->assertStringContainsString('Gagal berhenti berlangganan monitor:', $flashMessage); }); }); } function testAuthenticationAndAuthorization() { describe('authentication and authorization', function () { it('requires authentication', function () { $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://auth-example.com', ]); $response = $this->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect('/login'); }); it('only affects current user subscription', function () { $currentUser = User::factory()->create(); $otherUser = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://multi-user-example.com', ]); // Both users subscribe to the monitor $monitor->users()->attach([$currentUser->id, $otherUser->id]); $response = $this->actingAs($currentUser)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); // Verify only current user is unsubscribed $this->assertDatabaseMissing('user_monitor', [ 'user_id' => $currentUser->id, 'monitor_id' => $monitor->id, ]); // Verify other user still subscribed $this->assertDatabaseHas('user_monitor', [ 'user_id' => $otherUser->id, 'monitor_id' => $monitor->id, ]); }); }); } function testCacheManagement() { describe('cache management', function () { it('clears user-specific monitor cache after unsubscription', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://cache-example.com', ]); // Subscribe user to monitor $monitor->users()->attach($user->id); // Set cache for current user $cacheKey = 'public_monitors_authenticated_'.$user->id; Cache::put($cacheKey, 'some_cached_data'); // Verify cache exists before unsubscription $this->assertNotNull(Cache::get($cacheKey)); $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); // Verify cache is cleared after unsubscription $this->assertNull(Cache::get($cacheKey)); }); it('does not affect other users cache when unsubscribing', function () { $currentUser = User::factory()->create(); $otherUser = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://multi-cache-example.com', ]); // Subscribe both users $monitor->users()->attach([$currentUser->id, $otherUser->id]); // Set cache for both users $currentUserCacheKey = 'public_monitors_authenticated_'.$currentUser->id; $otherUserCacheKey = 'public_monitors_authenticated_'.$otherUser->id; Cache::put($currentUserCacheKey, 'current_user_data'); Cache::put($otherUserCacheKey, 'other_user_data'); $response = $this->actingAs($currentUser)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); // Verify only current user's cache is cleared $this->assertNull(Cache::get($currentUserCacheKey)); $this->assertNotNull(Cache::get($otherUserCacheKey)); $this->assertEquals('other_user_data', Cache::get($otherUserCacheKey)); }); }); } function testEdgeCasesAndDataIntegrity() { describe('edge cases and data integrity', function () { it('handles multiple subscriptions correctly', function () { $user = User::factory()->create(); $monitor1 = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://monitor1-example.com', ]); $monitor2 = Monitor::factory()->create([ 'is_public' => true, 'url' => 'https://monitor2-example.com', ]); // Subscribe to both monitors $monitor1->users()->attach($user->id); $monitor2->users()->attach($user->id); // Unsubscribe from first monitor $response = $this->actingAs($user)->delete("/monitor/{$monitor1->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); // Verify unsubscribed from monitor1 but not monitor2 $this->assertDatabaseMissing('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor1->id, ]); $this->assertDatabaseHas('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor2->id, ]); }); it('works with monitors that have withoutGlobalScopes applied', function () { $user = User::factory()->create(); // Create monitor that might normally be filtered by global scopes $monitor = Monitor::withoutGlobalScopes()->create([ 'is_public' => true, 'url' => 'https://test-scope.com', 'uptime_status' => 'up', 'uptime_check_enabled' => true, 'certificate_check_enabled' => false, 'uptime_check_interval_in_minutes' => 5, 'uptime_last_check_date' => now(), 'uptime_status_last_change_date' => now(), 'certificate_status' => 'not applicable', ]); // Subscribe user to monitor $monitor->users()->attach($user->id); $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); $response->assertSessionHas('flash.message', 'Berhasil berhenti berlangganan monitor: https://test-scope.com'); // Verify unsubscription worked $this->assertDatabaseMissing('user_monitor', [ 'user_id' => $user->id, 'monitor_id' => $monitor->id, ]); }); it('handles URL property correctly with empty string URL', function () { $user = User::factory()->create(); $monitor = Monitor::factory()->create([ 'is_public' => true, 'url' => '', // Test empty URL instead of null ]); // Subscribe user to monitor $monitor->users()->attach($user->id); $response = $this->actingAs($user)->delete("/monitor/{$monitor->id}/unsubscribe"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); // Verify success message handles empty URL gracefully $flashMessage = session('flash.message'); $this->assertStringContainsString('Berhasil berhenti berlangganan monitor:', $flashMessage); }); }); } describe('UnsubscribeMonitorController', function () { testSuccessfulUnsubscription(); testValidationAndErrorHandling(); testAuthenticationAndAuthorization(); testCacheManagement(); testEdgeCasesAndDataIntegrity(); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/PublicMonitorControllerTest.php
tests/Feature/PublicMonitorControllerTest.php
<?php use App\Models\Monitor; use App\Models\MonitorHistory; use App\Models\MonitorUptimeDaily; use function Pest\Laravel\get; describe('PublicMonitorController', function () { beforeEach(function () { $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $this->disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); }); it('displays public monitors page', function () { $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->component('monitors/PublicIndex') ->has('monitors') ->has('stats') ->has('filters') ->has('availableTags') ); }); it('includes only public and enabled monitors', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->where('monitors.data.0.id', $this->publicMonitor->id) ->count('monitors.data', 1) ); }); it('excludes private monitors', function () { $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->whereNot('monitors.data.0.id', $this->privateMonitor->id) ); }); it('excludes disabled monitors', function () { $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->whereNot('monitors.data.0.id', $this->disabledMonitor->id) ); }); it('includes monitor statistics', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'response_time' => 250, 'created_at' => now(), ]); MonitorUptimeDaily::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_percentage' => 99.5, 'date' => now()->toDateString(), ]); $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('monitors.data.0.last_check_date') ->has('monitors.data.0.today_uptime_percentage') ); }); it('includes basic monitor information', function () { MonitorHistory::factory()->create([ 'monitor_id' => $this->publicMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('monitors.data.0.id') ->has('monitors.data.0.name') ->has('monitors.data.0.url') ); }); it('paginates public monitors', function () { Monitor::factory()->count(20)->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('monitors.data', 15) // Default pagination ->has('monitors.links') ->has('monitors.meta') ); }); it('respects per_page parameter', function () { Monitor::factory()->count(10)->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $response = get('/public-monitors?per_page=5'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->has('monitors.data', 5) ); }); it('calculates monitor counts correctly', function () { Monitor::factory()->count(3)->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $upMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_status' => 'up', ]); $downMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'uptime_status' => 'down', ]); MonitorHistory::factory()->create([ 'monitor_id' => $upMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); MonitorHistory::factory()->create([ 'monitor_id' => $downMonitor->id, 'uptime_status' => 'down', 'created_at' => now(), ]); $response = get('/public-monitors'); $response->assertOk(); $response->assertInertia(fn ($page) => $page ->where('stats.total', 6) ->where('stats.up', 5) // All monitors default to up except the one explicitly set to down ->where('stats.down', 1) // Only the one explicitly set to down ); }); it('orders monitors by created date descending', function () { $oldMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'created_at' => now()->subDays(2), ]); $newMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, 'created_at' => now(), ]); MonitorHistory::factory()->create([ 'monitor_id' => $oldMonitor->id, 'uptime_status' => 'up', 'created_at' => now()->subDays(2), ]); MonitorHistory::factory()->create([ 'monitor_id' => $newMonitor->id, 'uptime_status' => 'up', 'created_at' => now(), ]); $response = get('/public-monitors'); $response->assertOk(); // Just verify that both monitors are present in the response $response->assertInertia(fn ($page) => $page ->has('monitors.data') ); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MaintenanceWindowServiceTest.php
tests/Feature/MaintenanceWindowServiceTest.php
<?php use App\Models\Monitor; use App\Services\MaintenanceWindowService; use Carbon\Carbon; beforeEach(function () { $this->service = new MaintenanceWindowService; }); it('detects monitor in one-time maintenance window', function () { Carbon::setTestNow('2025-12-15 03:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'one_time', 'start' => '2025-12-15T02:00:00+00:00', 'end' => '2025-12-15T04:00:00+00:00', ], ], ]); expect($this->service->isInMaintenance($monitor))->toBeTrue(); }); it('detects monitor not in one-time maintenance window', function () { Carbon::setTestNow('2025-12-15 05:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'one_time', 'start' => '2025-12-15T02:00:00+00:00', 'end' => '2025-12-15T04:00:00+00:00', ], ], ]); expect($this->service->isInMaintenance($monitor))->toBeFalse(); }); it('detects monitor in recurring maintenance window', function () { // Set to Sunday 03:00 UTC Carbon::setTestNow('2025-12-14 03:00:00'); // Sunday $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'recurring', 'day_of_week' => 0, // Sunday 'start_time' => '02:00', 'end_time' => '04:00', 'timezone' => 'UTC', ], ], ]); expect($this->service->isInMaintenance($monitor))->toBeTrue(); }); it('detects monitor not in recurring maintenance window on different day', function () { // Set to Monday 03:00 UTC Carbon::setTestNow('2025-12-15 03:00:00'); // Monday $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'recurring', 'day_of_week' => 0, // Sunday 'start_time' => '02:00', 'end_time' => '04:00', 'timezone' => 'UTC', ], ], ]); expect($this->service->isInMaintenance($monitor))->toBeFalse(); }); it('respects timezone in recurring maintenance window', function () { // Set to Sunday 09:00 UTC which is 16:00 in Asia/Jakarta (+7) Carbon::setTestNow('2025-12-14 09:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'recurring', 'day_of_week' => 0, // Sunday 'start_time' => '15:00', 'end_time' => '17:00', 'timezone' => 'Asia/Jakarta', ], ], ]); expect($this->service->isInMaintenance($monitor))->toBeTrue(); }); it('returns false when no maintenance windows configured', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => null, ]); expect($this->service->isInMaintenance($monitor))->toBeFalse(); }); it('returns false when maintenance windows is empty array', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [], ]); expect($this->service->isInMaintenance($monitor))->toBeFalse(); }); it('uses cached is_in_maintenance flag when valid', function () { Carbon::setTestNow('2025-12-15 03:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'is_in_maintenance' => true, 'maintenance_ends_at' => '2025-12-15 04:00:00', 'maintenance_windows' => [], // Empty but flag is set ]); expect($this->service->isInMaintenance($monitor))->toBeTrue(); }); it('updates maintenance status correctly', function () { Carbon::setTestNow('2025-12-15 03:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'is_in_maintenance' => false, 'maintenance_windows' => [ [ 'type' => 'one_time', 'start' => '2025-12-15T02:00:00+00:00', 'end' => '2025-12-15T04:00:00+00:00', ], ], ]); $updated = $this->service->updateMaintenanceStatus($monitor); expect($updated)->toBeTrue(); $monitor->refresh(); expect($monitor->is_in_maintenance)->toBeTrue(); expect($monitor->maintenance_starts_at)->not->toBeNull(); expect($monitor->maintenance_ends_at)->not->toBeNull(); }); it('exits maintenance when window ends', function () { Carbon::setTestNow('2025-12-15 05:00:00'); // After window $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'is_in_maintenance' => true, 'maintenance_starts_at' => '2025-12-15 02:00:00', 'maintenance_ends_at' => '2025-12-15 04:00:00', 'maintenance_windows' => [ [ 'type' => 'one_time', 'start' => '2025-12-15T02:00:00+00:00', 'end' => '2025-12-15T04:00:00+00:00', ], ], ]); $updated = $this->service->updateMaintenanceStatus($monitor); expect($updated)->toBeTrue(); $monitor->refresh(); expect($monitor->is_in_maintenance)->toBeFalse(); expect($monitor->maintenance_starts_at)->toBeNull(); expect($monitor->maintenance_ends_at)->toBeNull(); }); it('gets next maintenance window for one-time', function () { Carbon::setTestNow('2025-12-14 01:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'one_time', 'start' => '2025-12-15T02:00:00+00:00', 'end' => '2025-12-15T04:00:00+00:00', ], ], ]); $nextWindow = $this->service->getNextMaintenanceWindow($monitor); expect($nextWindow)->not->toBeNull(); expect($nextWindow['type'])->toBe('one_time'); expect($nextWindow)->toHaveKey('next_start'); expect($nextWindow)->toHaveKey('next_end'); }); it('cleans up expired one-time maintenance windows', function () { Carbon::setTestNow('2025-12-20 00:00:00'); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'maintenance_windows' => [ [ 'type' => 'one_time', 'start' => '2025-12-15T02:00:00+00:00', 'end' => '2025-12-15T04:00:00+00:00', // Expired ], [ 'type' => 'recurring', 'day_of_week' => 0, 'start_time' => '02:00', 'end_time' => '04:00', 'timezone' => 'UTC', ], [ 'type' => 'one_time', 'start' => '2025-12-25T02:00:00+00:00', 'end' => '2025-12-25T04:00:00+00:00', // Future ], ], ]); $cleaned = $this->service->cleanupExpiredWindows(); expect($cleaned)->toBe(1); $monitor->refresh(); expect(count($monitor->maintenance_windows))->toBe(2); // Expired one removed // Verify the remaining windows $types = collect($monitor->maintenance_windows)->pluck('type')->toArray(); expect($types)->toContain('recurring'); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/TagControllerTest.php
tests/Feature/TagControllerTest.php
<?php use App\Models\Monitor; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\get; describe('TagController', function () { beforeEach(function () { $this->user = User::factory()->create(); // Create monitors with various tags $monitor1 = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor1->attachTags(['production', 'api', 'critical']); $monitor2 = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor2->attachTags(['staging', 'api', 'backend']); $monitor3 = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $monitor3->attachTags(['development', 'frontend']); $monitor3->users()->attach($this->user->id, ['is_active' => true]); $monitor4 = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor4->attachTags(['production', 'database']); $monitor5 = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, // Disabled monitor ]); $monitor5->attachTags(['archived', 'old']); Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, // No tags ]); }); describe('index', function () { it('returns all unique tags from visible monitors', function () { $response = actingAs($this->user)->get('/tags'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect($tags)->toBeArray(); expect($tags)->toContain('production'); expect($tags)->toContain('api'); expect($tags)->toContain('staging'); expect($tags)->toContain('development'); expect($tags)->toContain('archived'); // Tags controller returns all tags, not filtered by enabled }); it('requires authentication for unauthenticated users', function () { $response = get('/tags'); $response->assertRedirect('/login'); }); it('includes tags from owned private monitors', function () { $privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $privateMonitor->attachTags(['private-tag', 'internal']); $privateMonitor->users()->attach($this->user->id, ['is_active' => true]); $response = actingAs($this->user)->get('/tags'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect($tags)->toContain('private-tag'); expect($tags)->toContain('internal'); }); it('excludes tags from disabled monitors', function () { $response = actingAs($this->user)->get('/tags'); $response->assertOk(); $tags = $response->json(); expect($tags)->not->toContain('archived'); expect($tags)->not->toContain('old'); }); it('returns unique tags without duplicates', function () { $response = actingAs($this->user)->get('/tags'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); // Count occurrences of 'production' tag $productionCount = count(array_filter($tags, fn ($tag) => $tag === 'production')); expect($productionCount)->toBe(1); // Count occurrences of 'api' tag $apiCount = count(array_filter($tags, fn ($tag) => $tag === 'api')); expect($apiCount)->toBe(1); }); it('returns tags', function () { $response = actingAs($this->user)->get('/tags'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); // Just check that we have tags expect($tags)->toBeArray(); expect(count($tags))->toBeGreaterThan(0); }); it('handles monitors without tags', function () { // Delete all monitors with tags Monitor::whereNotNull('tags')->delete(); $response = actingAs($this->user)->get('/tags'); $response->assertOk(); $response->assertJson(['tags' => []]); }); }); describe('search', function () { it('searches for tags by query', function () { $response = actingAs($this->user)->get('/tags/search?search=prod'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect($tags)->toContain('production'); expect($tags)->not->toContain('staging'); expect($tags)->not->toContain('api'); }); it('returns empty array when no matches found', function () { $response = actingAs($this->user)->get('/tags/search?search=nonexistent'); $response->assertOk(); $response->assertJson(['tags' => []]); }); it('searches case-insensitively', function () { $response = actingAs($this->user)->get('/tags/search?search=PROD'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect($tags)->toContain('production'); }); it('requires query parameter', function () { $response = actingAs($this->user)->get('/tags/search'); $response->assertOk(); $response->assertJson(['tags' => []]); }); it('handles empty query parameter', function () { $response = actingAs($this->user)->get('/tags/search?search='); $response->assertOk(); $response->assertJson(['tags' => []]); }); it('limits search results', function () { // Create many monitors with tags matching the search for ($i = 0; $i < 30; $i++) { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor->attachTags(["test-tag-$i", 'test-common']); } $response = actingAs($this->user)->get('/tags/search?search=test'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect(count($tags))->toBeLessThanOrEqual(10); // Controller limit is 10 }); it('searches only in visible monitors', function () { $privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $privateMonitor->attachTags(['secret-tag']); $otherUser = User::factory()->create(); $response = actingAs($otherUser)->get('/tags/search?search=secret'); $response->assertOk(); $response->assertJson(['tags' => []]); }); it('includes partial matches', function () { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor->attachTags(['production-server', 'production-database']); $response = actingAs($this->user)->get('/tags/search?search=duct'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect($tags)->toContain('production'); }); it('returns unique results', function () { // Create multiple monitors with same tag for ($i = 0; $i < 5; $i++) { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor->attachTags(['duplicate-tag']); } $response = actingAs($this->user)->get('/tags/search?search=duplicate'); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); $duplicateCount = count(array_filter($tags, fn ($tag) => $tag === 'duplicate-tag')); expect($duplicateCount)->toBe(1); }); it('handles special characters in search query', function () { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor->attachTags(['test@special', 'test#hash', 'test$money']); $response = actingAs($this->user)->get('/tags/search?search='.urlencode('test@')); $response->assertOk(); $data = $response->json(); $tags = collect($data['tags'])->pluck('name')->toArray(); expect($tags)->toContain('test@special'); }); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/MonitorTagTest.php
tests/Feature/MonitorTagTest.php
<?php use App\Models\Monitor; use App\Models\User; test('monitor can have tags attached', function () { $user = User::factory()->create(); $this->actingAs($user); $monitor = Monitor::factory()->create([ 'url' => 'https://example.com', 'uptime_check_enabled' => true, ]); $monitor->attachTags(['production', 'api', 'critical']); expect($monitor->tags->count())->toBe(3); expect($monitor->tags->pluck('name')->toArray())->toContain('production', 'api', 'critical'); }); test('monitor can be filtered by tags', function () { $user = User::factory()->create(); $this->actingAs($user); $monitor1 = Monitor::factory()->create(['url' => 'https://example1.com']); $monitor2 = Monitor::factory()->create(['url' => 'https://example2.com']); $monitor3 = Monitor::factory()->create(['url' => 'https://example3.com']); $monitor1->attachTags(['production']); $monitor2->attachTags(['staging']); $monitor3->attachTags(['production', 'api']); $productionMonitors = Monitor::withoutGlobalScopes()->withAnyTags(['production'])->get(); $stagingMonitors = Monitor::withoutGlobalScopes()->withAnyTags(['staging'])->get(); expect($productionMonitors->count())->toBe(2); expect($stagingMonitors->count())->toBe(1); expect($productionMonitors->pluck('id'))->toContain($monitor1->id, $monitor3->id); expect($stagingMonitors->pluck('id'))->toContain($monitor2->id); }); test('tag endpoint returns tags for monitors', function () { $user = User::factory()->create(); $this->actingAs($user); $monitor = Monitor::factory()->create(); $monitor->attachTags(['production', 'api']); $response = $this->get('/tags'); $response->assertOk(); $response->assertJsonStructure([ 'tags' => [ '*' => ['id', 'name', 'type'], ], ]); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/ToggleMonitorActiveControllerTest.php
tests/Feature/ToggleMonitorActiveControllerTest.php
<?php use App\Models\Monitor; use App\Models\User; use function Pest\Laravel\actingAs; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\post; describe('ToggleMonitorActiveController', function () { beforeEach(function () { $this->user = User::factory()->create(); $this->admin = User::factory()->create(['is_admin' => true]); $this->otherUser = User::factory()->create(); $this->publicMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $this->privateMonitor = Monitor::factory()->create([ 'is_public' => false, 'uptime_check_enabled' => true, ]); $this->disabledMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => false, ]); // User owns the private monitor $this->privateMonitor->users()->attach($this->user->id, ['is_active' => true]); }); it('allows admin to disable an active monitor', function () { // Admin needs to be attached to the monitor to toggle it $this->publicMonitor->users()->attach($this->admin->id, ['is_active' => true]); $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$this->publicMonitor->id}/toggle-active"); $response->assertRedirect('/dashboard'); $response->assertSessionHas('flash.type', 'success'); assertDatabaseHas('monitors', [ 'id' => $this->publicMonitor->id, 'uptime_check_enabled' => false, ]); }); it('allows admin to enable a disabled monitor', function () { // Admin needs to be attached to the monitor $this->disabledMonitor->users()->attach($this->admin->id, ['is_active' => true]); $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$this->disabledMonitor->id}/toggle-active"); $response->assertRedirect('/dashboard'); $response->assertSessionHas('flash.type', 'success'); assertDatabaseHas('monitors', [ 'id' => $this->disabledMonitor->id, 'uptime_check_enabled' => true, ]); }); it('allows owner to toggle their private monitor', function () { $response = actingAs($this->user) ->from('/dashboard') ->post("/monitor/{$this->privateMonitor->id}/toggle-active"); $response->assertRedirect('/dashboard'); $response->assertSessionHas('flash.type', 'success'); assertDatabaseHas('monitors', [ 'id' => $this->privateMonitor->id, 'uptime_check_enabled' => false, ]); // Toggle back $response = actingAs($this->user) ->from('/dashboard') ->post("/monitor/{$this->privateMonitor->id}/toggle-active"); $response->assertRedirect('/dashboard'); assertDatabaseHas('monitors', [ 'id' => $this->privateMonitor->id, 'uptime_check_enabled' => true, ]); }); it('prevents non-owner from toggling private monitor', function () { $response = actingAs($this->otherUser) ->from('/dashboard') ->post("/monitor/{$this->privateMonitor->id}/toggle-active"); // User not subscribed will get redirect with error $response->assertRedirect('/dashboard'); $response->assertSessionHas('flash.type', 'error'); assertDatabaseHas('monitors', [ 'id' => $this->privateMonitor->id, 'uptime_check_enabled' => true, // Should remain unchanged ]); }); it('prevents regular user from toggling public monitor not subscribed to', function () { $response = actingAs($this->user) ->from('/dashboard') ->post("/monitor/{$this->publicMonitor->id}/toggle-active"); // User not subscribed will get redirect with error $response->assertRedirect('/dashboard'); $response->assertSessionHas('flash.type', 'error'); assertDatabaseHas('monitors', [ 'id' => $this->publicMonitor->id, 'uptime_check_enabled' => true, ]); }); it('requires authentication', function () { $response = post("/monitor/{$this->publicMonitor->id}/toggle-active"); $response->assertRedirect('/login'); }); it('handles non-existent monitor', function () { $response = actingAs($this->admin) ->from('/dashboard') ->post('/monitor/999999/toggle-active'); $response->assertRedirect('/dashboard'); $response->assertSessionHas('flash.type', 'error'); }); it('toggles state correctly multiple times', function () { $monitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor->users()->attach($this->admin->id, ['is_active' => true]); // First toggle - disable $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$monitor->id}/toggle-active"); $response->assertRedirect(); assertDatabaseHas('monitors', ['id' => $monitor->id, 'uptime_check_enabled' => false]); // Second toggle - enable $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$monitor->id}/toggle-active"); $response->assertRedirect(); assertDatabaseHas('monitors', ['id' => $monitor->id, 'uptime_check_enabled' => true]); // Third toggle - disable again $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$monitor->id}/toggle-active"); $response->assertRedirect(); assertDatabaseHas('monitors', ['id' => $monitor->id, 'uptime_check_enabled' => false]); }); it('maintains other monitor properties when toggling', function () { $monitor = Monitor::factory()->create([ 'url' => 'https://example-toggle.com', 'is_public' => true, 'uptime_check_enabled' => true, ]); $monitor->users()->attach($this->admin->id, ['is_active' => true]); $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$monitor->id}/toggle-active"); $response->assertRedirect(); assertDatabaseHas('monitors', [ 'id' => $monitor->id, 'url' => 'https://example-toggle.com', 'is_public' => true, 'uptime_check_enabled' => false, ]); }); it('returns success message in session', function () { $this->publicMonitor->users()->attach($this->admin->id, ['is_active' => true]); $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$this->publicMonitor->id}/toggle-active"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); assertDatabaseHas('monitors', [ 'id' => $this->publicMonitor->id, 'uptime_check_enabled' => false, ]); }); it('works with pinned monitors', function () { $pinnedMonitor = Monitor::factory()->create([ 'is_public' => true, 'uptime_check_enabled' => true, ]); // Set as pinned through pivot table $pinnedMonitor->users()->attach($this->admin->id, ['is_active' => true, 'is_pinned' => true]); $response = actingAs($this->admin) ->from('/dashboard') ->post("/monitor/{$pinnedMonitor->id}/toggle-active"); $response->assertRedirect(); $response->assertSessionHas('flash.type', 'success'); assertDatabaseHas('monitors', [ 'id' => $pinnedMonitor->id, 'uptime_check_enabled' => false, ]); // Check pin status remains in pivot table assertDatabaseHas('user_monitor', [ 'monitor_id' => $pinnedMonitor->id, 'user_id' => $this->admin->id, 'is_pinned' => true, ]); }); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/DisabledMonitorFilterTest.php
tests/Feature/DisabledMonitorFilterTest.php
<?php use App\Models\Monitor; use App\Models\User; test('statistics endpoint includes disabled monitors count', function () { $user = User::factory()->create(); $this->actingAs($user); // Create a monitor and disable it for the user (user-specific disabled) $monitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, // Monitor is globally enabled 'is_public' => false, ]); // Detach any auto-attached user_monitor row $monitor->users()->detach($user->id); // Attach user to monitor with is_active = false (user-specific disabled) $monitor->users()->attach($user->id, ['is_active' => false]); $response = $this->get('/statistic-monitor'); $response->assertStatus(200); $data = $response->json(); $this->assertArrayHasKey('globally_disabled_monitors', $data); $this->assertEquals(1, $data['globally_disabled_monitors']); }); test('private monitors endpoint supports user-specific disabled filter', function () { $user = User::factory()->create(); $this->actingAs($user); // Create a globally enabled monitor but user-specific disabled $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => false, ]); $enabledMonitor->users()->detach($user->id); $enabledMonitor->users()->attach($user->id, ['is_active' => false]); // User-specific disabled // Create a globally disabled monitor $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => false, ]); $disabledMonitor->users()->detach($user->id); $disabledMonitor->users()->attach($user->id, ['is_active' => true]); // Test user-specific disabled filter (this should show monitors where user has is_active = false) // Note: This filter is for user-specific disabled, not globally disabled $response = $this->get('/private-monitors?status_filter=disabled'); $response->assertStatus(200); $data = $response->json(); // The disabled filter should show monitors where the user has is_active = false $this->assertCount(1, $data['data']); $this->assertEquals($enabledMonitor->id, $data['data'][0]['id']); }); test('public monitors endpoint supports globally disabled filter', function () { $user = User::factory()->create(); $this->actingAs($user); // Create enabled and disabled public monitors $enabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => true, 'is_public' => true, ]); $disabledMonitor = Monitor::factory()->create([ 'uptime_check_enabled' => false, 'is_public' => true, ]); // Test globally disabled filter $response = $this->getJson('/public-monitors?status_filter=disabled'); $response->assertStatus(200); $data = $response->json(); $this->assertCount(1, $data['data']); $this->assertEquals($disabledMonitor->id, $data['data'][0]['id']); }); test('disabled filter only shows for authenticated users', function () { // Test as guest user $response = $this->get('/statistic-monitor'); $response->assertStatus(200); $data = $response->json(); $this->assertArrayHasKey('globally_disabled_monitors', $data); $this->assertEquals(0, $data['globally_disabled_monitors']); // Should be 0 for guests });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/tests/Feature/ExampleTest.php
tests/Feature/ExampleTest.php
<?php test('returns a successful response', function () { $response = $this->get('/'); $response->assertStatus(200); });
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false