Anonymous Segment.com tracking. Closes #91.

This commit is contained in:
James Brooks
2015-01-23 17:24:34 +00:00
committed by Joseph Cohen
parent a63c65a6c3
commit 5c391cc888
23 changed files with 523 additions and 8 deletions

View File

@@ -127,16 +127,16 @@ return [
* Packages Service Providers... * Packages Service Providers...
*/ */
'Dingo\Api\Provider\ApiServiceProvider', 'Dingo\Api\Provider\ApiServiceProvider',
'GrahamCampbell\Security\SecurityServiceProvider', 'Fideloper\Proxy\ProxyServiceProvider',
'GrahamCampbell\Binput\BinputServiceProvider', 'GrahamCampbell\Binput\BinputServiceProvider',
'GrahamCampbell\Throttle\ThrottleServiceProvider',
'GrahamCampbell\Markdown\MarkdownServiceProvider', 'GrahamCampbell\Markdown\MarkdownServiceProvider',
'Roumen\Feed\FeedServiceProvider', 'GrahamCampbell\Security\SecurityServiceProvider',
'Thujohn\Rss\RssServiceProvider', 'GrahamCampbell\Throttle\ThrottleServiceProvider',
'Jenssegers\Date\DateServiceProvider', 'Jenssegers\Date\DateServiceProvider',
'McCool\LaravelAutoPresenter\LaravelAutoPresenterServiceProvider', 'McCool\LaravelAutoPresenter\LaravelAutoPresenterServiceProvider',
'PragmaRX\Google2FA\Vendor\Laravel\ServiceProvider', 'PragmaRX\Google2FA\Vendor\Laravel\ServiceProvider',
'Fideloper\Proxy\ProxyServiceProvider', 'Roumen\Feed\FeedServiceProvider',
'Thujohn\Rss\RssServiceProvider',
/* /*
* Application Service Providers... * Application Service Providers...
@@ -148,6 +148,8 @@ return [
'CachetHQ\Cachet\Providers\ViewComposerServiceProvider', 'CachetHQ\Cachet\Providers\ViewComposerServiceProvider',
'CachetHQ\Cachet\Providers\LoadConfigServiceProvider', 'CachetHQ\Cachet\Providers\LoadConfigServiceProvider',
'CachetHQ\Cachet\Providers\SettingsServiceProvider', 'CachetHQ\Cachet\Providers\SettingsServiceProvider',
'CachetHQ\Cachet\Providers\SegmentApiServiceProvider',
'CachetHQ\Segment\SegmentServiceProvider',
], ],

View File

@@ -0,0 +1,9 @@
<?php
return [
'write_key' => '',
'consumer' => 'socket',
'debug' => false,
'ssl' => true,
'error_handler' => null,
];

View File

@@ -10,4 +10,5 @@ return [
'complete_setup' => 'Setup abschließen', 'complete_setup' => 'Setup abschließen',
'completed' => 'Cachet wurde erfolgreich eingerichtet!', 'completed' => 'Cachet wurde erfolgreich eingerichtet!',
'finish_setup' => 'Zum Dashboard', 'finish_setup' => 'Zum Dashboard',
'allow_tracking' => 'Allow anonymous usage tracking?',
]; ];

View File

@@ -10,4 +10,5 @@ return [
'complete_setup' => 'Complete Setup', 'complete_setup' => 'Complete Setup',
'completed' => 'Cachet has been configured successfully!', 'completed' => 'Cachet has been configured successfully!',
'finish_setup' => 'Go to dashboard', 'finish_setup' => 'Go to dashboard',
'allow_tracking' => 'Allow anonymous usage tracking?',
]; ];

View File

@@ -10,4 +10,5 @@ return [
'complete_setup' => 'Terminer l\'installation', 'complete_setup' => 'Terminer l\'installation',
'completed' => 'Cachet a été configuré avec succès !', 'completed' => 'Cachet a été configuré avec succès !',
'finish_setup' => 'Aller au tableau de bord', 'finish_setup' => 'Aller au tableau de bord',
'allow_tracking' => 'Allow anonymous usage tracking?',
]; ];

View File

@@ -61,3 +61,14 @@ App::missing(function ($exception) {
App::down(function () { App::down(function () {
return Response::make("Be right back!", 503); return Response::make("Be right back!", 503);
}); });
/*
|--------------------------------------------------------------------------
| Analytics
|--------------------------------------------------------------------------
|
| We handle all Segment.com tracking here. The function call will only do
| something if tracking is enabled.
|
*/
segment_identify();

View File

@@ -108,6 +108,15 @@
</div> </div>
</div> </div>
</div> </div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label>{{ trans('setup.allow_tracking') }}</label>
<input type="hidden" value="0" name="app_track">
<input type="checkbox" value="1" name="app_track" class="form-control" {{ Setting::get('app_track') ? 'checked' : null }}>
</div>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-xs-12"> <div class="col-xs-12">
<div class="form-group"> <div class="form-group">

View File

@@ -78,6 +78,12 @@
{{ trans("setup.show_support") }} {{ trans("setup.show_support") }}
</label> </label>
</div> </div>
<div class="form-group">
<label>
<input type="checkbox" name="settings[app_track]" value="1" checked >
{{ trans("setup.allow_tracking") }}
</label>
</div>
<hr> <hr>
<div class="form-group text-center"> <div class="form-group text-center">
<span class="wizard-next btn btn-success" data-current-block="1" data-next-block="2" data-loading-text="<i class='icon ion-load-c'></i>"> <span class="wizard-next btn btn-success" data-current-block="1" data-next-block="2" data-loading-text="<i class='icon ion-load-c'></i>">

View File

@@ -14,6 +14,7 @@
"ext-mcrypt": "*", "ext-mcrypt": "*",
"ext-openssl": "*", "ext-openssl": "*",
"laravel/framework": "4.2.*", "laravel/framework": "4.2.*",
"cachethq/segment": "1.0.*@dev",
"dingo/api": "0.8.*", "dingo/api": "0.8.*",
"doctrine/dbal": "2.5.*", "doctrine/dbal": "2.5.*",
"graham-campbell/binput": "2.1.*", "graham-campbell/binput": "2.1.*",

106
composer.lock generated
View File

@@ -4,8 +4,63 @@
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"hash": "3752fec41d40201f38e46974caa27d62", "hash": "b32031bb1053f393308be4f68d1d0c94",
"packages": [ "packages": [
{
"name": "cachethq/segment",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/cachethq/Laravel-Segment.git",
"reference": "39121d7953cb91197f0474b9cf43ae198fca1e26"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/cachethq/Laravel-Segment/zipball/39121d7953cb91197f0474b9cf43ae198fca1e26",
"reference": "39121d7953cb91197f0474b9cf43ae198fca1e26",
"shasum": ""
},
"require": {
"illuminate/config": "~4.1",
"illuminate/support": "~4.1",
"php": ">=5.4.7",
"segmentio/analytics-php": "~1.1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"autoload": {
"psr-4": {
"CachetHQ\\Segment\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "James Brooks",
"email": "james@cachethq.io"
}
],
"description": "Segment.com wrapper written for Laravel 4",
"keywords": [
"CachetHQ",
"Laravel Segment",
"api",
"cachet",
"framework",
"laravel",
"segment",
"segment.com",
"segment.io"
],
"time": "2015-01-23 22:49:00"
},
{ {
"name": "classpreloader/classpreloader", "name": "classpreloader/classpreloader",
"version": "1.0.2", "version": "1.0.2",
@@ -2108,6 +2163,51 @@
], ],
"time": "2014-12-09 14:53:34" "time": "2014-12-09 14:53:34"
}, },
{
"name": "segmentio/analytics-php",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/segmentio/analytics-php.git",
"reference": "db24fa9a2e1110570c338fea7a6f46bbb7ef105c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/segmentio/analytics-php/zipball/db24fa9a2e1110570c338fea7a6f46bbb7ef105c",
"reference": "db24fa9a2e1110570c338fea7a6f46bbb7ef105c",
"shasum": ""
},
"require": {
"php": ">=5.3"
},
"require-dev": {
"phpunit/phpunit": "3.7.*"
},
"type": "library",
"autoload": {
"files": [
"lib/Segment.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Segment.io <friends@segment.io>",
"homepage": "https://segment.io/"
}
],
"description": "Segmentio Analytics PHP Library",
"homepage": "https://segment.io/libraries/php",
"keywords": [
"analytics",
"analytics.js",
"segmentio"
],
"time": "2015-01-07 07:11:38"
},
{ {
"name": "stack/builder", "name": "stack/builder",
"version": "v1.0.3", "version": "v1.0.3",
@@ -3997,7 +4097,9 @@
], ],
"aliases": [], "aliases": [],
"minimum-stability": "stable", "minimum-stability": "stable",
"stability-flags": [], "stability-flags": {
"cachethq/segment": 20
},
"prefer-stable": false, "prefer-stable": false,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {

View File

@@ -50,7 +50,13 @@ class OneClickDeployCommand extends Command
public function fire() public function fire()
{ {
if ($this->migrate) { if ($this->migrate) {
return $this->runMigrations(); $migrations = $this->runMigrations();
segment_track('Installation', [
'event' => 'Heroku Deployment',
]);
return $migrations;
} }
$this->info('Please run "php artisan migrate" to finish the installation.'); $this->info('Please run "php artisan migrate" to finish the installation.');

View File

@@ -109,6 +109,11 @@ class DashComponentController extends Controller
$component->update($_component); $component->update($_component);
if (! $component->isValid()) { if (! $component->isValid()) {
segment_track('Dashboard', [
'event' => 'Edit Component',
'success' => false,
]);
return Redirect::back()->withInput(Binput::all()) return Redirect::back()->withInput(Binput::all())
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -118,6 +123,11 @@ class DashComponentController extends Controller
->with('errors', $component->getErrors()); ->with('errors', $component->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Edit Component',
'success' => true,
]);
// The component was added successfully, so now let's deal with the tags. // The component was added successfully, so now let's deal with the tags.
$tags = preg_split('/ ?, ?/', $tags); $tags = preg_split('/ ?, ?/', $tags);
@@ -168,6 +178,11 @@ class DashComponentController extends Controller
$component = Component::create($_component); $component = Component::create($_component);
if (! $component->isValid()) { if (! $component->isValid()) {
segment_track('Dashboard', [
'event' => 'Created Component',
'success' => false,
]);
return Redirect::back()->withInput(Binput::all()) return Redirect::back()->withInput(Binput::all())
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -177,6 +192,11 @@ class DashComponentController extends Controller
->with('errors', $component->getErrors()); ->with('errors', $component->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Created Component',
'success' => true,
]);
// The component was added successfully, so now let's deal with the tags. // The component was added successfully, so now let's deal with the tags.
$tags = preg_split('/ ?, ?/', $tags); $tags = preg_split('/ ?, ?/', $tags);
@@ -207,6 +227,10 @@ class DashComponentController extends Controller
*/ */
public function deleteComponentAction(Component $component) public function deleteComponentAction(Component $component)
{ {
segment_track('Dashboard', [
'event' => 'Deleted Component',
]);
$component->delete(); $component->delete();
return Redirect::back(); return Redirect::back();
@@ -221,6 +245,10 @@ class DashComponentController extends Controller
*/ */
public function deleteComponentGroupAction(ComponentGroup $group) public function deleteComponentGroupAction(ComponentGroup $group)
{ {
segment_track('Dashboard', [
'event' => 'Deleted Component Group',
]);
$group->delete(); $group->delete();
return Redirect::back(); return Redirect::back();
@@ -248,6 +276,11 @@ class DashComponentController extends Controller
$group = ComponentGroup::create(Binput::get('group')); $group = ComponentGroup::create(Binput::get('group'));
if (! $group->isValid()) { if (! $group->isValid()) {
segment_track('Dashboard', [
'event' => 'Created Component Group',
'success' => false,
]);
return Redirect::back()->withInput(Binput::all()) return Redirect::back()->withInput(Binput::all())
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -257,6 +290,11 @@ class DashComponentController extends Controller
->with('errors', $group->getErrors()); ->with('errors', $group->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Created Component Group',
'success' => true,
]);
$successMsg = sprintf( $successMsg = sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
trans('dashboard.notifications.awesome'), trans('dashboard.notifications.awesome'),

View File

@@ -66,6 +66,11 @@ class DashIncidentController extends Controller
$incident = Incident::create($incidentData); $incident = Incident::create($incidentData);
if (! $incident->isValid()) { if (! $incident->isValid()) {
segment_track('Dashboard', [
'event' => 'Created Incident',
'success' => false,
]);
return Redirect::back()->withInput(Binput::all()) return Redirect::back()->withInput(Binput::all())
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -82,6 +87,11 @@ class DashIncidentController extends Controller
]); ]);
} }
segment_track('Dashboard', [
'event' => 'Created Incident',
'success' => true,
]);
$successMsg = sprintf( $successMsg = sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
trans('dashboard.notifications.awesome'), trans('dashboard.notifications.awesome'),
@@ -127,6 +137,10 @@ class DashIncidentController extends Controller
*/ */
public function deleteTemplateAction(IncidentTemplate $template) public function deleteTemplateAction(IncidentTemplate $template)
{ {
segment_track('Dashboard', [
'event' => 'Deleted Incident Template',
]);
$template->delete(); $template->delete();
return Redirect::back(); return Redirect::back();
@@ -143,6 +157,11 @@ class DashIncidentController extends Controller
$template = IncidentTemplate::create($_template); $template = IncidentTemplate::create($_template);
if (! $template->isValid()) { if (! $template->isValid()) {
segment_track('Dashboard', [
'event' => 'Created Incident Template',
'success' => false,
]);
return Redirect::back()->withInput(Binput::all()) return Redirect::back()->withInput(Binput::all())
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -152,6 +171,11 @@ class DashIncidentController extends Controller
->with('errors', $template->getErrors()); ->with('errors', $template->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Created Incident Template',
'success' => true,
]);
$successMsg = sprintf( $successMsg = sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
trans('dashboard.notifications.awesome'), trans('dashboard.notifications.awesome'),
@@ -170,6 +194,10 @@ class DashIncidentController extends Controller
*/ */
public function deleteIncidentAction(Incident $incident) public function deleteIncidentAction(Incident $incident)
{ {
segment_track('Dashboard', [
'event' => 'Deleted Incident',
]);
$incident->delete(); $incident->delete();
return Redirect::back(); return Redirect::back();
@@ -204,6 +232,11 @@ class DashIncidentController extends Controller
$incident->update($_incident); $incident->update($_incident);
if (! $incident->isValid()) { if (! $incident->isValid()) {
segment_track('Dashboard', [
'event' => 'Edited Incident',
'success' => false,
]);
return Redirect::back()->withInput(Binput::all()) return Redirect::back()->withInput(Binput::all())
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -213,6 +246,11 @@ class DashIncidentController extends Controller
->with('errors', $incident->getErrors()); ->with('errors', $incident->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Edited Incident',
'success' => true,
]);
$successMsg = sprintf( $successMsg = sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
trans('dashboard.notifications.awesome'), trans('dashboard.notifications.awesome'),
@@ -231,6 +269,10 @@ class DashIncidentController extends Controller
*/ */
public function editTemplateAction(IncidentTemplate $template) public function editTemplateAction(IncidentTemplate $template)
{ {
segment_track('Dashboard', [
'event' => 'Edited Incident Template',
]);
$template->update(Binput::get('template')); $template->update(Binput::get('template'));
return Redirect::back()->with('updatedTemplate', $template); return Redirect::back()->with('updatedTemplate', $template);

View File

@@ -60,6 +60,11 @@ class DashTeamController extends Controller
$user = User::create(Binput::all()); $user = User::create(Binput::all());
if (! $user->isValid()) { if (! $user->isValid()) {
segment_track('Dashboard', [
'event' => 'Added User',
'success' => false,
]);
return Redirect::back()->withInput(Binput::except('password')) return Redirect::back()->withInput(Binput::except('password'))
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -69,6 +74,11 @@ class DashTeamController extends Controller
->with('errors', $user->getErrors()); ->with('errors', $user->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Added User',
'success' => true,
]);
$successMsg = sprintf( $successMsg = sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
trans('dashboard.notifications.awesome'), trans('dashboard.notifications.awesome'),
@@ -98,6 +108,11 @@ class DashTeamController extends Controller
$user->update($items); $user->update($items);
if (! $user->isValid()) { if (! $user->isValid()) {
segment_track('Dashboard', [
'event' => 'Updated User',
'success' => false,
]);
return Redirect::back()->withInput(Binput::except('password')) return Redirect::back()->withInput(Binput::except('password'))
->with('title', sprintf( ->with('title', sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
@@ -107,6 +122,11 @@ class DashTeamController extends Controller
->with('errors', $user->getErrors()); ->with('errors', $user->getErrors());
} }
segment_track('Dashboard', [
'event' => 'Updated User',
'success' => true,
]);
$successMsg = sprintf( $successMsg = sprintf(
'<strong>%s</strong> %s', '<strong>%s</strong> %s',
trans('dashboard.notifications.awesome'), trans('dashboard.notifications.awesome'),

View File

@@ -39,8 +39,18 @@ class DashUserController extends Controller
// Let's enable/disable auth // Let's enable/disable auth
if ($enable2FA && ! Auth::user()->hasTwoFactor) { if ($enable2FA && ! Auth::user()->hasTwoFactor) {
$items['google_2fa_secret'] = Google2FA::generateSecretKey(); $items['google_2fa_secret'] = Google2FA::generateSecretKey();
segment_track('User Management', [
'event' => 'enabled_two_factor',
'value' => true,
]);
} elseif (! $enable2FA) { } elseif (! $enable2FA) {
$items['google_2fa_secret'] = ''; $items['google_2fa_secret'] = '';
segment_track('User Management', [
'event' => 'enabled_two_factor',
'value' => false,
]);
} }
if (trim($passwordChange) === '') { if (trim($passwordChange) === '') {
@@ -76,6 +86,10 @@ class DashUserController extends Controller
*/ */
public function regenerateApiKey(User $user) public function regenerateApiKey(User $user)
{ {
segment_track('User Management', [
'event' => 'regenrated_api_token'
]);
$user->api_key = User::generateApiKey(); $user->api_key = User::generateApiKey();
$user->save(); $user->save();

View File

@@ -22,6 +22,10 @@ class HomeController extends Controller
*/ */
public function showIndex() public function showIndex()
{ {
segment_track('Status Page', [
'event' => 'Landed',
]);
$components = Component::orderBy('order')->orderBy('created_at')->get(); $components = Component::orderBy('order')->orderBy('created_at')->get();
$allIncidents = []; $allIncidents = [];
@@ -38,6 +42,21 @@ class HomeController extends Controller
try { try {
// If date provided is valid // If date provided is valid
$oldDate = Date::createFromFormat('Y-m-d', Binput::get('start_date')); $oldDate = Date::createFromFormat('Y-m-d', Binput::get('start_date'));
segment_track('Status Page', [
'start_date' => $oldDate->format('Y-m-d'),
]);
if (Setting::get('app_tracking')) {
Segment::track([
'userId' => Config::get('app.key'),
'event' => 'Home Page',
'properties' => [
'start_date' => $oldDate,
],
]);
}
// If trying to get a future date fallback to today // If trying to get a future date fallback to today
if ($today->gt($oldDate)) { if ($today->gt($oldDate)) {
$startDate = $oldDate; $startDate = $oldDate;

View File

@@ -47,6 +47,10 @@ class SetupController extends Controller
{ {
$postData = Binput::all(); $postData = Binput::all();
segment_track('Setup', [
'step' => '1',
]);
$v = Validator::make($postData, [ $v = Validator::make($postData, [
'settings.app_name' => 'required', 'settings.app_name' => 'required',
'settings.app_domain' => 'required', 'settings.app_domain' => 'required',
@@ -72,6 +76,10 @@ class SetupController extends Controller
{ {
$postData = Binput::all(); $postData = Binput::all();
segment_track('Setup', [
'step' => '2',
]);
$v = Validator::make($postData, [ $v = Validator::make($postData, [
'settings.app_name' => 'required', 'settings.app_name' => 'required',
'settings.app_domain' => 'required', 'settings.app_domain' => 'required',

View File

@@ -25,6 +25,10 @@ class LoadConfigServiceProvider extends ServiceProvider
// Don't throw any errors, we may not be setup yet. // Don't throw any errors, we may not be setup yet.
} }
// Set the Segment.com settings.
$segmentRepository = $this->app->make('CachetHQ\Cachet\Segment\RepositoryInterface');
$this->app->config->set('cachethq/segment::write_key', $segmentRepository->fetch());
// Override default app values. // Override default app values.
$this->app->config->set('app.url', $appDomain ?: $this->app->config->get('app.url')); $this->app->config->set('app.url', $appDomain ?: $this->app->config->get('app.url'));
$this->app->config->set('app.locale', $appLocale ?: $this->app->config->get('app.locale')); $this->app->config->set('app.locale', $appLocale ?: $this->app->config->get('app.locale'));

View File

@@ -0,0 +1,37 @@
<?php
namespace CachetHQ\Cachet\Providers;
use CachetHQ\Cachet\Segment\CacheRepository;
use CachetHQ\Cachet\Segment\HttpRepository;
use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
class SegmentApiServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('CachetHQ\Cachet\Segment\RepositoryInterface', function () {
$url = 'https://gist.githubusercontent.com/jbrooksuk/5de24bc1cf90fb1a3d57/raw/cachet.json';
$guzzleClient = new Client();
$client = new HttpRepository($guzzleClient, $url);
return new CacheRepository($client);
});
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace CachetHQ\Cachet\Segment;
use CachetHQ\Cachet\Facades\Setting;
use CachetHQ\Cachet\Models\Setting as SettingModel;
use Carbon\Carbon;
class CacheRepository implements RepositoryInterface
{
/**
* @var \CachetHQ\Cachet\Segment\HttpRepository
*/
protected $repository;
/**
* Instantiates a new instance of the Cache Repository.
*
* @param \CachetHQ\Cachet\Segment\HttpRepository $repository
*/
public function __construct(RepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* Determines whether to use the segment_write_key setting or to fetch a new.
*
* @return string
*/
public function fetch()
{
// Firstly, does the setting exist?
if (false === ($writeKey = Setting::get('segment_write_key'))) {
// No, let's go fetch it.
$writeKey = $this->repository->fetch();
Setting::set('segment_write_key', $writeKey);
} else {
// It does, but how old is it?
$setting = SettingModel::where('name', 'segment_write_key')->first();
// It's older than an hour, let's refresh
if ($setting->updated_at->lt(Carbon::now()->subHour())) {
$writeKey = $this->repository->fetch();
// Update the setting. This is done manual to make sure updated_at is overwritten.
$setting->value = $writeKey;
$setting->updated_at = Carbon::now();
$setting->save();
}
}
return $writeKey;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace CachetHQ\Cachet\Segment;
use GuzzleHttp\ClientInterface;
class HttpRepository implements RepositoryInterface
{
/**
* @var \Guzzle\GuzzleClient
*/
protected $client;
/**
* @var string
*/
protected $url;
/**
* Instantiates a new instance of the SegmentApi class.
*
* @param \Guzzle\GuzzleClient $client
* @param string $url
*/
public function __construct(ClientInterface $client, $url)
{
$this->client = $client;
$this->url = $url;
}
/**
* Fetches the segment_write_key from the given url.
*
* @return string
*/
public function fetch()
{
return $this->client->get($this->url)->json()['segment_write_key'];
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace CachetHQ\Cachet\Segment;
interface RepositoryInterface
{
/**
* Returns the segment_write_key.
*
* @return string
*/
public function fetch();
}

View File

@@ -1,5 +1,7 @@
<?php <?php
use CachetHQ\Cachet\Facades\Setting;
use CachetHQ\Segment\Facades\Segment;
use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Request;
@@ -78,3 +80,77 @@ if (!function_exists('set_active')) {
return empty($classes) ? '' : "class=\"{$class}\""; return empty($classes) ? '' : "class=\"{$class}\"";
} }
} }
if (!function_exists('segment_identify')) {
/**
* Identifies the user for Segment.com.
*
* @return bool
*/
function segment_identify()
{
if (Setting::get('app_track')) {
return Segment::identify([
'anonymousId' => Config::get('app.key'),
'context' => [
'locale' => Config::get('app.locale'),
'timezone' => Setting::get('app_timezone'),
],
]);
} else {
return false;
}
}
}
if (!function_exists('segment_track')) {
/**
* Tracks events in Segment.com.
*
* @param string $event
* @param array $properties
*
* @return bool
*/
function segment_track($event, array $properties)
{
if (Setting::get('app_track')) {
return Segment::track([
'anonymousId' => Config::get('app.key'),
'event' => $event,
'properties' => $properties,
'context' => [
'locale' => Config::get('app.locale'),
'timezone' => Setting::get('app_timezone'),
],
]);
} else {
return false;
}
}
}
if (!function_exists('segment_page')) {
/**
* Tracks pages in Segment.com.
*
* @param string $name
*
* @return bool
*/
function segment_page($page)
{
if (Setting::get('app_track')) {
return Segment::page([
'anonymousId' => Config::get('app.key'),
'page' => $page,
'context' => [
'locale' => Config::get('app.locale'),
'timezone' => Setting::get('app_timezone'),
],
]);
} else {
return false;
}
}
}