You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

159 lines
5.4 KiB

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using Google.Apis.Upload;
using System.Threading.Tasks;
using System.Threading;
public class GoogleDriveUtils
{
static string[] Scopes = { DriveService.Scope.Drive }; // or DriveService.Scope.Drive for full access
static string ApplicationName = "MyDriveUploader";
// static string GoogleRawFileUrl = "https://drive.google.com/uc?id=";
static string GoogleRawFileUrl = "https://drive.usercontent.google.com/download?id=";
public static DriveService service;
public static void setupService()
{
UserCredential credential;
using (var stream = new FileStream("./Material/client_secret_30989913678-hk8sipecu98lp5vdsk0ictf5gufmn33p.apps.googleusercontent.com.json", FileMode.Open, FileAccess.Read))
{
// credential = GoogleCredential.FromStream(stream)
// .CreateScoped(Scopes);
string credPath = "./Material/token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
public static string getFolder(DriveService service, string path, string parentFolderId)
{
Debug.Log("Getting/Creating folder path: " + path);
if (path.Length == 0) return parentFolderId;
List<string> folders = new List<string>(path.Split('/'));
string currentFolderId = parentFolderId;
foreach (string folder in folders)
{
var request = service.Files.List();
request.Q = $"mimeType='application/vnd.google-apps.folder' and name='{folder}' and '{currentFolderId}' in parents and trashed=false";
request.Fields = "files(id, name)";
request.SupportsAllDrives = true;
request.IncludeItemsFromAllDrives = true;
var result = request.Execute();
if (result.Files.Count > 0)
{
currentFolderId = result.Files[0].Id;
Debug.Log("Found folder: " + folder + " with ID: " + currentFolderId);
}
else
{
// Folder does not exist, create it
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = folder,
MimeType = "application/vnd.google-apps.folder",
Parents = new List<string> { currentFolderId }
};
var createRequest = service.Files.Create(fileMetadata);
createRequest.Fields = "id";
createRequest.SupportsAllDrives = true;
var file = createRequest.Execute();
currentFolderId = file.Id;
}
}
return currentFolderId;
}
public static IEnumerator UploadCoroutine(DriveService service, string _uploadFile, string folderId, string _fileId, string type, System.Action<string> onComplete)
{
Debug.Log("Uploading file to Google Drive: " + _uploadFile);
if (!System.IO.File.Exists(_uploadFile))
{
Debug.LogError("File does not exist: " + _uploadFile);
onComplete?.Invoke(null);
yield break;
}
Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = Path.GetFileName(_uploadFile),
Parents = new List<string> { folderId }
};
Debug.Log("Metadata prepared: " + fileMetadata.Name);
using (var stream = new FileStream(_uploadFile, FileMode.Open))
{
var request = service.Files.Create(fileMetadata, stream, "image/png");
request.Fields = "id, name";
request.SupportsAllDrives = true;
request.ProgressChanged += (progress) =>
{
Debug.Log($"Upload Progress: {progress.Status} - Bytes Sent: {progress.BytesSent} {progress.Exception?.Message}");
};
request.ResponseReceived += (file) =>
{
Debug.Log($"File uploaded successfully: {file.Name} (ID: {file.Id})");
};
var uploadTask = request.UploadAsync();
// Wait for the upload to complete
while (!uploadTask.IsCompleted)
{
yield return null; // pause and continue next frame
}
if (uploadTask.IsFaulted || uploadTask.IsCanceled)
{
Debug.LogError("Upload failed: " + uploadTask.Exception?.Message);
onComplete?.Invoke(null);
yield break;
}
var fileResult = request.ResponseBody;
if (fileResult == null)
{
Debug.LogError("Upload failed, file is null.");
onComplete?.Invoke(null);
yield break;
}
string fileUrl = $"{GoogleRawFileUrl}{fileResult.Id}";
onComplete?.Invoke(fileUrl);
}
}
}