nhance/app/Controllers/GoogleDriveController.php

356 lines
14 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\ClientModel;
use App\Models\ClientPolicyModel;
use Google_Service_Drive_DriveFile;
use Kint;
class GoogleDriveController extends BaseController
{
protected $clientModel;
protected $clientPolicyModel;
protected $googleDrive;
protected $driveService;
protected $cache;
public function __construct()
{
$this->clientModel = new ClientModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->googleDrive = \Config\Services::myGoogleDrive();
$this->driveService = $this->googleDrive->getDriveService();
$this->cache = \Config\Services::cache(); // Load the cache service
}
public function listFiles()
{
// dd($this->getClientFolderIds(client_id : 18));
$file_path = WRITEPATH.'uploads/client_kyc_documents/nhance_bpf.pdf';
// dd($file_path);
// dd($this->uploadFiletoGdrive(client_id : 18,doc_type:'KYC',file_path:$file_path,file_name:"dummy.pdf"));
dd( $this->uploadFiletoGdrive(client_id: 12, doc_type: 'KYC', file_path: $file_path, file_name: "dummy.pdf"));
$session = \Config\Services::session();
$fileName = $request->getVar('filename');
$fileType = $request->getVar('filetype');
$userAccess = $session->get('userEmail');
$parentFolderID = '1M0GH3GbNUOYZLNeHXA5U7C_P2NSx7F7O';
$searchQuery = '';//"'your-folder-id' in parents"
try {
// $driveService = $this->googleDrive->getDriveService();
$searchQuery = "name contains 'test' and 'vitvelz@gmail.com' in readers";
// Query to list files
$response = $this->driveService->files->listFiles([
'q' => $searchQuery,
'supportsAllDrives' => true,
'includeItemsFromAllDrives' => true,
'fields' => 'nextPageToken, files(id, name, mimeType, size, createdTime, modifiedTime, owners, shared, permissions, webViewLink, thumbnailLink)',
'pageSize' => 20,
]);
$files = $response->getFiles();
if (empty($files)) {
echo "No files found.";
} else {
foreach ($files as $file) {
echo "File Name: " . $file->getName() . " | File ID: " . $file->getId() . "<br>";
}
}
} catch (\Exception $e) {
return $this->response->setStatusCode(500)->setBody($e->getMessage());
}
}
//by file id
public function downloadFile(string $fileId = '',string $fileName = '',string $mimeType = '',string $fileSize = '')
{
// dd($fileName);
try {
if($fileName == '' && $mimeType == '')
{
// Get file metadata
$file = $this->driveService->files->get($fileId, ['fields' => 'name, mimeType,size']);
$fileName = $file->getName();
$mimeType = $file->getMimeType();
$fileSize = $file->getSize();
}
// Download the file content from Google Drive
$response = $this->driveService->files->get($fileId, ['alt' => 'media']);
$fileContent = $response->getBody()->getContents();
// dd($fileContent);
$temp_file_name = WRITEPATH.'/tmp/'.date('YmdHis');
$this->cache->save('temp_gdrive_file', $temp_file_name, 300);
file_put_contents( $temp_file_name, $fileContent );
// Use CodeIgniter helper for downloading the file
return $this->response->download($temp_file_name, null)->setFileName($fileName);
} catch (\Exception $e) {
return $this->response->setStatusCode(500)->setBody($e->getMessage());
}
}
public function generateNewGoogleDriveAccessToken()
{
$this->driveService->generateNewToken();
}
public function getClientFolderIds(int $client_id = 0,int $client_policy_id = 0)
{
// Fetch client short name from the database
if($client_id)
{
//check folder ids in cahce,
$cacheKey = "client_gdrive_folderids_{$client_id}";
$folderIds = $this->cache->get($cacheKey);
// dd($folderIds);
if($folderIds !== NULL)//if available retrun from cache
{
return $folderIds;
}
//if not in cache then get it from grdrive
$client = $this->clientModel->find((int)$client_id);
$clientShortName = $client['short_name']; // Assuming short_name is the column for client's short name
}
else if($client_policy_id)
{
$cacheKey = "client_policy_gdrive_folderids_{$client_policy_id}";
$folderIds = $this->cache->get($cacheKey);
// dd($folderIds);
if($folderIds !== NULL)//if available retrun from cache
{
return $folderIds;
}
$client = $this->clientPolicyModel->select('c.short_name,pt.policy_type,client_policy.policy_no')
->join('clients c','client_policy.client_id = c.id')
->join('policy_type pt','client_policy.policy_type_id = pt.id')
->where('client_policy.id',$client_policy_id)
->get()->getResultarray();
// dd($client);
$clientShortName = $client[0]['short_name'];
$policyFolderName = $client[0]['policy_type'].'-'.$client[0]['policy_no'];
}
else
{
return [];
}
// dd($policyFolderName);
// Define parent folder ID where client folders are stored
$parentFolderId = getenv('GDRIVE_ROOT_FOLDER_ID');; // Replace with your specific folder ID
// Check if the client folder exists in GDrive, if not create one
$clientFolderId = $this->checkOrCreateFolder($clientShortName, $parentFolderId);
// Check or create KYC_DOCS folder inside the client folder
$kycFolderId = $this->checkOrCreateFolder('KYC_DOCS', $clientFolderId);
// Check or create POLICY_DOCS folder inside the client folder
$policyFolderId = $this->checkOrCreateFolder('POLICY_DOCS', $clientFolderId);
if($client_policy_id && (isset($policyFolderName)))
{
$clientPolicyFolderId = $this->checkOrCreateFolder($policyFolderName, $policyFolderId);
$clientPolicyUploadFolderId = $this->checkOrCreateFolder('UPLOADS', $clientPolicyFolderId);
}
// Return folder IDs in the specified format
$folderIds = [
'client_folder_id' => $clientFolderId, // example HCL,TCS
'kyc_doc_folder_id' => $kycFolderId, // KYC_DOCS inside HCL,TCS
'policy_doc_folder_id' => $policyFolderId, //POLICY_DOCS inside HCL,TCS
'client_policy_doc_folder_id' => isset($clientPolicyFolderId) ? $clientPolicyFolderId : null, //GMC-POLICY_NO inside POLICY_DOCS folder
'client_policy_uoload_doc_folder_id' => isset($clientPolicyUploadFolderId) ? $clientPolicyUploadFolderId : null, //UPLOADS folder in side GMC-POLICY_NO folder
];
// Save the folder IDs in cache for future requests
$this->cache->save($cacheKey, $folderIds, 604800); // Cache for 7 Days (3600 seconds * 24 * 7 )
return $folderIds;
}
// Method to check if a folder exists or create one if it doesn't
public function checkOrCreateFolder($folderName, $parentFolderId)
{
// Step 1: Check if the folder exists
$folderId = $this->getFolderId($folderName, $parentFolderId);
if ($folderId === null) {
// Step 2: If folder does not exist, create it
$folderId = $this->createFolder($folderName, $parentFolderId);
}
// Step 3: Return the folder ID
return $folderId;
}
// Method to get the folder ID by searching in Google Drive
private function getFolderId($folderName, $parentFolderId)
{
$query = "name = '$folderName' and mimeType = 'application/vnd.google-apps.folder' and '$parentFolderId' in parents and trashed = false";
$response = $this->driveService->files->listFiles([
'q' => $query,
'spaces' => 'drive',
'fields' => 'files(id, name)',
'pageSize' => 1,
]);
if (count($response->files) > 0) {
return $response->files[0]->id; // Return folder ID if found
}
return null; // Return null if folder doesn't exist
}
// Method to create a folder in Google Drive
private function createFolder($folderName, $parentFolderId)
{
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => $folderName,
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => [$parentFolderId]
]);
$folder = $this->driveService->files->create($fileMetadata, [
'fields' => 'id',
]);
return $folder->id; // Return the newly created folder's ID
}
// public function uploadFiletoGdrive(int $client_id = 0,int $client_policy_id = 0,string $doc_type,string
// $file_path,string $file_name)
public function uploadFiletoGdrive(int $client_id = 0, int $client_policy_id = 0, string $doc_type = '', string $file_path = '', string $file_name = '')
{
$gdriveFolderIds = $this->getClientFolderIds(client_id: $client_id,client_policy_id: $client_policy_id);
// Kint::dump($gdriveFolderIds);//die();
$parentFolderId = '';
if($client_id && $doc_type == 'KYC')
{
$parentFolderId = $gdriveFolderIds['kyc_doc_folder_id'];
}
else if($client_policy_id && $doc_type == 'POLICY')
{
$parentFolderId = $gdriveFolderIds['client_policy_doc_folder_id'];
}
else if($client_policy_id && $doc_type == 'UPLOADS')
{
$parentFolderId = $gdriveFolderIds['client_policy_uoload_doc_folder_id'];
}
if($parentFolderId == '')
{
return null;
}
// dd($parentFolderId);
$file = new \Google_Service_Drive_DriveFile([
'name' => $file_name,
'parents' => [$parentFolderId] // Specify the folder ID here
]);
$file_blob_data = file_get_contents($file_path);
$createdFile = $this->driveService->files->create($file, [
'data' => $file_blob_data,
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart',
'fields' => 'id' // Specify fields to return
]);
if($createdFile->id && $doc_type !== 'UPLOADS')
{
unlink($file_path);
}
return $createdFile->id;
}
public function downloadGdriveFile()
{
$client_id = $this->request->getGet('client_id');
$client_policy_id = $this->request->getGet('client_policy_id');
$file_type = $this->request->getGet('file_type');
$file_name = $this->request->getGet('file_name');
if(!is_numeric($client_policy_id))
$client_policy_id = 0;
else
$client_id = 0;
$gdriveFolderIds = $this->getClientFolderIds(client_id: $client_id,client_policy_id: $client_policy_id);
// dd($gdriveFolderIds);
$parentFolderId = '';
if($file_type == 'kyc')
{
$parentFolderId = $gdriveFolderIds['kyc_doc_folder_id'];
}
else if($file_type == 'policy')
{
$parentFolderId = $gdriveFolderIds['client_policy_doc_folder_id'];
}
else if($file_type == 'uploads')
{
$parentFolderId = $gdriveFolderIds['client_policy_uoload_doc_folder_id'];
}
if($parentFolderId == '')
{
return $this->response->setStatusCode(500)
->setHeader('Content-Type', 'text/html')
->setBody('<script>alert("File not found");</script>');
}
return $this->searchGdriveFileByName(parentFolderID: $parentFolderId, fileName: $file_name);
}
//search files in gdrive by parent folder id and name of the file
public function searchGdriveFileByName(string $parentFolderID,string $fileName)
{
//check exisitng temp file from cache and delete it
if($this->cache->get('temp_gdrive_file') && is_file($this->cache->get('temp_gdrive_file')))
{
unlink($this->cache->get('temp_gdrive_file'));
}
try {
$searchQuery = "'$parentFolderID' in parents and (name contains '$fileName')";
// Query to list files
$response = $this->driveService->files->listFiles([
'q' => $searchQuery,
'supportsAllDrives' => true,
'includeItemsFromAllDrives' => true,
'fields' => 'nextPageToken, files(id, name, mimeType, size)',
'pageSize' => 1,
]);
$files = $response->getFiles();
if (empty($files)) {
return $this->response->setStatusCode(500)
->setHeader('Content-Type', 'text/html')
->setBody('<script>alert("File not found");window.close();</script>');
}
else
{
//echo "File Name: " . $files[0]->getName() . " | File ID: " . $file[0]->getId() . "<br>";
// echo($files[0]->getId());
// echo 'working';
return $this->downloadFile(fileId:$files[0]->getId(),fileName:$files[0]->getName(),mimeType:$files[0]->getMimeType(),fileSize:$files[0]->getSize());
}
} catch (\Exception $e) {
return $this->response->setStatusCode(500)->setBody($e->getMessage());
}
}
}