### API Request Examples Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Examples of making API requests using curl or HTTP clients. ```shell curl -X GET \ http://localhost:8000/api/v1/servers/nearest?token=YOUR_API_TOKEN \ -H 'Accept: application/json' ``` -------------------------------- ### Configuration Setup Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Illustrates how to configure application settings. ```php config([\n 'speedtest-tracker.notifications.enabled' => true,\n 'speedtest-tracker.notifications.channels' => ['mail', 'slack'],\n]); ``` -------------------------------- ### Event Listening Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Examples of registering and handling application events. ```php use App\Listeners\SpeedtestCompletedListener;\nuse Illuminate\Support\Facades\Event;\n\n// Register an event listener\nEvent::listen(App\Events\SpeedtestCompleted::class, SpeedtestCompletedListener::class); ``` -------------------------------- ### Database Query Examples Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Illustrates direct database queries. ```php use Illuminate\Support\Facades\DB;\n\n// Select specific columns from the results table\n$results = DB::table('results')->select('id', 'download', 'upload')->get(); ``` -------------------------------- ### Backup Strategy Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Demonstrates a basic database backup strategy. ```shell # Example backup command (requires mysqldump) mysqldump -u your_db_user -p your_db_name > backup_$(date +%Y%m%d_%H%M%S).sql ``` -------------------------------- ### Checking Speedtest CLI Installation Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Verify that the speedtest-cli executable is installed and accessible in the system's PATH. This is a prerequisite for running speed tests. ```bash speedtest --help ``` -------------------------------- ### Insert Example Settings Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Populates the settings table with various configuration values for different groups like general, notifications, and integrations. ```sql INSERT INTO settings (group, name, payload) VALUES ('general', 'threshold_enabled', '{"payload": true}'), ('general', 'threshold_download', '{"payload": 250}'), ('general', 'threshold_upload', '{"payload": 25}'), ('general', 'threshold_ping', '{"payload": 50}'), ('notifications', 'webhook_enabled', '{"payload": false}'), ('notifications', 'telegram_enabled', '{"payload": true}'), ('notifications', 'telegram_bot_token', '{"payload": "123456:ABC..."}'), ('integrations', 'influxdb_enabled', '{"payload": false}'); ``` -------------------------------- ### StatResource JSON Output Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/types.md Example JSON output transformed by StatResource, showing aggregated statistics for ping, download, and upload with bit conversions. ```json { "ping": { "avg": 15.5, "min": 10.2, "max": 25.8 }, "download": { "avg": 480000000, "avg_bits": 3840000000, "avg_bits_human": "3.84 Gbps" }, "upload": { "avg": 95000000, ... }, "total_results": 42 } ``` -------------------------------- ### Token Creation and Validation Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Examples for generating and validating API tokens. ```php use App\Models\User;\n\n// Create a new API token for a user\n$user = User::find(1);\n$token = $user->createToken('my-app');\n\n// Validate an incoming API token\n$request->validate([\n 'token' => 'required|exists:personal_access_tokens,token',\n]); ``` -------------------------------- ### Model Query Examples Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Demonstrates filtering, aggregating, and querying relationships for data models. ```php use App\Models\Result;\n\n// Get all results with a download speed greater than 100 Mbps\n$results = Result::where(\"download\", ">=", 100000000)->get();\n\n// Get the average upload speed for all results\n$averageUpload = Result::avg(\"upload\");\n\n// Get results and their associated server details\n$resultsWithServers = Result::with(\"server\")->get(); ``` -------------------------------- ### ResultResource JSON Output Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/types.md Example JSON output transformed by ResultResource, including computed bitrate and byte conversions. ```json { "id": 1, "service": "ookla", "ping": 15.5, "download": 500000000, "download_bits": 4000000000, "download_bits_human": "4 Gbps", "status": "completed", "healthy": true, "created_at": "2025-05-28T10:30:00" } ``` -------------------------------- ### Prometheus Metrics Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Example of metrics exposed by the application for Prometheus monitoring. These include speedtest results and a total counter. ```text speedtest_ping_milliseconds speedtest_download_bytes_per_second speedtest_upload_bytes_per_second speedtest_healthy (0 or 1) speedtest_total (counter) ``` -------------------------------- ### Create a New User Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Example of creating a new user with administrative privileges. Requires importing the User model and UserRole enum. ```php use App\Models\User; use App\Enums\UserRole; $user = User::create([ 'name' => 'Admin User', 'email' => 'admin@example.com', 'password' => Hash::make('password'), 'role' => UserRole::Admin, ]); ``` -------------------------------- ### Example Usage of Prunable Method Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Shows an example of how to use the `prunable` method to count the number of results that would be deleted by the prune command. This method is automatically invoked by Laravel's prune scheduler. ```php // Automatically called by Laravel's prune command Result::prune()->count(); // Delete and return count of deleted rows ``` -------------------------------- ### InfluxDB Configuration Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Configuration settings for integrating with InfluxDB, a time-series database. These are typically set in the .env file or through the settings UI. ```dotenv INFLUXDB_ENABLED=true INFLUXDB_URL=http://localhost:8086 INFLUXDB_TOKEN=token INFLUXDB_BUCKET=speedtest ``` -------------------------------- ### Example Data for Users Table Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Provides a sample JSON object for a user record in the 'users' table. Shows user identification, authentication details, and role information. ```json { "id": 1, "name": "Admin User", "email": "admin@example.com", "email_verified_at": "2025-01-01T00:00:00", "password": "$2y$12$வைக்", "role": "admin", "remember_token": null, "created_at": "2025-01-01T00:00:00", "updated_at": "2025-01-01T00:00:00" } ``` -------------------------------- ### Example Token Abilities for Personal Access Tokens Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Demonstrates the structure of the 'abilities' JSON field in the 'personal_access_tokens' table. Lists the permissions granted to a specific API token. ```json { "abilities": ["results:read", "speedtests:run"] } ``` -------------------------------- ### Custom Action Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Implements a custom action class using Lorisleiva Actions. This allows for organizing business logic into reusable action classes. ```php namespace App\Actions\Custom; use Lorisleiva\Actions\Concerns\AsAction; class CustomAction { use AsAction; public function handle(): void { // Business logic } } ``` -------------------------------- ### Example JSON API Response for ResultResource Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md Illustrates the structure of a typical JSON API response generated by the ResultResource, including all fields and their potential values. ```json { "id": 1, "service": "ookla", "ping": 15.5, "download": 500000000, "upload": 100000000, "download_bits": 4000000000, "upload_bits": 800000000, "download_bits_human": "4 Gbps", "upload_bits_human": "800 Mbps", "download_bytes": 500000000, "upload_bytes": 100000000, "download_bytes_human": "500 MB", "upload_bytes_human": "100 MB", "benchmarks": { "download": { "value": 480000000, "unit": "bytes/s" }, "upload": { "value": 95000000, "unit": "bytes/s" } }, "healthy": true, "status": "completed", "scheduled": true, "dispatched_by": 1, "comments": "Good speeds today", "data": { "server": { "id": "1234", "name": "Example ISP", "host": "speedtest.example.com", "location": "New York, NY", "country": "United States", "ip": "203.0.113.1", "port": 8080 }, "isp": "Example ISP", "interface": { "externalIp": "203.0.113.50" }, "ping": { "jitter": 1.5, "latency": 15.5, "low": 10.2, "high": 25.8 }, "download": { "bandwidth": 500000000, "bytes": 5000000000, "elapsed": 10000, "latency": { "iqm": 15.5, "low": 10.2, "high": 25.8, "jitter": 1.5 } }, "upload": { "bandwidth": 100000000, "bytes": 1000000000, "elapsed": 10000, "latency": { "iqm": 15.5, "low": 10.2, "high": 25.8, "jitter": 1.5 } }, "packetLoss": 0, "result": { "id": "123456789", "url": "https://www.speedtest.net/result/123456789" }, "message": "" }, "created_at": "2025-05-28T10:30:00", "updated_at": "2025-05-28T10:35:00" } ``` -------------------------------- ### Handle Error When Fetching Ookla Servers Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/actions.md This example shows the expected error response format when unable to retrieve Ookla servers. It returns an array containing an error message. ```php [ 'error' => '⚠️ Unable to retrieve Ookla servers, check internet connection and see logs.' ] ``` -------------------------------- ### StatResource Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Describes the structure of statistics, including aggregate fields and response examples. ```APIDOC ## StatResource ### Description Represents aggregated statistics derived from speed test results. This resource allows for summarizing performance metrics over time or across different dimensions. ### Structure - **average_download** (float) - The average download speed across a set of results. - **average_upload** (float) - The average upload speed across a set of results. - **average_ping** (float) - The average ping latency across a set of results. - **max_download** (float) - The highest download speed recorded. - **max_upload** (float) - The highest upload speed recorded. - **min_ping** (float) - The lowest ping latency recorded. - **total_results** (integer) - The total number of speed test results included in the aggregation. - **failed_results** (integer) - The number of speed test results that failed. - **start_time** (datetime) - The start timestamp of the aggregation period. - **end_time** (datetime) - The end timestamp of the aggregation period. ### Aggregate Fields - **download_std_dev** (float) - Standard deviation of download speeds. - **upload_std_dev** (float) - Standard deviation of upload speeds. - **ping_std_dev** (float) - Standard deviation of ping latencies. ### Response Example ```json { "average_download": 150.5, "average_upload": 75.2, "average_ping": 15.3, "max_download": 200.0, "max_upload": 100.0, "min_ping": 10.0, "total_results": 100, "failed_results": 5, "start_time": "2026-05-01T00:00:00+00:00", "end_time": "2026-05-30T23:59:59+00:00", "download_std_dev": 25.5, "upload_std_dev": 15.1, "ping_std_dev": 3.2 } ``` ``` -------------------------------- ### Conditional Field Inclusion Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md Demonstrates the use of the $this->when() method to conditionally include fields in the JSON response, such as 'download_bits_human'. ```php 'download_bits_human' => $this->when( $this->download, fn(): string => Bitrate::formatBits(Bitrate::bytesToBits($this->download)).'ps' ) ``` -------------------------------- ### Authentication Header Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Authenticate API requests using a Bearer token provided in the Authorization header. Ensure the token has the necessary abilities for the requested action. ```http Authorization: Bearer {token} ``` -------------------------------- ### Accessing Network Metrics Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Provides examples of accessing computed network metrics from a Result object. These attributes are derived from the raw test data. ```php $result->download_bits; $result->upload_bits; $result->packet_loss; $result->ip_address; $result->isp; ``` -------------------------------- ### Speedtest Events Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Details the 10 available speedtest events, their firing conditions, properties, and usage examples. ```APIDOC ## Speedtest Events ### Description This section details the various events that can be triggered during the speed test process, providing insights into their properties and how to utilize them. ### Events There are 10 distinct speedtest events available, each firing at specific points in the test lifecycle. ### Properties Each event typically includes properties such as: - **event_name** (string): The name of the event. - **timestamp** (datetime): The time the event occurred. - **payload** (mixed): Data associated with the event, varying by event type. ### Usage Examples Refer to the 'Code Examples Included' section for examples on listening to and handling these events. ``` -------------------------------- ### Example Data for Results Table Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Illustrates a typical JSON object representing a single speed test result entry in the 'results' table. Includes details like service, status, performance metrics, and timestamps. ```json { "id": 1, "service": "ookla", "status": "completed", "ping": 15.5, "download": 500000000, "upload": 100000000, "healthy": true, "scheduled": true, "benchmarks": { "download": { "value": 480000000, "unit": "bytes/s" }, "upload": { "value": 95000000, "unit": "bytes/s" } }, "data": { "server": { "id": 1234, "name": "...", ... }, "ping": { "jitter": 1.5, "latency": 15.5, ... }, "download": { "bandwidth": 500000000, ... }, "upload": { "bandwidth": 100000000, ... }, ... }, "comments": null, "dispatched_by": 1, "created_at": "2025-05-28T10:30:00", "updated_at": "2025-05-28T10:35:00" } ``` -------------------------------- ### Custom Job Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Defines a custom job that can be queued for asynchronous processing. This is useful for long-running tasks that should not block the main application flow. ```php namespace App\Jobs\Custom; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; class CustomJob implements ShouldQueue { use Queueable; public function handle(): void { // Job logic } } ``` -------------------------------- ### Get API Server Data (PHP) Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/actions.md Retrieves a list of speedtest servers formatted for API responses. Returns an empty array if the fetch fails. ```php public static function forApi(): array ``` ```php // Used by OoklaController $servers = GetOoklaSpeedtestServers::forApi(); return response()->json(['data' => $servers]); ``` -------------------------------- ### Fetch Raw Ookla Speedtest Servers Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/actions.md Use this static method to fetch the raw server data directly from the Ookla API. It includes an example of how to check for and handle potential errors. ```php use App\Actions\GetOoklaSpeedtestServers; $raw = GetOoklaSpeedtestServers::fetch(); if (!is_array($raw[0] ?? null)) { // Error occurred echo $raw[0]; } else { // Process servers } ``` -------------------------------- ### Custom Notification Channel Example Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Defines a custom notification channel for sending alerts. This involves creating a new Notification class and specifying the channel in the `via` method. ```php namespace App\Notifications\Custom; use App\Models\Result; use Illuminate\Notifications\Notification; class SpeedtestNotification extends Notification { public function via($notifiable) { return ['custom']; } public function toCustom($notifiable) { // Send notification } } ``` -------------------------------- ### Get Formatted Ookla Speedtest Servers for UI Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/actions.md Retrieve a list of available Ookla speedtest servers formatted for user selection in a UI. The result is a map of server IDs to displayable labels. ```php use App\Actions\GetOoklaSpeedtestServers; $servers = GetOoklaSpeedtestServers::run(); // Returns: // [ // "1234" => "Example ISP (New York, NY, 1234)", // "5678" => "Another ISP (Los Angeles, CA, 5678)", // ... // ] foreach ($servers as $id => $label) { echo "$id: $label"; } ``` -------------------------------- ### Get Aggregated Statistics Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md Retrieves aggregated statistics, allowing filtering by start and end dates. Requires the `results:read` token ability. ```APIDOC ## GET /api/v1/stats ### Description Get aggregated statistics. This endpoint allows for dynamic filtering of results based on the creation date. ### Method GET ### Endpoint /api/v1/stats ### Parameters #### Query Parameters - **filter[start_at]** (string) - Optional - Dynamic filter on created_at - **filter[end_at]** (string) - Optional - Dynamic filter on created_at ### Response #### Success Response (200) - **data** (StatResource) - Aggregated data ### Authorization Requires `results:read` token ability ``` -------------------------------- ### Run Database Backup Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Execute the backup command to create a backup of the current database. ```bash php artisan backup:run ``` -------------------------------- ### Get Scheduled Results Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Retrieves all results that are marked as 'scheduled'. ```php $scheduled = Result::where('scheduled', true)->get(); ``` -------------------------------- ### Action Invocation Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Demonstrates how to trigger specific actions or commands. ```php use Illuminate\Support\Facades\Artisan;\n\n// Run a specific Artisan command\nArtisan::call('speedtest:run'); ``` -------------------------------- ### Create a New Result Instance Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Demonstrates how to create a new Result record using the `create` static method. This is the typical way to instantiate and save a new speedtest result. ```php $result = Result::create([ 'service' => ResultService::Ookla, 'status' => ResultStatus::Waiting, 'scheduled' => true, 'dispatched_by' => $userId, ]); ``` -------------------------------- ### Get Healthy Results Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Retrieves all results marked as 'healthy'. ```php $healthy = Result::where('healthy', true)->get(); ``` -------------------------------- ### Create Database Migration Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Use this command to generate a new migration file for creating database tables. ```bash php artisan make:migration create_backups_table ``` -------------------------------- ### Get Completed Results Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Retrieves all results that have a status of 'Completed'. ```php $completed = Result::where('status', ResultStatus::Completed)->get(); ``` -------------------------------- ### Get Latest Result Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Retrieves the most recent speedtest result recorded. ```APIDOC ## GET /api/v1/results/latest ### Description Retrieves the most recent speedtest result that has been recorded. ### Method GET ### Endpoint /api/v1/results/latest ### Response #### Success Response (200) - **data** (object) - The most recent speedtest result object. - **message** (string) - Confirmation message. #### Response Example { "data": { "id": 1, "ping": 20, "download": 100000000, "upload": 50000000, "status": "completed", "created_at": "2023-10-27T10:00:00Z" }, "message": "ok" } ``` -------------------------------- ### Get Latest Result Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Retrieves the most recently created result record. ```php $latest = Result::latest('created_at')->first(); ``` -------------------------------- ### Helper Function Usage Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Shows how to use utility helper functions within the application. ```php use function App\Helpers\formatBytes;\n\n$formattedSize = formatBytes(1000000000); // Formats 1GB to a human-readable string ``` -------------------------------- ### User Authentication Methods Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Demonstrates how users can authenticate using either email/password credentials or an API token. ```php // Email/password login Auth::attempt(['email' => $email, 'password' => $password]); // API token $token = $user->createToken('API Token')->plainTextToken; // Use in requests: Authorization: Bearer $token ``` -------------------------------- ### Get Single Result Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Retrieves a specific speedtest result by its unique identifier. ```APIDOC ## GET /api/v1/results/{id} ### Description Retrieves a single speedtest result identified by its unique ID. ### Method GET ### Endpoint /api/v1/results/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the result to retrieve. ### Response #### Success Response (200) - **data** (object) - The speedtest result object. - **message** (string) - Confirmation message. #### Response Example { "data": { "id": 1, "ping": 20, "download": 100000000, "upload": 50000000, "status": "completed", "created_at": "2023-10-27T10:00:00Z" }, "message": "ok" } ``` -------------------------------- ### Create User with Fillable Attributes Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Creates a new user instance with specified fillable attributes. Ensure all required fields like name, email, password, and role are provided. ```php $user = User::create([ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => Hash::make('secret'), 'role' => UserRole::User, ]); ``` -------------------------------- ### ResultResource Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/INDEX.md Details the structure and fields of the ResultResource, including conditional fields and usage examples. ```APIDOC ## ResultResource ### Description Provides detailed information about a single speed test result, including various metrics and configuration details. This resource includes conditional fields that may be present based on the test type or configuration. ### Fields - **id** (integer) - Unique identifier for the result. - **download** (float) - Download speed in Mbps. - **upload** (float) - Upload speed in Mbps. - **ping** (float) - Ping latency in ms. - **server_id** (integer) - Identifier of the test server. - **server_name** (string) - Name of the test server. - **server_location** (string) - Location of the test server. - **ip_address** (string) - IP address from which the test was run. - **isp** (string) - Internet Service Provider. - **country** (string) - Country where the test was performed. - **city** (string) - City where the test was performed. - **created_at** (datetime) - Timestamp when the result was recorded. - **updated_at** (datetime) - Timestamp when the result was last updated. - **scheduled** (boolean) - Indicates if the test was part of a schedule. - **failed** (boolean) - Indicates if the test failed. - **latency** (object) - Contains detailed latency information. - **jitter** (float) - Jitter value in ms. - **raw** (float) - Raw latency value in ms. - **packet_loss** (float) - Percentage of packet loss. - **bytes_sent** (integer) - Total bytes sent during the test. - **bytes_received** (integer) - Total bytes received during the test. - **external_ip** (string) - The external IP address detected during the test. - **internal_ip** (string) - The internal IP address detected during the test. - **interface_name** (string) - The network interface used for the test. - **mac_address** (string) - The MAC address of the network interface. - **vpn_status** (boolean) - Indicates if a VPN was active during the test. - **vpn_name** (string) - Name of the VPN service if active. ### Usage Examples Refer to the 'Code Examples Included' section for examples on how to query and utilize ResultResource data. ``` -------------------------------- ### Run Speedtest Action Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Initiates a new speedtest execution. The test is queued and jobs handle the asynchronous execution. ```php use App\Actions\Ookla\RunSpeedtest; $result = RunSpeedtest::run( scheduled: false, serverId: 12345, dispatchedBy: auth()->id() ); // Returns Result model with status = Waiting // Jobs execute asynchronously ``` -------------------------------- ### Query Users by Role or Email Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Demonstrates how to query the User model to retrieve all users with a specific role (e.g., Admin) or find a user by their email address. ```php // Get all admins $admins = User::where('role', UserRole::Admin)->get(); // Get by email $user = User::where('email', 'user@example.com')->first(); ``` -------------------------------- ### Refreshing Database with Seeders Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Reset the database by dropping all tables, running migrations, and seeding the database with initial data. Use with caution as it deletes all existing data. ```bash # Refresh php artisan migrate:refresh --seed ``` -------------------------------- ### Get Latest Result (Legacy) Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Retrieves the most recent speedtest result in a legacy format. This endpoint is deprecated. ```APIDOC ## GET /speedtest/latest ### Description Retrieves the latest speedtest result using a legacy format. This endpoint is deprecated and may be removed in future versions. ### Method GET ### Endpoint /speedtest/latest ### Response #### Success Response (200) - **data** (object) - The most recent speedtest result in legacy format. - **message** (string) - Confirmation message. #### Response Example { "data": { "ping": 20, "download": 100000000, "upload": 50000000 }, "message": "ok" } ``` -------------------------------- ### Backup SQLite Database Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Creates a backup copy of the SQLite database file. ```bash # Backup cp storage/database.sqlite storage/database.sqlite.backup ``` -------------------------------- ### Ookla Result JSON Structure Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Example of the JSON structure stored in the 'data' field for a complete Ookla speedtest result. ```json { "server": { "id": 12345, "name": "ISP Name", "host": "speedtest.example.com", "location": "New York, NY", "country": "United States", "ip": "203.0.113.1", "port": 8080 }, "isp": "Example ISP", "interface": { "externalIp": "203.0.113.50" }, "ping": { "jitter": 1.5, "latency": 15.5, "low": 10.2, "high": 25.8 }, "download": { "bandwidth": 500000000, "bytes": 5000000000, "elapsed": 10000, "latency": { "iqm": 15.5, "low": 10.2, "high": 25.8, "jitter": 1.5 } }, "upload": { "bandwidth": 100000000, "bytes": 1000000000, "elapsed": 10000, "latency": { "iqm": 15.5, "low": 10.2, "high": 25.8, "jitter": 1.5 } }, "packetLoss": 0, "result": { "id": "123456789", "url": "https://www.speedtest.net/result/123456789" }, "message": "" } ``` -------------------------------- ### MySQL Database Configuration Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Configuration for connecting to a MySQL database. Ensure DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD are set correctly. ```bash # MySQL DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=speedtest_tracker DB_USERNAME=root DB_PASSWORD=secret ``` -------------------------------- ### Processing Queue Jobs Asynchronously Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/README.md Configure the application to process queue jobs asynchronously by setting the QUEUE_CONNECTION to a driver like 'database' or 'redis'. This improves application responsiveness by offloading tasks. ```bash # Or process asynchronously php artisan queue:work ``` -------------------------------- ### SQLite Database Configuration Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Default database configuration using SQLite. Set DB_CONNECTION to sqlite and specify the database file name. ```bash # SQLite (default) DB_CONNECTION=sqlite DB_DATABASE=database.sqlite ``` -------------------------------- ### Conditional Field Example in StatResource Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md Shows how to conditionally include fields in the StatResource response using the $this->when() method, based on the presence of data. ```php // These fields only included if the stat is not null 'avg_bits' => $this->when($this->avg_download, fn(): int|float => Bitrate::bytesToBits($this->avg_download)) ``` -------------------------------- ### PostgreSQL Database Configuration Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/database-schema.md Configuration for connecting to a PostgreSQL database. Ensure DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD are set correctly. ```bash # PostgreSQL DB_CONNECTION=pgsql DB_HOST=localhost DB_PORT=5432 DB_DATABASE=speedtest_tracker DB_USERNAME=postgres DB_PASSWORD=secret ``` -------------------------------- ### Format Bits to Bitrate String Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/helpers.md Use toBitRate to format a bit value into a standard bitrate string with units like Bps, Kbps, Mbps, Gbps. Similar to bitsToHuman but appends 'ps' to units. ```php Number::toBitRate(0); // "0 B" Number::toBitRate(1000); // "1 Kbps" Number::toBitRate(1000000); // "1 Mbps" Number::toBitRate(4000000000, 2); // "4.00 Gbps" Number::toBitRate(500000000, 1, 2); // "500.0 Mbps" ``` ```php // StatResource uses this for display 'avg_bits_human' => Number::toBitRate($bits) . 'ps' // But Bitrate helper is now preferred ``` -------------------------------- ### Run Speedtest Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Queue a new Ookla speedtest to be executed. Authentication is required, and the user's token must have the `speedtests:run` ability. An optional `server_id` can be provided. ```APIDOC ## POST /api/v1/speedtests/run ### Description Queue a new Ookla speedtest to be executed. ### Method POST ### Endpoint /api/v1/speedtests/run ### Parameters #### Request Body - **server_id** (integer) - Optional - Optional Ookla server ID to use for the test. ### Request Example ```json { "server_id": 12345 } ``` ### Response #### Success Response (201) - **data** (object) - Details of the queued speedtest. - **message** (string) - "Speedtest added to the queue." #### Response Example ```json { "data": { "id": 42, "service": "ookla", "ping": null, "download": null, "upload": null, "download_bits": null, "upload_bits": null, "benchmarks": null, "healthy": null, "status": "waiting", "scheduled": true, "dispatched_by": 1, "comments": null, "data": { "server": { "id": 12345 } }, "created_at": "2025-05-28T10:35:00", "updated_at": "2025-05-28T10:35:00" }, "message": "Speedtest added to the queue." } ``` #### Response (Validation Error) ```json { "data": { "server_id": ["The server_id must be an integer."] }, "message": "Validation failed." } ``` #### Error Handling - **403 Forbidden**: User token lacks `speedtests:run` ability. - **422 Unprocessable Entity**: Validation error. ``` -------------------------------- ### Get Latest Result Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Fetch the single most recent speedtest result. Authentication is required, and the user's token must have the `results:read` ability. ```APIDOC ## GET /api/v1/results/latest ### Description Fetch the single most recent speedtest result. ### Method GET ### Endpoint /api/v1/results/latest ### Parameters No body or query parameters required. ### Response #### Success Response (200) - **data** (object) - Contains the speedtest result details (same structure as 'Get Result by ID'). - **message** (string) - "ok" #### Error Handling - **403 Forbidden**: User token lacks `results:read` ability. - **404 Not Found**: No results exist in the database. ``` -------------------------------- ### Get Result by ID Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Fetch a single speedtest result by its ID. Authentication is required, and the user's token must have the `results:read` ability. ```APIDOC ## GET /api/v1/results/{id} ### Description Fetch a single speedtest result by its ID. ### Method GET ### Endpoint /api/v1/results/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - Result ID #### Request Body No body required. ### Response #### Success Response (200) - **data** (object) - Contains the speedtest result details. - **message** (string) - "ok" #### Response Example ```json { "data": { "id": 1, "service": "ookla", "ping": 15.5, "download": 500000000, "upload": 100000000, "download_bits": 4000000000, "upload_bits": 800000000, "download_bits_human": "4 Gbps", "upload_bits_human": "800 Mbps", "download_bytes": 500000000, "upload_bytes": 100000000, "download_bytes_human": "500 MB", "upload_bytes_human": "100 MB", "benchmarks": { ... }, "healthy": true, "status": "completed", "scheduled": true, "dispatched_by": 1, "comments": null, "data": { ... }, "created_at": "2025-05-28T10:30:00", "updated_at": "2025-05-28T10:35:00" }, "message": "ok" } ``` #### Error Handling - **403 Forbidden**: User token lacks `results:read` ability. - **404 Not Found**: Result ID does not exist. ``` -------------------------------- ### StatResource Usage in Controllers Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md Demonstrates how to fetch aggregated statistics and return them using StatResource in a controller. ```php use App\Http\Resources\V1\StatResource; $stats = QueryBuilder::for(Result::class) ->selectRaw('avg(ping) as avg_ping') ->selectRaw('min(download) as min_download') // ... more aggregates ->first(); return new StatResource($stats); ``` -------------------------------- ### Get Aggregated Statistics Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Fetch aggregated speedtest statistics. This endpoint requires authentication and the `results:read` token ability. Optional date filters can be applied. ```json { "data": { "ping": { "avg": 15.5, "min": 10.2, "max": 25.8 }, "download": { "avg": 480000000, "avg_bits": 3840000000, "avg_bits_human": "3.84 Gbps", "min": 450000000, "min_bits": 3600000000, "min_bits_human": "3.6 Gbps", "max": 550000000, "max_bits": 4400000000, "max_bits_human": "4.4 Gbps" }, "upload": { "avg": 95000000, "avg_bits": 760000000, "avg_bits_human": "760 Mbps", "min": 85000000, "min_bits": 680000000, "min_bits_human": "680 Mbps", "max": 110000000, "max_bits": 880000000, "max_bits_human": "880 Mbps" }, "total_results": 42 }, "message": "ok" } ``` -------------------------------- ### Get Speedtest Result by ID Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Fetches a single speedtest result using its unique identifier. Requires authentication with a Bearer token and the `results:read` ability. ```json { "data": { "id": 1, "service": "ookla", "ping": 15.5, "download": 500000000, "upload": 100000000, "download_bits": 4000000000, "upload_bits": 800000000, "download_bits_human": "4 Gbps", "upload_bits_human": "800 Mbps", "download_bytes": 500000000, "upload_bytes": 100000000, "download_bytes_human": "500 MB", "upload_bytes_human": "100 MB", "benchmarks": { ... }, "healthy": true, "status": "completed", "scheduled": true, "dispatched_by": 1, "comments": null, "data": { ... }, "created_at": "2025-05-28T10:30:00", "updated_at": "2025-05-28T10:35:00" }, "message": "ok" } ``` -------------------------------- ### SpeedtestController::__invoke Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md Queues a new speedtest to be run. This endpoint initiates a speed test, optionally specifying a server. ```APIDOC ## POST /api/v1/speedtests/run ### Description Queue a new speedtest. ### Authorization Requires `speedtests:run` token ability ### Request Body ```json { "server_id": 12345 } ``` ### Validation - `server_id` - Optional integer ### Returns `ResultResource` with status 201 Created ``` -------------------------------- ### Create New Result Record Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Creates a new result record with initial status 'Waiting' and marks it as scheduled. ```php use App\Models\Result; use App\Enums\ResultService; use App\Enums\ResultStatus; $result = Result::create([ 'service' => ResultService::Ookla, 'status' => ResultStatus::Waiting, 'scheduled' => true, 'dispatched_by' => auth()->id(), ]); ``` -------------------------------- ### Invoke Aggregated Statistics Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/resources.md This method retrieves aggregated statistics. It requires the `results:read` token ability and supports dynamic filtering by start and end dates. ```php public function __invoke(Request $request) ``` -------------------------------- ### Accessing Latency Details Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Illustrates how to access computed latency details for both ping, download, and upload phases of the speedtest. This includes jitter, min, max, and IQM values. ```php $result->ping_jitter; $result->ping_low; $result->ping_high; $result->download_jitter; $result->download_latency_low; $result->download_latency_high; $result->download_latency_iqm; $result->upload_jitter; $result->upload_latency_low; $result->upload_latency_high; $result->upload_latency_iqm; ``` -------------------------------- ### Example Usage of DispatchedBy Relationship Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Demonstrates how to access the User model associated with a Result via the `dispatchedBy` relationship. It retrieves the user who triggered the test and accesses their name. ```php $result = Result::find(1); $user = $result->dispatchedBy; // Returns User model or null echo $user->name; // User who triggered the test ``` -------------------------------- ### Queue a Scheduled Speedtest Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/actions.md Use this to queue a new speedtest execution, optionally specifying a server and the user who triggered it. The action returns the newly created Result model. ```php use App\Actions\Ookla\RunSpeedtest; use App\Enums\ResultService; use App\Enums\ResultStatus; // Queue a scheduled test $result = RunSpeedtest::run( scheduled: true, serverId: 12345, dispatchedBy: auth()->id() ); echo $result->id; // 42 echo $result->status; // ResultStatus::Waiting ``` -------------------------------- ### List Ookla Servers Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md List available Ookla speedtest servers for running manual tests. Authentication is required, and the user's token must have the `ookla:list-servers` ability. ```APIDOC ## GET /api/v1/ookla/list-servers ### Description List available Ookla speedtest servers for running manual tests. ### Method GET ### Endpoint /api/v1/ookla/list-servers ### Parameters No body or query parameters required. ### Response #### Success Response (200) - **data** (array) - A list of available Ookla server objects. - **message** (string) - "Speedtest servers fetched successfully." #### Response Example ```json { "data": [ { "id": "1234", "host": "speedtest.example.com", "name": "Example ISP", "location": "New York, NY", "country": "United States" }, { "id": "5678", "host": "speedtest2.example.com", "name": "Another ISP", "location": "Los Angeles, CA", "country": "United States" } ], "message": "Speedtest servers fetched successfully." } ``` #### Response (Fetch Error) ```json { "data": [], "message": "Speedtest servers fetched successfully." } ``` #### Error Handling - **403 Forbidden**: User token lacks `ookla:list-servers` ability. ``` -------------------------------- ### GET /api/v1/stats Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/endpoints.md Fetch aggregated speedtest statistics across all results with optional date filtering. Authentication is required via a Bearer token with the `results:read` ability. ```APIDOC ## GET /api/v1/stats ### Description Fetch aggregated speedtest statistics across all results with optional date filtering. Authentication is required via a Bearer token with the `results:read` ability. ### Method GET ### Endpoint /api/v1/stats ### Parameters #### Query Parameters - **filter[start_at]** (string) - Optional - Dynamic filter for stats start date (filters `created_at`) - **filter[end_at]** (string) - Optional - Dynamic filter for stats end date (filters `created_at`) ### Response #### Success Response (200) - **data** (object) - Contains aggregated statistics for ping, download, upload, and total results. - **message** (string) - Status message, typically "ok". #### Response Example ```json { "data": { "ping": { "avg": 15.5, "min": 10.2, "max": 25.8 }, "download": { "avg": 480000000, "avg_bits": 3840000000, "avg_bits_human": "3.84 Gbps", "min": 450000000, "min_bits": 3600000000, "min_bits_human": "3.6 Gbps", "max": 550000000, "max_bits": 4400000000, "max_bits_human": "4.4 Gbps" }, "upload": { "avg": 95000000, "avg_bits": 760000000, "avg_bits_human": "760 Mbps", "min": 85000000, "min_bits": 680000000, "min_bits_human": "680 Mbps", "max": 110000000, "max_bits": 880000000, "max_bits_human": "880 Mbps" }, "total_results": 42 }, "message": "ok" } ``` ### Error Handling - **403 Forbidden**: User token lacks `results:read` ability. ``` -------------------------------- ### Accessing Test Data Details Source: https://github.com/alexjustesen/speedtest-tracker/blob/1.x/_autodocs/api-reference/models.md Demonstrates how to access specific test data fields, such as total bytes transferred, duration, and the Ookla result URL. Also shows how to retrieve any error messages. ```php $result->downloaded_bytes; $result->uploaded_bytes; $result->download_elapsed; $result->upload_elapsed; $result->result_url; $result->error_message; ```