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; using System.Threading;
public class GoogleDriveUtils public class GoogleDriveUtils
{ {
static string[] Scopes = { DriveService.Scope.Drive }; // or DriveService.Scope.Drive for full access static string[] Scopes = { DriveService.Scope.Drive }; // or DriveService.Scope.Drive for full access
static string ApplicationName = "MyDriveUploader"; 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 DriveService service;
@ -90,82 +91,67 @@ public class GoogleDriveUtils
return currentFolderId; 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); Debug.Log("Uploading file to Google Drive: " + _uploadFile);
if (System.IO.File.Exists(_uploadFile)) if (!System.IO.File.Exists(_uploadFile))
{ {
// File body = new File(); Debug.LogError("File does not exist: " + _uploadFile);
// body.Name = System.IO.Path.GetFileName(_uploadFile); onComplete?.Invoke(null);
// body.Description = "File updated by Diamto Drive Sample"; yield break;
// body.MimeType = "image/png"; }
// byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
// System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
// Replace with your folder ID Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File()
var fileMetadata = new Google.Apis.Drive.v3.Data.File() {
{ Name = Path.GetFileName(_uploadFile),
Name = Path.GetFileName(_uploadFile), Parents = new List<string> { folderId }
Parents = new List<string> };
{
folderId
}
};
Debug.Log("metadata prepared." + fileMetadata); Debug.Log("Metadata prepared: " + fileMetadata.Name);
// 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.
var request = service.Files.Create(fileMetadata, stream, "image/png"); using (var stream = new FileStream(_uploadFile, FileMode.Open))
request.Fields = "id, name"; {
request.SupportsAllDrives = true; 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.ProgressChanged += (progress) =>
request.ResponseReceived += (file) => Debug.Log($"File uploaded successfully: {file.Name} (ID: {file.Id})"); {
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) var uploadTask = request.UploadAsync();
{
// TODO: handle a file upload error.
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// Debug.Log("request prepared." + request);
// var file = request.ResponseBody; // Wait for the upload to complete
while (!uploadTask.IsCompleted)
{
yield return null; // pause and continue next frame
}
// if(file==null) if (uploadTask.IsFaulted || uploadTask.IsCanceled)
// { {
// Debug.LogError("Upload failed, file is null."); Debug.LogError("Upload failed: " + uploadTask.Exception?.Message);
// return; onComplete?.Invoke(null);
// } yield break;
// string fileId= file.Id; }
// string fileUrl = $"https://drive.google.com/file/d/{fileId}/view";
// Debug.Log("File URL: " + fileUrl);
// Debug.Log("File ID: " + fileId);
}
var fileResult = request.ResponseBody;
} if (fileResult == null)
catch (Exception e)
{ {
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 discard = parmas.Length > 4 && (parmas[4].Trim().ToLower() == "discard");
bool default_image = parmas.Length > 5 && (parmas[5].Trim().ToLower() == "default"); bool default_image = parmas.Length > 5 && (parmas[5].Trim().ToLower() == "default");
if (discard) if (ImageDiscard != null) ImageDiscard.SetActive(discard);
{ if (ImageDiscardPostcard != null) ImageDiscardPostcard.SetActive(discard);
if (ImageDiscard != null) ImageDiscard.SetActive(true);
}
else
{
if (ImageDiscard != null) ImageDiscard.SetActive(false);
}
Debug.Log("choice: " + discard + " default" + default_image + " summary:" + summary); Debug.Log("discard: " + discard + " default" + default_image + " summary:" + summary);
if (summary.Length > 0) if (summary.Length > 0)
{ {
@ -92,15 +86,13 @@ public class UploadToGoogleDrive : MonoBehaviour
if (default_image) if (default_image)
{ {
ImageGenerate.SetActive(false); ImageGenerate.SetActive(false);
if (!discard) ImageDiscard.SetActive(false);
ImageGeneratePostcard.SetActive(false); ImageGeneratePostcard.SetActive(false);
if (!discard) ImageDiscardPostcard.SetActive(false);
} }
else else
{ {
ImageGenerate.SetActive(true); ImageGenerate.SetActive(true);
ImageGeneratePostcard.SetActive(true); ImageGeneratePostcard.SetActive(true);
} }
TextNumber.SetText(id); TextNumber.SetText(id);
@ -136,7 +128,7 @@ public class UploadToGoogleDrive : MonoBehaviour
string print_fullPath = System.IO.Path.Combine(OutputFolder + "/" + uploadDest + "/", filename + "_print.png"); string print_fullPath = System.IO.Path.Combine(OutputFolder + "/" + uploadDest + "/", filename + "_print.png");
Debug.Log("print_path: " + print_fullPath); 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"); string share_fullPath = System.IO.Path.Combine(OutputFolder + "/" + uploadDest + "/", filename + ".png");
Debug.Log("share_path: " + share_fullPath); 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) if(GoogleDriveUtils.service == null)
// { {
// Debug.Log("service is null, setting up service again."); Debug.Log("service is null, setting up service again.");
// setupService(); setupService();
// } }
string path = _fileId; string path = _fileId;
int lastSlash = path.LastIndexOf('/'); int lastSlash = path.LastIndexOf('/');
if (lastSlash >= 0) if (lastSlash >= 0)
{ {
path = path.Substring(0, lastSlash); path = path[..lastSlash];
} }
Debug.Log("Uploading file to Google Drive: " + _uploadFile + " folder=" + path); Debug.Log("Uploading file to Google Drive: " + _uploadFile + " folder=" + path);
string folderId = GoogleDriveUtils.getFolder(GoogleDriveUtils.service, path, GoogleDriveFolderId); 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) public void writeToFirebase(string collection, string id, string url, string type)

Loading…
Cancel
Save