├── .gitattributes ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── resources └── views │ ├── active-users │ └── tile.blade.php │ ├── devices │ └── tile.blade.php │ └── urls │ └── tile.blade.php ├── src ├── Commands │ └── FetchGoogleAnalyticsRealtimeCommand.php ├── Components │ ├── GoogleAnalyticsRealtimeActiveUsersComponent.php │ ├── GoogleAnalyticsRealtimeDevicesComponent.php │ └── GoogleAnalyticsRealtimeUrlsComponent.php ├── GoogleAnalyticsRealtimeApi.php ├── GoogleAnalyticsRealtimeServiceProvider.php └── GoogleAnalyticsRealtimeStore.php └── tests └── ExampleTest.php /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/ 2 | node_modules/ 3 | npm-debug.log 4 | yarn-error.log 5 | 6 | # Laravel 4 specific 7 | bootstrap/compiled.php 8 | app/storage/ 9 | 10 | # Laravel 5 & Lumen specific 11 | public/storage 12 | public/hot 13 | 14 | # Laravel 5 & Lumen specific with changed public path 15 | public_html/storage 16 | public_html/hot 17 | 18 | storage/*.key 19 | .env 20 | Homestead.yaml 21 | Homestead.json 22 | /.vagrant 23 | .phpunit.result.cache 24 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-dashboard-google-analytics-realtime-tile` will be documented in this file 4 | 5 | ## 1.0.0 - 2020-06-09 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) :vendor_name 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A tile to display Google Analytics realtime information 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/ingoldsby/laravel-dashboard-google-analytics-realtime-tile.svg?style=flat-square)](https://packagist.org/packages/ingoldsby/laravel-dashboard-google-analytics-realtime-tile) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/ingoldsby/laravel-dashboard-google-analytics-realtime-tile.svg?style=flat-square)](https://packagist.org/packages/ingoldsby/laravel-dashboard-google-analytics-realtime-tile) 5 | 6 | This tile can be used on [the Laravel Dashboard](https://docs.spatie.be/laravel-dashboard) to display Google Analytics realtime information. 7 | 8 | ## Installation 9 | 10 | You can install the package via composer: 11 | 12 | ```bash 13 | composer require ingoldsby/laravel-dashboard-google-analytics-realtime-tile 14 | ``` 15 | 16 | ## Google Analytics credentials 17 | 18 | Before using this tile you need to ensure you have the correct credentials on your system. Follow the instructions on [Real Time Reporting API Overview](https://developers.google.com/analytics/devguides/reporting/realtime/v3) to sign up to access the API. When access is granted: 19 | 1. Enable the Google Analytics API. 20 | 2. Create a [Service Account](https://developers.google.com/identity/protocols/oauth2/service-account) with appropriate permissions. 21 | 3. Navigate to the Service Account and add a new JSON private key. A JSON file will be downloaded - rename this to 'analytics-credentials.json' and move it to your root Laravel directory. 22 | 23 | Make note of the 'Service Account ID' that is generated. It will follow the format of "@.iam.gserviceaccount.com". 24 | 25 | ## Google Analytics view 26 | 27 | Access [Google Analytics](https://analytics.google.com/analytics) and navigate to the required view (e.g. Account > Properties & Apps > View). Make note of the 'View ID' that is displayed underneath the view name. Click on 'View User Management' and add a new user. The email address is the Service Account ID that was used in the Google Analytics credentials step. 28 | 29 | More information is available on the [Real Time Reporting API Developer Guide](https://developers.google.com/analytics/devguides/reporting/realtime/v3/devguide). Also take into account your [quotas and limits on API Requests](https://developers.google.com/analytics/devguides/config/mgmt/v3/limits-quotas). 30 | 31 | ## Usage 32 | 33 | In the `dashboard` config file, you must add this configuration in the `tiles` key. 34 | 35 | 1. Enter the view ID that you wish to gather information for e.g. 123456789. 36 | 2. If you changed the name and/or location of the analytics credentials JSON from suggested below, update the field. 37 | 3. The number of URLs displayed on the URLs tile can be limited by amending the `urls_displayed` field, with a default value of 10. 38 | 4. The `active users` tile can have the background changed depending upon a threshold of how many active users you set. If the `active_users_warning_threshold` field is not in the settings, there will be no threshold and no change to the background. Setting to a value of 0 would use the warning background when there are 0 active users. Setting to a value of 10 would use the warning background when there are 10 or fewer active users. 39 | 40 | ```php 41 | // in config/dashboard.php 42 | 43 | return [ 44 | // ... 45 | 'tiles' => [ 46 | 'google_analytics_realtime' => [ 47 | 'view_id' => '123456789', 48 | 'key_file_location' => __DIR__ . '/../analytics-credentials.json', 49 | 'urls_displayed' => 4, 50 | 'active_users_warning_threshold' => 0, 51 | ] 52 | ], 53 | ]; 54 | ``` 55 | 56 | In `app\Console\Kernel.php` you should schedule the `\Ingoldsby\GoogleAnalyticsRealtimeTile\Commands\FetchGoogleAnalyticsRealtimeCommand` to run every minute, pending your Google API quotas and limits. 57 | 58 | ```php 59 | // in app/console/Kernel.php 60 | 61 | protected function schedule(Schedule $schedule) 62 | { 63 | // ... 64 | $schedule->command(\Ingoldsby\GoogleAnalyticsRealtimeTile\Commands\FetchGoogleAnalyticsRealtimeCommand::class)->everyMinute(); 65 | } 66 | ``` 67 | 68 | In your dashboard view you can use three separate tiles: 69 | * `livewire:google-analytics-realtime-active-users-tile` 70 | * `livewire:google-analytics-realtime-devices-tile` 71 | * `livewire:google-analytics-realtime-urls-tile` 72 | 73 | ```html 74 | 75 | 76 | 77 | 78 | 79 | ``` 80 | 81 | The layout above will produce something similar to: 82 | 83 | ![Dashboard tiles](https://user-images.githubusercontent.com/26500496/84089697-05779b00-aa33-11ea-86e3-e2d4da80fc6b.png) 84 | 85 | ## Testing 86 | 87 | ``` bash 88 | composer test 89 | ``` 90 | 91 | ## Changelog 92 | 93 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 94 | 95 | ## Contributing 96 | 97 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 98 | 99 | ## Security 100 | 101 | If you discover any security related issues, please email instead of using the issue tracker. 102 | 103 | ## Support Spatie 104 | 105 | I have learnt a lot from Spatie's various packages, including [Mailcoach](https://mailcoach.app), and would recommend you check them out if you want to know more. 106 | 107 | Learn how to create a package like this one, by watching Spatie's premium video course: 108 | 109 | [![Laravel Package training](https://spatie.be/github/package-training.jpg)](https://laravelpackage.training) 110 | 111 | Spatie invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support them by [buying one of their paid products](https://spatie.be/open-source/support-us). 112 | 113 | ## Credits 114 | 115 | - [Ingoldsby](https://github.com/ingoldsby) 116 | - [All Contributors](../../contributors) 117 | 118 | ## License 119 | 120 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ingoldsby/laravel-dashboard-google-analytics-realtime-tile", 3 | "description": "A Google Analytics realtime tile for Laravel Dashboard", 4 | "keywords": [ 5 | "ingoldsby", 6 | "laravel-dashboard-google-analytics-realtime-tile" 7 | ], 8 | "homepage": "https://github.com/ingoldsby/laravel-dashboard-google-analytics-realtime-tile", 9 | "license": "MIT", 10 | "authors": [ 11 | { 12 | "name": "Ingoldsby", 13 | "email": "ingoldsby@ingoldsby.info", 14 | "role": "Developer" 15 | } 16 | ], 17 | "require": { 18 | "google/apiclient": "^2.0", 19 | "php": "^7.4", 20 | "spatie/laravel-dashboard": "^1.0" 21 | }, 22 | "require-dev": { 23 | "phpunit/phpunit": "^9.0" 24 | }, 25 | "autoload": { 26 | "psr-4": { 27 | "Ingoldsby\\GoogleAnalyticsRealtimeTile\\": "src" 28 | } 29 | }, 30 | "autoload-dev": { 31 | "psr-4": { 32 | "Spatie\\GoogleAnalyticsRealtimeTile\\Tests\\": "tests" 33 | } 34 | }, 35 | "scripts": { 36 | "test": "vendor/bin/phpunit", 37 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage", 38 | "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes" 39 | }, 40 | "config": { 41 | "sort-packages": true 42 | }, 43 | "extra": { 44 | "laravel": { 45 | "providers": [ 46 | "Ingoldsby\\GoogleAnalyticsRealtimeTile\\GoogleAnalyticsRealtimeServiceProvider" 47 | ] 48 | } 49 | }, 50 | "minimum-stability": "dev", 51 | "prefer-stable": true 52 | } 53 | -------------------------------------------------------------------------------- /resources/views/active-users/tile.blade.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 |
Right now
6 |
7 |
{{ $activeUsers }}
8 |
9 |
active users on site
10 |
11 |
12 |
13 |
-------------------------------------------------------------------------------- /resources/views/devices/tile.blade.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |

