71 lines
2.0 KiB
PHP
71 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Models\PackageName;
|
|
use Illuminate\Bus\Queueable;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Bus\Dispatchable;
|
|
use Illuminate\Queue\InteractsWithQueue;
|
|
use Illuminate\Queue\SerializesModels;
|
|
use Kreait\Firebase\Factory;
|
|
use Kreait\Firebase\Messaging\CloudMessage;
|
|
|
|
class SendPushToPackageJob implements ShouldQueue
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
|
public function __construct(
|
|
public PackageName $packageName,
|
|
public string $title,
|
|
public string $description = '',
|
|
public array $data = []
|
|
) {}
|
|
|
|
public function handle(): void
|
|
{
|
|
if (!$firebaseFile = $this->getFirebaseJsonPath()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$messaging = (new Factory)
|
|
->withServiceAccount($firebaseFile)
|
|
->createMessaging();
|
|
|
|
$users = $this->packageName->users()
|
|
->whereNotNull('user_package_name.fcm_token')
|
|
->get();
|
|
|
|
foreach ($users as $user) {
|
|
$fcmToken = $user->packageNames()
|
|
->where('package_names.id', $this->packageName->id)
|
|
->first()
|
|
->pivot
|
|
->fcm_token;
|
|
|
|
if (!$fcmToken) {
|
|
continue;
|
|
}
|
|
|
|
$message = CloudMessage::withTarget('token', $fcmToken)
|
|
->withNotification([
|
|
'title' => $this->title,
|
|
'body' => $this->description,
|
|
])
|
|
->withData($this->data);
|
|
|
|
$messaging->send($message);
|
|
}
|
|
|
|
} catch (\Throwable $e) {
|
|
\Log::error('SendPushToPackageJob failed: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
private function getFirebaseJsonPath(): ?string
|
|
{
|
|
$media = $this->packageName->getFirstMedia('firebase_json');
|
|
return $media?->getPath();
|
|
}
|
|
} |