Files
verifikator/app/Services/GoogleDriveService.php

103 lines
3.3 KiB
PHP

<?php
namespace App\Services;
use Carbon\Carbon;
use Google\Client;
use Google\Service\Drive;
use Google\Service\Drive\DriveFile;
use Illuminate\Support\Facades\Log;
use Throwable;
class GoogleDriveService
{
private string $credentialsPath;
private string $rootFolderId;
public function __construct()
{
$this->credentialsPath = (string) config('services.google_drive.credentials_path');
$this->rootFolderId = (string) config('services.google_drive.folder_id');
}
public function uploadPdf(string $content, string $nip, string $namaPegawai, string $tanggal, string $namaKategori, ?string $namaFile = null): string|false
{
if (! $this->credentialsPath || ! file_exists($this->credentialsPath) || ! $this->rootFolderId) {
Log::error('GoogleDriveService: belum dikonfigurasi, upload dilewati.');
return false;
}
try {
$client = new Client;
$client->setAuthConfig($this->credentialsPath);
$client->addScope(Drive::DRIVE);
$service = new Drive($client);
$pengajuanPresensiFolderId = $this->findOrCreateFolder($service, 'Pengajuan Presensi', $this->rootFolderId);
$pegawaiFolderId = $this->findOrCreateFolder($service, $this->sanitize("$nip - $namaPegawai"), $pengajuanPresensiFolderId);
$bulanFolderId = $this->findOrCreateFolder($service, Carbon::parse($tanggal)->translatedFormat('F Y'), $pegawaiFolderId);
$fileName = $namaFile ?? Carbon::now()->format('YmdHis').'_'.$nip.'_'.$this->sanitize($namaKategori).'.pdf';
$fileMetadata = new DriveFile([
'name' => $fileName,
'parents' => [$bulanFolderId],
]);
$uploaded = $service->files->create($fileMetadata, [
'data' => $content,
'mimeType' => 'application/pdf',
'uploadType' => 'multipart',
'fields' => 'id, webViewLink',
'supportsAllDrives' => true,
]);
return $uploaded->getWebViewLink() ?: $uploaded->getId();
} catch (Throwable $th) {
Log::error('GoogleDriveService uploadPdf : '.$th->getMessage());
return false;
}
}
private function findOrCreateFolder(Drive $service, string $name, string $parentId): string
{
$escapedName = str_replace("'", "\\'", $name);
$result = $service->files->listFiles([
'q' => "name='$escapedName' and '$parentId' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false",
'fields' => 'files(id)',
'supportsAllDrives' => true,
'includeItemsFromAllDrives' => true,
'corpora' => 'allDrives',
]);
$existing = $result->getFiles();
if (count($existing) > 0) {
return $existing[0]->getId();
}
$folder = new DriveFile([
'name' => $name,
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => [$parentId],
]);
$created = $service->files->create($folder, [
'fields' => 'id',
'supportsAllDrives' => true,
]);
return $created->getId();
}
private function sanitize(string $value): string
{
return trim(str_replace(['/', '\\'], '-', $value));
}
}