Realtime Devices

4 |
5 |
6 |
7 | @foreach ($devices as $key => $value) 8 |
{{ $key }}: {{ $value }} @if ($value == 1)visitor @else visitors @endif
9 | @endforeach 10 |
11 |
12 |
13 |
14 |
-------------------------------------------------------------------------------- /resources/views/urls/tile.blade.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |

Realtime Pages (top {{ count($urls) }})

5 |
6 |
7 | @foreach ($urls as $key => $value) 8 |
{{ $value }} @if ($value == 1) visitor @else visitors @endif: {{ $key }}
9 | @endforeach 10 |
11 |
12 |
13 |
14 |
-------------------------------------------------------------------------------- /src/Commands/FetchGoogleAnalyticsRealtimeCommand.php: -------------------------------------------------------------------------------- 1 | info('Fetching Google Analytics ...'); 18 | 19 | $response = $realtime->getAnalyticsRealtime(); 20 | 21 | GoogleAnalyticsRealtimeStore::make()->setAnalyticsRealtime($response); 22 | 23 | $this->info('All done!'); 24 | } 25 | } -------------------------------------------------------------------------------- /src/Components/GoogleAnalyticsRealtimeActiveUsersComponent.php: -------------------------------------------------------------------------------- 1 | position = $position; 16 | } 17 | 18 | public function render() 19 | { 20 | return view('dashboard-google-analytics-realtime-tiles::active-users.tile', [ 21 | 'activeUsers' => GoogleAnalyticsRealtimeStore::make()->analyticsRealtimeActiveUsers(), 22 | 'refreshIntervalInSeconds' => config('dashboard.tiles.google_analytics_realtime.refresh_interval_in_seconds') ?? 60, 23 | ]); 24 | } 25 | } -------------------------------------------------------------------------------- /src/Components/GoogleAnalyticsRealtimeDevicesComponent.php: -------------------------------------------------------------------------------- 1 | position = $position; 16 | } 17 | 18 | public function render() 19 | { 20 | return view('dashboard-google-analytics-realtime-tiles::devices.tile', [ 21 | 'devices' => GoogleAnalyticsRealtimeStore::make()->analyticsRealtimeDevices(), 22 | 'refreshIntervalInSeconds' => config('dashboard.tiles.google_analytics_realtime.refresh_interval_in_seconds') ?? 60, 23 | ]); 24 | } 25 | } -------------------------------------------------------------------------------- /src/Components/GoogleAnalyticsRealtimeUrlsComponent.php: -------------------------------------------------------------------------------- 1 | position = $position; 16 | } 17 | 18 | public function render() 19 | { 20 | return view('dashboard-google-analytics-realtime-tiles::urls.tile', [ 21 | 'urls' => GoogleAnalyticsRealtimeStore::make()->analyticsRealtimeUrls(), 22 | 'refreshIntervalInSeconds' => config('dashboard.tiles.google_analytics_realtime.refresh_interval_in_seconds') ?? 60, 23 | ]); 24 | } 25 | } -------------------------------------------------------------------------------- /src/GoogleAnalyticsRealtimeApi.php: -------------------------------------------------------------------------------- 1 | 'rt:pagePath, rt:deviceCategory'); 17 | 18 | try { 19 | $results = $analytics->data_realtime->get( 20 | 'ga:' . config('dashboard.tiles.google_analytics_realtime.view_id'), 21 | 'rt:activeUsers', 22 | $optParams); 23 | 24 | $realtimeInfo['active_users'] = $results->totalsForAllResults['rt:activeUsers']; 25 | 26 | [$url, $device] = self::extractUrlAndDeviceInfo($results->rows); 27 | 28 | $realtimeInfo['active_users'] = $results->totalsForAllResults['rt:activeUsers']; 29 | $realtimeInfo['urls'] = array_slice($url, 0, (config('dashboard.tiles.google_analytics_realtime.urls_displayed') ?? 10)); 30 | $realtimeInfo['devices'] = $device; 31 | 32 | return $realtimeInfo; 33 | } catch (apiServiceException $e) { 34 | $error = $e->getMessage(); 35 | 36 | return $error; 37 | } 38 | 39 | } 40 | 41 | /** 42 | * Initializes an Analytics Reporting API V4 service object. 43 | * 44 | * @return An authorized Analytics Reporting API V4 service object. 45 | */ 46 | public static function initializeAnalytics() : Google_Service_Analytics 47 | { 48 | $client = new Google_Client(); 49 | 50 | $client->setAuthConfig(config('dashboard.tiles.google_analytics_realtime.key_file_location')); 51 | $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); 52 | $analytics = new Google_Service_Analytics($client); 53 | 54 | return $analytics; 55 | } 56 | 57 | public static function extractUrlAndDeviceInfo($rows) : array 58 | { 59 | 60 | $url = array(); 61 | $device = array(); 62 | 63 | if (isset($rows)) { 64 | foreach ($rows as $row) { 65 | $url = self::initOrUpdateArray($url, $row[0], $row[2]); 66 | $device = self::initOrUpdateArray($device, $row[1], $row[2]); 67 | } 68 | 69 | array_multisort($url, SORT_DESC); 70 | array_multisort($device, SORT_DESC); 71 | } 72 | 73 | return [$url, $device]; 74 | 75 | } 76 | 77 | public static function initOrUpdateArray($array, $key, $value) : array 78 | { 79 | 80 | if (! array_key_exists($key, $array)) { 81 | $array[$key] = 0; 82 | } 83 | 84 | $array[$key] = $array[$key] + $value; 85 | 86 | return $array; 87 | 88 | } 89 | 90 | } -------------------------------------------------------------------------------- /src/GoogleAnalyticsRealtimeServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 18 | $this->commands([ 19 | FetchGoogleAnalyticsRealtimeCommand::class, 20 | ]); 21 | } 22 | 23 | $this->publishes([ 24 | __DIR__ . '/../resources/views' => resource_path('views/vendor/dashboard-google-analytics-realtime-tiles'), 25 | ], 'dashboard-google-analytics-realtime-tiles'); 26 | 27 | $this->loadViewsFrom(__DIR__ . '/../resources/views', 'dashboard-google-analytics-realtime-tiles'); 28 | 29 | Livewire::component('google-analytics-realtime-active-users-tile', GoogleAnalyticsRealtimeActiveUsersComponent::class); 30 | Livewire::component('google-analytics-realtime-devices-tile', GoogleAnalyticsRealtimeDevicesComponent::class); 31 | Livewire::component('google-analytics-realtime-urls-tile', GoogleAnalyticsRealtimeUrlsComponent::class); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/GoogleAnalyticsRealtimeStore.php: -------------------------------------------------------------------------------- 1 | tile = Tile::firstOrCreateForName("google_analytics_realtime"); 19 | } 20 | 21 | public function setAnalyticsRealtime(array $analyticsRealtime) : self 22 | { 23 | $this->tile->putData('active_users', $analyticsRealtime['active_users']); 24 | $this->tile->putData('urls', $analyticsRealtime['urls']); 25 | $this->tile->putData('devices', $analyticsRealtime['devices']); 26 | 27 | return $this; 28 | } 29 | 30 | public function analyticsRealtimeActiveUsers() 31 | { 32 | return $this->tile->getData('active_users') ?? []; 33 | } 34 | 35 | public function analyticsRealtimeUrls() 36 | { 37 | return $this->tile->getData('urls') ?? []; 38 | } 39 | 40 | public function analyticsRealtimeDevices() 41 | { 42 | return $this->tile->getData('devices') ?? []; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /tests/ExampleTest.php: -------------------------------------------------------------------------------- 1 | assertTrue(true); 13 | } 14 | } --------------------------------------------------------------------------------