update drive url

main
reng 3 months ago
parent bfe3734365
commit 9aa01c96a6
  1. 106
      Assets/Scripts/GoogleDriveUtils.cs
  2. 57
      Assets/Scripts/UploadToGoogleDrive.cs

@ -15,12 +15,13 @@ 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;
@ -90,82 +91,67 @@ public class GoogleDriveUtils
return currentFolderId;
}
public static async Task upload(DriveService service, string _uploadFile, string folderId, string _fileId, string type)
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))
if (!System.IO.File.Exists(_uploadFile))
{
// File body = new File();
// body.Name = System.IO.Path.GetFileName(_uploadFile);
// body.Description = "File updated by Diamto Drive Sample";
// body.MimeType = "image/png";
// byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
// System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
Debug.LogError("File does not exist: " + _uploadFile);
onComplete?.Invoke(null);
yield break;
}
// Replace with your folder ID
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = Path.GetFileName(_uploadFile),
Parents = new List<string>
{
folderId
}
};
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);
// FilesResource.CreateMediaUpload request;
// Create a new file on drive.
using (var stream = new FileStream(_uploadFile, FileMode.Open))
{
// Create a new file, with metadata and stream.
Debug.Log("Metadata prepared: " + fileMetadata.Name);
var request = service.Files.Create(fileMetadata, stream, "image/png");
request.Fields = "id, name";
request.SupportsAllDrives = true;
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})");
request.ProgressChanged += (progress) =>
{
Debug.Log($"Upload Progress: {progress.Status} - Bytes Sent: {progress.BytesSent} {progress.Exception?.Message}");
};
var results = await request.UploadAsync();
request.ResponseReceived += (file) =>
{
Debug.Log($"File uploaded successfully: {file.Name} (ID: {file.Id})");
};
if (results.Status == UploadStatus.Failed)
{
// TODO: handle a file upload error.
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// Debug.Log("request prepared." + request);
var uploadTask = request.UploadAsync();
// var file = request.ResponseBody;
// Wait for the upload to complete
while (!uploadTask.IsCompleted)
{
yield return null; // pause and continue next frame
}
// if(file==null)
// {
// Debug.LogError("Upload failed, file is null.");
// return;
// }
// string fileId= file.Id;
// string fileUrl = $"https://drive.google.com/file/d/{fileId}/view";
// Debug.Log("File URL: " + fileUrl);
// Debug.Log("File ID: " + fileId);
}
if (uploadTask.IsFaulted || uploadTask.IsCanceled)
{
Debug.LogError("Upload failed: " + uploadTask.Exception?.Message);
onComplete?.Invoke(null);
yield break;
}
var fileResult = request.ResponseBody;
}
catch (Exception e)
if (fileResult == null)
{
Debug.LogError("An error occurred: " + e.Message + " " + e.StackTrace);
Debug.LogError("Upload failed, file is null.");
onComplete?.Invoke(null);
yield break;
}
}
else
{
Debug.LogError("File does not exist: " + _uploadFile);
string fileUrl = $"{GoogleRawFileUrl}{fileResult.Id}";
onComplete?.Invoke(fileUrl);
}
}
}

@ -67,16 +67,10 @@ public class UploadToGoogleDrive : MonoBehaviour
bool discard = parmas.Length > 4 && (parmas[4].Trim().ToLower() == "discard");
bool default_image = parmas.Length > 5 && (parmas[5].Trim().ToLower() == "default");
if (discard)
{
if (ImageDiscard != null) ImageDiscard.SetActive(true);
}
else
{
if (ImageDiscard != null) ImageDiscard.SetActive(false);
}
if (ImageDiscard != null) ImageDiscard.SetActive(discard);
if (ImageDiscardPostcard != null) ImageDiscardPostcard.SetActive(discard);
Debug.Log("choice: " + discard + " default" + default_image + " summary:" + summary);
Debug.Log("discard: " + discard + " default" + default_image + " summary:" + summary);
if (summary.Length > 0)
{
@ -92,15 +86,13 @@ public class UploadToGoogleDrive : MonoBehaviour
if (default_image)
{
ImageGenerate.SetActive(false);
if (!discard) ImageDiscard.SetActive(false);
ImageGeneratePostcard.SetActive(false);
if (!discard) ImageDiscardPostcard.SetActive(false);
}
else
{
ImageGenerate.SetActive(true);
ImageGeneratePostcard.SetActive(true);
}
TextNumber.SetText(id);
@ -136,7 +128,7 @@ public class UploadToGoogleDrive : MonoBehaviour
string print_fullPath = System.IO.Path.Combine(OutputFolder + "/" + uploadDest + "/", filename + "_print.png");
Debug.Log("print_path: " + print_fullPath);
upload(print_fullPath, id, "print");
upload(print_fullPath, id, "print", !default_image && !discard);
string share_fullPath = System.IO.Path.Combine(OutputFolder + "/" + uploadDest + "/", filename + ".png");
Debug.Log("share_path: " + share_fullPath);
@ -174,27 +166,50 @@ public class UploadToGoogleDrive : MonoBehaviour
}
async void upload(string _uploadFile, string _fileId, string type)
void upload(string _uploadFile, string _fileId, string type, bool needToPrint = true)
{
// if(service == null)
// {
// Debug.Log("service is null, setting up service again.");
// setupService();
// }
if(GoogleDriveUtils.service == null)
{
Debug.Log("service is null, setting up service again.");
setupService();
}
string path = _fileId;
int lastSlash = path.LastIndexOf('/');
if (lastSlash >= 0)
{
path = path.Substring(0, lastSlash);
path = path[..lastSlash];
}
Debug.Log("Uploading file to Google Drive: " + _uploadFile + " folder=" + path);
string folderId = GoogleDriveUtils.getFolder(GoogleDriveUtils.service, path, GoogleDriveFolderId);
await GoogleDriveUtils.upload(GoogleDriveUtils.service, _uploadFile, folderId, _fileId, type);
StartCoroutine(GoogleDriveUtils.UploadCoroutine(GoogleDriveUtils.service, _uploadFile, folderId, _fileId, type,
(response) =>
{
if (response != null)
{
var url = response;
Debug.Log("Upload successful:" + url);
if (type == "print")
{
if(needToPrint)
writeToFirebase("prints", System.DateTime.Now.ToString("yyyyMMdd_hhmmss"), url, type);
}
else
{
writeToFirebase("records", "user/" + _fileId + "/file/" + type, url, type);
}
}
else
{
Debug.LogError("Upload failed: " + response);
}
}
));
}
public void writeToFirebase(string collection, string id, string url, string type)

Loading…
Cancel
Save