phase 5
This commit is contained in:
@@ -2,20 +2,22 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\AnalyticsSession;
|
||||
use App\Models\Event;
|
||||
use App\Models\PageView;
|
||||
use App\Models\Visitor;
|
||||
use App\Jobs\ProcessTrackingPayload;
|
||||
use App\Models\Website;
|
||||
use App\Services\GoalEvaluationService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Jaybizzle\CrawlerDetect\CrawlerDetect;
|
||||
|
||||
class CollectController extends Controller
|
||||
{
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
if ($this->isBot($request)) {
|
||||
return response()->json(['ok' => false, 'reason' => 'bot'], 200);
|
||||
}
|
||||
|
||||
$payload = $request->validate([
|
||||
'tid' => 'required|string',
|
||||
'vid' => 'required|string|max:64',
|
||||
@@ -55,117 +57,81 @@ class CollectController extends Controller
|
||||
'is_new_session' => 'nullable|boolean',
|
||||
]);
|
||||
|
||||
$website = Website::where('tracking_id', $payload['tid'])
|
||||
->where('is_active', true)
|
||||
->first();
|
||||
|
||||
if (! $website) {
|
||||
return response()->json(['ok' => false], 404);
|
||||
if (! $this->isDomainValid($payload)) {
|
||||
return response()->json(['ok' => false, 'reason' => 'domain_mismatch'], 400);
|
||||
}
|
||||
|
||||
$now = Carbon::now();
|
||||
|
||||
$visitor = Visitor::updateOrCreate(
|
||||
[
|
||||
'website_id' => $website->id,
|
||||
'uid' => $payload['vid'],
|
||||
],
|
||||
[
|
||||
'last_seen_at' => $now,
|
||||
'first_seen_at' => $now,
|
||||
'device_type' => $payload['device'] ?? null,
|
||||
'browser' => $payload['browser'] ?? null,
|
||||
'browser_version' => $payload['browser_version'] ?? null,
|
||||
'os' => $payload['os'] ?? null,
|
||||
'os_version' => $payload['os_version'] ?? null,
|
||||
'screen_resolution' => $payload['sr'] ?? null,
|
||||
'language' => $payload['lang'] ?? null,
|
||||
],
|
||||
);
|
||||
|
||||
if ($visitor->wasRecentlyCreated) {
|
||||
$visitor->update(['first_seen_at' => $now]);
|
||||
}
|
||||
|
||||
$session = AnalyticsSession::firstOrCreate(
|
||||
['uid' => $payload['sid']],
|
||||
[
|
||||
'website_id' => $website->id,
|
||||
'visitor_id' => $visitor->id,
|
||||
'started_at' => $now,
|
||||
'entry_page' => $payload['path'] ?? $payload['url'] ?? null,
|
||||
'ip_address' => $request->ip(),
|
||||
'referrer_url' => $payload['referrer'] ?? null,
|
||||
'referrer_domain' => $payload['ref_domain'] ?? null,
|
||||
'utm_source' => $payload['utm_source'] ?? null,
|
||||
'utm_medium' => $payload['utm_medium'] ?? null,
|
||||
'utm_campaign' => $payload['utm_campaign'] ?? null,
|
||||
'utm_term' => $payload['utm_term'] ?? null,
|
||||
'utm_content' => $payload['utm_content'] ?? null,
|
||||
],
|
||||
);
|
||||
|
||||
if ($payload['type'] === 'pageview') {
|
||||
$this->recordPageView($website, $visitor, $session, $payload, $now);
|
||||
}
|
||||
|
||||
if ($payload['type'] === 'event') {
|
||||
$this->recordEvent($website, $visitor, $session, $payload, $now);
|
||||
}
|
||||
|
||||
$session->update([
|
||||
'ended_at' => $now,
|
||||
'duration' => $now->diffInSeconds($session->started_at),
|
||||
'exit_page' => $payload['path'] ?? $payload['url'] ?? $session->exit_page,
|
||||
'pages_count' => $session->pageViews()->count(),
|
||||
'is_bounce' => $session->pageViews()->count() <= 1,
|
||||
]);
|
||||
|
||||
$session->refresh();
|
||||
|
||||
app(GoalEvaluationService::class)->evaluate($website, $visitor, $session, $payload, $now);
|
||||
ProcessTrackingPayload::dispatch($payload, $request->ip(), Carbon::now());
|
||||
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
private function recordPageView(
|
||||
Website $website,
|
||||
Visitor $visitor,
|
||||
AnalyticsSession $session,
|
||||
array $payload,
|
||||
Carbon $now,
|
||||
): void {
|
||||
PageView::create([
|
||||
'website_id' => $website->id,
|
||||
'visitor_id' => $visitor->id,
|
||||
'analytics_session_id' => $session->id,
|
||||
'url' => $payload['url'] ?? '',
|
||||
'path' => $payload['path'] ?? '/',
|
||||
'title' => $payload['title'] ?? null,
|
||||
'referrer' => $payload['referrer'] ?? null,
|
||||
'time_on_page' => $payload['time_on_page'] ?? null,
|
||||
'viewed_at' => $now,
|
||||
]);
|
||||
/**
|
||||
* 1x1 transparent GIF tracking pixel for no-JS fallback.
|
||||
* Usage: <img src="/api/pixel?tid=TA-XXX" width="1" height="1" alt="">
|
||||
*/
|
||||
public function pixel(Request $request): Response
|
||||
{
|
||||
if ($this->isBot($request)) {
|
||||
return $this->gifResponse();
|
||||
}
|
||||
|
||||
$tid = $request->get('tid');
|
||||
|
||||
if ($tid) {
|
||||
$payload = [
|
||||
'tid' => $tid,
|
||||
'vid' => $request->get('vid', md5($request->ip() . $request->userAgent())),
|
||||
'sid' => $request->get('sid', md5($request->ip() . $request->userAgent() . date('Y-m-d-H'))),
|
||||
'type' => 'pageview',
|
||||
'url' => $request->get('url', $request->header('Referer')),
|
||||
'path' => $request->get('path', parse_url($request->header('Referer', '/'), PHP_URL_PATH)),
|
||||
'referrer' => $request->header('Referer'),
|
||||
];
|
||||
|
||||
ProcessTrackingPayload::dispatch($payload, $request->ip(), Carbon::now());
|
||||
}
|
||||
|
||||
return $this->gifResponse();
|
||||
}
|
||||
|
||||
private function recordEvent(
|
||||
Website $website,
|
||||
Visitor $visitor,
|
||||
AnalyticsSession $session,
|
||||
array $payload,
|
||||
Carbon $now,
|
||||
): void {
|
||||
Event::create([
|
||||
'website_id' => $website->id,
|
||||
'visitor_id' => $visitor->id,
|
||||
'analytics_session_id' => $session->id,
|
||||
'name' => $payload['event_name'] ?? 'unknown',
|
||||
'category' => $payload['event_category'] ?? null,
|
||||
'action' => $payload['event_action'] ?? null,
|
||||
'label' => $payload['event_label'] ?? null,
|
||||
'value' => $payload['event_value'] ?? null,
|
||||
'properties' => $payload['event_properties'] ?? null,
|
||||
'occurred_at' => $now,
|
||||
private function isBot(Request $request): bool
|
||||
{
|
||||
return (new CrawlerDetect)->isCrawler($request->userAgent());
|
||||
}
|
||||
|
||||
private function isDomainValid(array $payload): bool
|
||||
{
|
||||
$url = $payload['url'] ?? null;
|
||||
if (! $url) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$host = parse_url($url, PHP_URL_HOST);
|
||||
if (! $host) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$website = Website::where('tracking_id', $payload['tid'])->first();
|
||||
if (! $website) {
|
||||
return true; // let the job handle the 404
|
||||
}
|
||||
|
||||
$domain = $website->domain;
|
||||
|
||||
// Allow exact match or subdomain match (e.g. www.example.com matches example.com)
|
||||
return $host === $domain || str_ends_with($host, '.' . $domain);
|
||||
}
|
||||
|
||||
private function gifResponse(): Response
|
||||
{
|
||||
// 1x1 transparent GIF
|
||||
$gif = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
|
||||
|
||||
return response($gif, 200, [
|
||||
'Content-Type' => 'image/gif',
|
||||
'Content-Length' => strlen($gif),
|
||||
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CollectCors
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if ($request->isMethod('OPTIONS')) {
|
||||
return response('', 204, $this->corsHeaders($request));
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
foreach ($this->corsHeaders($request) as $key => $value) {
|
||||
$response->headers->set($key, $value);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function corsHeaders(Request $request): array
|
||||
{
|
||||
return [
|
||||
'Access-Control-Allow-Origin' => '*',
|
||||
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers' => 'Content-Type, X-Requested-With',
|
||||
'Access-Control-Max-Age' => '86400',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\AnalyticsSession;
|
||||
use App\Models\Event;
|
||||
use App\Models\PageView;
|
||||
use App\Models\Visitor;
|
||||
use App\Models\Website;
|
||||
use App\Services\GoalEvaluationService;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Stevebauman\Location\Facades\Location;
|
||||
|
||||
class ProcessTrackingPayload implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
public function __construct(
|
||||
private readonly array $payload,
|
||||
private readonly string $ip,
|
||||
private readonly Carbon $receivedAt,
|
||||
) {}
|
||||
|
||||
public function handle(GoalEvaluationService $goalService): void
|
||||
{
|
||||
$website = Website::where('tracking_id', $this->payload['tid'])
|
||||
->where('is_active', true)
|
||||
->first();
|
||||
|
||||
if (! $website) {
|
||||
return;
|
||||
}
|
||||
|
||||
$now = $this->receivedAt;
|
||||
|
||||
$visitor = Visitor::updateOrCreate(
|
||||
[
|
||||
'website_id' => $website->id,
|
||||
'uid' => $this->payload['vid'],
|
||||
],
|
||||
[
|
||||
'last_seen_at' => $now,
|
||||
'first_seen_at' => $now,
|
||||
'device_type' => $this->payload['device'] ?? null,
|
||||
'browser' => $this->payload['browser'] ?? null,
|
||||
'browser_version' => $this->payload['browser_version'] ?? null,
|
||||
'os' => $this->payload['os'] ?? null,
|
||||
'os_version' => $this->payload['os_version'] ?? null,
|
||||
'screen_resolution' => $this->payload['sr'] ?? null,
|
||||
'language' => $this->payload['lang'] ?? null,
|
||||
],
|
||||
);
|
||||
|
||||
if ($visitor->wasRecentlyCreated) {
|
||||
$visitor->update(['first_seen_at' => $now]);
|
||||
$this->geolocate($visitor);
|
||||
}
|
||||
|
||||
$session = AnalyticsSession::firstOrCreate(
|
||||
['uid' => $this->payload['sid']],
|
||||
[
|
||||
'website_id' => $website->id,
|
||||
'visitor_id' => $visitor->id,
|
||||
'started_at' => $now,
|
||||
'entry_page' => $this->payload['path'] ?? $this->payload['url'] ?? null,
|
||||
'ip_address' => $this->ip,
|
||||
'referrer_url' => $this->payload['referrer'] ?? null,
|
||||
'referrer_domain' => $this->payload['ref_domain'] ?? null,
|
||||
'utm_source' => $this->payload['utm_source'] ?? null,
|
||||
'utm_medium' => $this->payload['utm_medium'] ?? null,
|
||||
'utm_campaign' => $this->payload['utm_campaign'] ?? null,
|
||||
'utm_term' => $this->payload['utm_term'] ?? null,
|
||||
'utm_content' => $this->payload['utm_content'] ?? null,
|
||||
],
|
||||
);
|
||||
|
||||
if ($this->payload['type'] === 'pageview') {
|
||||
PageView::create([
|
||||
'website_id' => $website->id,
|
||||
'visitor_id' => $visitor->id,
|
||||
'analytics_session_id' => $session->id,
|
||||
'url' => $this->payload['url'] ?? '',
|
||||
'path' => $this->payload['path'] ?? '/',
|
||||
'title' => $this->payload['title'] ?? null,
|
||||
'referrer' => $this->payload['referrer'] ?? null,
|
||||
'time_on_page' => $this->payload['time_on_page'] ?? null,
|
||||
'viewed_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($this->payload['type'] === 'event') {
|
||||
Event::create([
|
||||
'website_id' => $website->id,
|
||||
'visitor_id' => $visitor->id,
|
||||
'analytics_session_id' => $session->id,
|
||||
'name' => $this->payload['event_name'] ?? 'unknown',
|
||||
'category' => $this->payload['event_category'] ?? null,
|
||||
'action' => $this->payload['event_action'] ?? null,
|
||||
'label' => $this->payload['event_label'] ?? null,
|
||||
'value' => $this->payload['event_value'] ?? null,
|
||||
'properties' => $this->payload['event_properties'] ?? null,
|
||||
'occurred_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
$session->update([
|
||||
'ended_at' => $now,
|
||||
'duration' => $now->diffInSeconds($session->started_at),
|
||||
'exit_page' => $this->payload['path'] ?? $this->payload['url'] ?? $session->exit_page,
|
||||
'pages_count' => $session->pageViews()->count(),
|
||||
'is_bounce' => $session->pageViews()->count() <= 1,
|
||||
]);
|
||||
|
||||
$session->refresh();
|
||||
|
||||
$goalService->evaluate($website, $visitor, $session, $this->payload, $now);
|
||||
}
|
||||
|
||||
private function geolocate(Visitor $visitor): void
|
||||
{
|
||||
try {
|
||||
$position = Location::get($this->ip);
|
||||
|
||||
if ($position) {
|
||||
$visitor->update(array_filter([
|
||||
'country' => $position->countryCode ?? null,
|
||||
'region' => $position->regionName ?? null,
|
||||
'city' => $position->cityName ?? null,
|
||||
]));
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Geolocation is best-effort; never fail the job over it
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,22 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
RateLimiter::for('collect', function (Request $request) {
|
||||
return Limit::perMinute(120)->by($request->ip());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user