예제 #1
2
	/// <summary>
	/// Auth and get all files in AppData.
	/// </summary>
	IEnumerator InitGoogleDrive()
	{
		initInProgress = true;

		drive = new GoogleDrive();
		drive.ClientID = "897584417662-rnkgkl5tlpnsau7c4oc0g2jp08cpluom.apps.googleusercontent.com";
		drive.ClientSecret = "tGNLbYnrdRO2hdFmwJAo5Fbt";

		var authorization = drive.Authorize();
		yield return StartCoroutine(authorization);

		if (authorization.Current is Exception)
		{
			Debug.LogWarning(authorization.Current as Exception);
			goto finish;
		}
		else
			Debug.Log("User Account: " + drive.UserAccount);

		// Get all files in AppData folder and view text file.
		{
			var listFiles = drive.ListFiles(drive.AppData);
			yield return StartCoroutine(listFiles);
			var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles);

			if (files != null)
			{
				foreach (var file in files)
				{
					Debug.Log(file);

					if (file.Title.EndsWith(".txt"))
					{
						var download = drive.DownloadFile(file);
						yield return StartCoroutine(download);
						
						var data = GoogleDrive.GetResult<byte[]>(download);
						Debug.Log(System.Text.Encoding.UTF8.GetString(data));
					}
				}
			}
			else
			{
				Debug.LogError(listFiles.Current);
			}
		}

	finish:
		initInProgress = false;
	}
예제 #2
0
        private static bool VerifyExistUpdates()
        {
            string gbackupFolder = ConfigurationManager.AppSettings["UpdatePathNameGDrive"];
            string jsonUpdate    = ConfigurationManager.AppSettings["jsonFileUpdate"];

            using (DriveService service = GoogleDrive.AbrirServico(credential))
            {
                string[] capdeUpdate = GoogleDrive.ProcurarArquivoId(service, gbackupFolder);

                if (capdeUpdate.Length == 0)
                {
                    GoogleDrive.CreateFolder(service, gbackupFolder);
                }

                string[] fileJsonUpdate = GoogleDrive.ProcurarArquivoId(service, jsonUpdate);
                if (fileJsonUpdate.Length != 0)
                {
                    string ss = Encoding.ASCII.GetString(GoogleDrive.DownloadFile(service, fileJsonUpdate[0]).ToArray());
                    serverVersion = JsonConvert.DeserializeObject <AppVersion>(ss);

                    if (Convert.ToDouble(thisAssemblyVersion.FileVersion.Replace(".", "")) < Convert.ToDouble(serverVersion.versao.Replace(".", "")))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
예제 #3
0
        private void WorkDownload_DoWork(object sender, DoWorkEventArgs e)
        {
            using (DriveService service = GoogleDrive.AbrirServico(credential))
            {
                Dictionary <string, string[]> dicioFields = new Dictionary <string, string[]>();
                foreach (string s in listFields)
                {
                    dicioFields.Add(s, GoogleDrive.ProcurarArquivoId(service, s));
                }

                int i = 0;

                if (!Directory.Exists(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\update\\"))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\update\\");
                }

                foreach (var field in dicioFields)
                {
                    MemoryStream ms = GoogleDrive.DownloadFile(service, field.Value[0]);
                    using (FileStream fs = new FileStream(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\update\\" + field.Key,
                                                          FileMode.Create, FileAccess.Write)) ms.WriteTo(fs);
                    i++;
                    (sender as BackgroundWorker).ReportProgress(i);
                }
            }
        }
예제 #4
0
    /// <summary>
    /// Auth and get all files in AppData.
    /// </summary>
    IEnumerator InitGoogleDrive()
    {
        initInProgress = true;

        drive              = new GoogleDrive();
        drive.ClientID     = "897584417662-rnkgkl5tlpnsau7c4oc0g2jp08cpluom.apps.googleusercontent.com";
        drive.ClientSecret = "tGNLbYnrdRO2hdFmwJAo5Fbt";

        drive.Scopes = new string[] {
            "https://www.googleapis.com/auth/drive.file",
            "https://www.googleapis.com/auth/userinfo.email",
            "https://www.googleapis.com/auth/drive.appdata",
        };

        var authorization = drive.Authorize();

        yield return(StartCoroutine(authorization));

        if (authorization.Current is Exception)
        {
            Debug.LogWarning(authorization.Current as Exception);
            goto finish;
        }
        else
        {
            Debug.Log("User Account: " + drive.UserAccount);
        }

        // Get all files in AppData folder and view text file.
        {
            var listFiles = drive.ListFiles(drive.AppData);
            yield return(StartCoroutine(listFiles));

            var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(listFiles);

            if (files != null)
            {
                foreach (var file in files)
                {
                    Debug.Log(file);

                    if (file.Title.EndsWith(".txt"))
                    {
                        var download = drive.DownloadFile(file);
                        yield return(StartCoroutine(download));

                        var data = GoogleDrive.GetResult <byte[]>(download);
                        Debug.Log(System.Text.Encoding.UTF8.GetString(data));
                    }
                }
            }
            else
            {
                Debug.LogError(listFiles.Current);
            }
        }

finish:
        initInProgress = false;
    }
예제 #5
0
    /// <summary>
    /// Auth and get all files in AppData.
    /// </summary>
    IEnumerator InitGoogleDrive()
    {
        initInProgress = true;

        drive              = new GoogleDrive();
        drive.ClientID     = "251952116687-bl6cbb0n9veq5ovirpk5n99pjlgtf16g.apps.googleusercontent.com";
        drive.ClientSecret = "z65O11Za6aB74a7r21_TbtFL";

        var authorization = drive.Authorize();

        yield return(StartCoroutine(authorization));

        if (authorization.Current is Exception)
        {
            Debug.LogWarning(authorization.Current as Exception);
            goto finish;
        }
        else
        {
            Debug.Log("User Account: " + drive.UserAccount);
        }

        // Get all files in AppData folder and view text file.
        {
            //var listFiles = drive.ListFiles(drive.AppData);
            //var listFiles = drive.ListAllFiles();
            var listFiles = drive.ListFolders("");


            yield return(StartCoroutine(listFiles));

            var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(listFiles);

            if (files != null)
            {
                foreach (var file in files)
                {
                    Debug.Log(file);

                    if (file.Title.EndsWith(".txt"))
                    {
                        var download = drive.DownloadFile(file);
                        yield return(StartCoroutine(download));

                        var data = GoogleDrive.GetResult <byte[]>(download);
                        Debug.Log(System.Text.Encoding.UTF8.GetString(data));
                    }
                }
            }
            else
            {
                Debug.LogError(listFiles.Current);
            }
        }

finish:
        initInProgress = false;
    }
예제 #6
0
	/// <summary>
	/// Auth and get all files in AppData.
	/// </summary>
	IEnumerator InitGoogleDrive()
	{
		initInProgress = true;

		drive = new GoogleDrive();
		drive.ClientID = "251952116687-bl6cbb0n9veq5ovirpk5n99pjlgtf16g.apps.googleusercontent.com";
		drive.ClientSecret = "z65O11Za6aB74a7r21_TbtFL";

		var authorization = drive.Authorize();
		yield return StartCoroutine(authorization);

		if (authorization.Current is Exception)
		{
			Debug.LogWarning(authorization.Current as Exception);
			goto finish;
		}
		else
			Debug.Log("User Account: " + drive.UserAccount);

		// Get all files in AppData folder and view text file.
		{
			//var listFiles = drive.ListFiles(drive.AppData);
			//var listFiles = drive.ListAllFiles();
			var listFiles = drive.ListFolders("");


			yield return StartCoroutine(listFiles);
			var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles);

			if (files != null)
			{
				foreach (var file in files)
				{
					Debug.Log(file);

					if (file.Title.EndsWith(".txt"))
					{
						var download = drive.DownloadFile(file);
						yield return StartCoroutine(download);
						
						var data = GoogleDrive.GetResult<byte[]>(download);
						Debug.Log(System.Text.Encoding.UTF8.GetString(data));
					}
				}
			}
			else
			{
				Debug.LogError(listFiles.Current);
			}
		}

	finish:
		initInProgress = false;
	}
예제 #7
0
    /// <summary>
    /// Auth and get all files in AppData.
    /// </summary>
    IEnumerator InitGoogleDrive()
    {
        initInProgress = true;

        drive              = new GoogleDrive();
        drive.ClientID     = "327028157545-te6a8nm4josmi80t08i3mvkn3snmnt9m.apps.googleusercontent.com";
        drive.ClientSecret = "XJWfBPzJinRvj1JLytI-eyWK";

        var authorization = drive.Authorize();

        yield return(StartCoroutine(authorization));

        if (authorization.Current is Exception)
        {
            Debug.LogWarning(authorization.Current as Exception);
            goto finish;
        }
        else
        {
            Debug.Log("User Account: " + drive.UserAccount);
        }

        // Get all files in AppData folder and view text file.
        {
            var listFiles = drive.ListFiles(drive.AppData);
            yield return(StartCoroutine(listFiles));

            var files = GoogleDrive.GetResult <List <GoogleDrive.File> > (listFiles);

            if (files != null)
            {
                foreach (var file in files)
                {
                    Debug.Log(file);

                    if (file.Title.EndsWith(".txt"))
                    {
                        var download = drive.DownloadFile(file);
                        yield return(StartCoroutine(download));

                        var data = GoogleDrive.GetResult <byte[]> (download);
                        Debug.Log(System.Text.Encoding.UTF8.GetString(data));
                    }
                }
            }
            else
            {
                Debug.LogError(listFiles.Current);
            }
        }

finish:
        initInProgress = false;
    }
예제 #8
0
    IEnumerator ListPresentationsCoroutine()
    {
        Drive.ClientID     = "327028157545-te6a8nm4josmi80t08i3mvkn3snmnt9m.apps.googleusercontent.com";
        Drive.ClientSecret = "XJWfBPzJinRvj1JLytI-eyWK";

        // Request authorization.
        var authorization = Drive.Authorize();

        yield return(StartCoroutine(authorization));

        if (authorization.Current is Exception)
        {
            Debug.LogWarning(authorization.Current as Exception);
            yield break;
        }

        // Authorization succeeded.
        Debug.Log("User Account: " + Drive.UserAccount);

        var listFiles = Drive.ListFilesByQueary("mimeType = 'application/vnd.google-apps.presentation'");

        //var listFiles = Drive.ListAllFiles ();
        yield return(StartCoroutine(listFiles));

        var files = GoogleDrive.GetResult <List <GoogleDrive.File> > (listFiles);

        if (files != null && files.Count > 0)
        {
            foreach (GoogleDrive.File file in files)
            {
                //Debug.Log (file.Title);
            }
            GoogleDrive.File file0 = files [0];
            var pdfExportLink      = file0.ExportLinks ["application/pdf"];

            var download = Drive.DownloadFile((string)pdfExportLink);
            yield return(StartCoroutine(download));

            var data = GoogleDrive.GetResult <byte[]> (download);
            if (data != null)
            {
                Debug.Log("Happy");
                Stream pdfStream = new MemoryStream(data);
                //PdfSharp.Pdf.PdfDocument pdfDoc = PdfSharp.Pdf.IO.PdfReader.Open (pdfStream, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);

                //	Debug.Log (pdfDoc.Info.Title);
            }
        }
        else
        {
            Debug.Log("files: " + files.Count);
        }
    }
예제 #9
0
    /// <summary>
    /// <para>Update 'my_text.txt' in the root folder.</para>
    /// <para>The file has json data.</para>
    /// </summary>
    IEnumerator UploadText()
    {
        if (drive == null || !drive.IsAuthorized || uploadTextInProgress)
        {
            yield break;
        }

        uploadTextInProgress = true;

        // Get 'my_text.txt'.
        var list = drive.ListFilesByQueary("title = 'my_text.txt'");

        yield return(StartCoroutine(list));

        GoogleDrive.File            file;
        Dictionary <string, object> data;

        var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(list);

        if (files == null || files.Count > 0)
        {
            // Found!
            file = files[0];

            // Download file data.
            var download = drive.DownloadFile(file);
            yield return(StartCoroutine(download));

            var bytes = GoogleDrive.GetResult <byte[]>(download);
            try
            {
                // Data is json format.
                var reader = new JsonFx.Json.JsonReader(Encoding.UTF8.GetString(bytes));
                data = reader.Deserialize <Dictionary <string, object> >();
            }
            catch (Exception e)
            {
                Debug.LogWarning(e);

                data = new Dictionary <string, object>();
            }
        }
        else
        {
            // Make a new file.
            file = new GoogleDrive.File(new Dictionary <string, object>
            {
                { "title", "my_text.txt" },
                { "mimeType", "text/plain" },
                { "description", "test" }
            });
            data = new Dictionary <string, object>();
        }

        // Update file data.
        data["date"] = DateTime.Now.ToString();
        if (data.ContainsKey("count"))
        {
            data["count"] = (int)data["count"] + 1;
        }
        else
        {
            data["count"] = 0;
        }

        // And uploading...
        {
            var bytes = Encoding.UTF8.GetBytes(JsonFx.Json.JsonWriter.Serialize(data));

            var upload = drive.UploadFile(file, bytes);
            yield return(StartCoroutine(upload));

            if (!(upload.Current is Exception))
            {
                Debug.Log("Upload complete!");
            }
        }

        uploadTextInProgress = false;
    }
예제 #10
0
    IEnumerator DonwloadAllFilesInFolder_internal(string loadFolderName, string saveFolderPath)
    {
        _isFileDownloadProcessing = true;

        _isFileDownloadDone       = false;
        _isSingleFileDownloadDone = false;



        string targetId = "";

        if (loadFolderName != "")
        {
            if (_filesDictionary != null && _filesDictionary.ContainsKey(loadFolderName))
            {
                targetId = _filesDictionary [loadFolderName].ID;
            }
        }

        var listFiles = _drive.ListFolders(recentFolderID);

        yield return(StartCoroutine(listFiles));

        var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(listFiles);


        if (files != null)
        {
            //Processing Number Initialize !!
            if (!Directory.Exists(saveFolderPath))
            {
                Directory.CreateDirectory(saveFolderPath);
            }


            //Processed file count
            _NumberOfTotalDownloadFile = 0;
            foreach (var file in files)
            {
                if (file.Title.EndsWith(".jpg") || file.Title.EndsWith(".png") || file.Title.EndsWith(".JPG") || file.Title.EndsWith(".PNG"))
                {
                    _NumberOfTotalDownloadFile += 1;
                }
            }
            _NumberOfProcessedFile    = 0;
            _isSingleFileDownloadDone = true;


            //Download Start;

            //fileName Duplicator Check
            List <string> fileNameList = new List <string>();

            foreach (var file in files)
            {
                                #if UNITY_EDITOR
                Debug.Log(file);
                                #endif

                if (_isFileDownloadCancel)
                {
                    break;
                }


                if (file.Title.EndsWith(".jpg") || file.Title.EndsWith(".png") || file.Title.EndsWith(".JPG") || file.Title.EndsWith(".PNG"))
                {
                    var download = _drive.DownloadFile(file);
                    yield return(StartCoroutine(download));

                    var data = GoogleDrive.GetResult <byte[]>(download);

                    //Name Duplicator checker
                    string finalFileTitle = file.Title;

                    bool bIsDuplicatedFileName = false;
                    int  duplicatedNumber      = 0;
                    foreach (string title in fileNameList)
                    {
                        if (title == file.Title)
                        {
                            bIsDuplicatedFileName = true;
                            duplicatedNumber++;
                        }
                    }

                    if (bIsDuplicatedFileName)
                    {
                        finalFileTitle += duplicatedNumber.ToString();
                    }

                    try{
                        FileStream fs = new FileStream(saveFolderPath + "/" + finalFileTitle, FileMode.Create);
                        fs.Write(data, 0, data.Length);
                        fs.Dispose();

                        fileNameList.Add(file.Title);

                        //-----
                        ++_NumberOfProcessedFile;
                        _isSingleFileDownloadDone = true;
                    }catch {
                        _isFileDownloadCancel = true;
                    }
                }
            }
        }
        else
        {
                        #if UNITY_EDITOR
            Debug.Log(listFiles.Current);
                        #endif
        }

        _isFileDownloadDone = true;
    }
예제 #11
0
        public HttpResponseMessage UploadGoogleDocument(UploadGoogleDocument documentGoogle)
        {
            HttpResponseMessage     responseToClient = new HttpResponseMessage();
            ResponseMessageDocument responseMessage  = new ResponseMessageDocument();
            bool fileDuplicateFlag = false;

            try
            {
                System.Collections.Generic.IEnumerable <string> iHeader;
                Request.Headers.TryGetValues("AuthToken", out iHeader);
                string authToken = iHeader.ElementAt(0);

                string tempDirectory = ConfigurationManager.AppSettings["TempDirectory"].ToString() + documentGoogle.EnvelopeId;
                using (var dbContext = new eSignEntities())
                {
                    EnvelopeRepository envelopeRepository = new EnvelopeRepository(dbContext);
                    bool isEnvelopePrepare = envelopeRepository.IsEnvelopePrepare(new Guid(documentGoogle.EnvelopeId));
                    if (!Directory.Exists(tempDirectory))
                    {
                        responseMessage.StatusCode    = HttpStatusCode.BadRequest;
                        responseMessage.StatusMessage = "BadRequest";
                        responseMessage.Message       = ConfigurationManager.AppSettings["EnvelopeIdMissing"].ToString();
                        responseMessage.EnvelopeId    = documentGoogle.EnvelopeId;
                        responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage);
                        return(responseToClient);
                    }
                    else if (isEnvelopePrepare == true)
                    {
                        responseMessage.StatusCode    = HttpStatusCode.BadRequest;
                        responseMessage.StatusMessage = "BadRequest";
                        responseMessage.Message       = ConfigurationManager.AppSettings["EnvelopePrepared"].ToString();
                        responseMessage.EnvelopeId    = documentGoogle.EnvelopeId;
                        responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage);
                        return(responseToClient);
                    }
                    else
                    {
                        UserTokenRepository userTokenRepository = new UserTokenRepository(dbContext);
                        string userEmail        = userTokenRepository.GetUserEmailByToken(authToken);
                        Guid   UserId           = userTokenRepository.GetUserProfileUserIDByID(userTokenRepository.GetUserProfileIDByEmail(userEmail));
                        bool   isEnvelopeExists = envelopeRepository.IsUserEnvelopeExists(UserId, new Guid(documentGoogle.EnvelopeId));
                        if (!isEnvelopeExists)
                        {
                            responseMessage.StatusCode    = HttpStatusCode.NoContent;
                            responseMessage.StatusMessage = "NoContent";
                            responseMessage.Message       = Convert.ToString(ConfigurationManager.AppSettings["NoContent"].ToString());
                            responseMessage.EnvelopeId    = documentGoogle.EnvelopeId;
                            responseToClient = Request.CreateResponse(HttpStatusCode.NoContent, responseMessage, Configuration.Formatters.XmlFormatter);
                            return(responseToClient);
                        }
                        string documentUploadPath = Path.Combine(tempDirectory, ConfigurationManager.AppSettings["UploadedDocuments"].ToString());
                        string docFinalPath       = Path.Combine(documentUploadPath, documentGoogle.FileName);
                        if (!Directory.Exists(documentUploadPath))
                        {
                            Directory.CreateDirectory(documentUploadPath);
                        }

                        string[] listOfFiles = Directory.GetFiles(documentUploadPath);
                        foreach (var file in listOfFiles)
                        {
                            if (file.Contains(documentGoogle.FileName))
                            {
                                fileDuplicateFlag = true;
                                break;
                            }
                        }
                        if (fileDuplicateFlag)
                        {
                            responseMessage.StatusCode    = HttpStatusCode.Ambiguous;
                            responseMessage.StatusMessage = "Ambiguous";
                            responseMessage.Message       = ConfigurationManager.AppSettings["FileDuplicate"].ToString();
                            responseMessage.EnvelopeId    = documentGoogle.EnvelopeId;
                            responseToClient = Request.CreateResponse(HttpStatusCode.Ambiguous, responseMessage);
                            return(responseToClient);
                        }
                        //string[] validFileTypes = { "docx", "pdf", "doc", "xls", "xlsx", "ppt", "pptx", "DOCX", "PDF", "DOC", "XLS", "XLSX", "PPT", "PPTX" };
                        //string ext = Path.GetExtension(documentDropbox.FileName);
                        //bool isValidType = false;
                        //for (int j = 0; j < validFileTypes.Length; j++)
                        //{
                        //    if (ext == "." + validFileTypes[j])
                        //    {
                        //        isValidType = true;
                        //        break;
                        //    }
                        //}
                        //if (!isValidType)
                        //{
                        //    responseMessage.StatusCode = HttpStatusCode.NotAcceptable;
                        //    responseMessage.StatusMessage = "NotAcceptable";
                        //    responseMessage.Message = ConfigurationManager.AppSettings["InvalidFileExtension"].ToString();
                        //    responseMessage.EnvelopeId = documentDropbox.EnvelopeId;
                        //    responseToClient = Request.CreateResponse(HttpStatusCode.NotAcceptable, responseMessage);
                        //    return responseToClient;
                        //}
                        string tocheck = string.Empty;
                        try
                        {
                            tocheck = gDrive.DownloadFile(documentGoogle.AccessToken, documentGoogle.DownloadUrl, documentGoogle.FileName, documentUploadPath);
                        }
                        catch (WebException ex)
                        {
                            responseMessage.StatusCode    = HttpStatusCode.BadRequest;
                            responseMessage.StatusMessage = "BadRequest";
                            responseMessage.Message       = ConfigurationManager.AppSettings["InvalidDownloadUri"].ToString();
                            responseMessage.EnvelopeId    = documentGoogle.EnvelopeId;
                            responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage);
                            return(responseToClient);
                        }
                        Guid documentId = Guid.NewGuid();

                        DocumentRepository documentRepository = new DocumentRepository(dbContext);
                        UnitOfWork         unitOfWork         = new UnitOfWork(dbContext);
                        Documents          doc = new Documents();
                        doc.ID               = documentId;
                        doc.EnvelopeID       = new Guid(documentGoogle.EnvelopeId);
                        doc.DocumentName     = documentGoogle.FileName;
                        doc.UploadedDateTime = DateTime.Now;
                        int docCount = Directory.GetFiles(documentUploadPath).Length;
                        doc.Order = (short)(docCount);
                        documentRepository.Save(doc);
                        unitOfWork.SaveChanges();

                        responseMessage.StatusCode    = HttpStatusCode.OK;
                        responseMessage.StatusMessage = "OK";
                        responseMessage.Message       = ConfigurationManager.AppSettings["SuccessDocumentUpload"].ToString();
                        responseMessage.EnvelopeId    = documentGoogle.EnvelopeId;
                        responseMessage.DocumentId    = Convert.ToString(documentId);
                        responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessage);
                        return(responseToClient);
                    }
                }
            }
            catch (Exception e)
            {
                responseToClient         = Request.CreateResponse((HttpStatusCode)422);
                responseToClient.Content = new StringContent(e.Message, Encoding.Unicode);
                throw new HttpResponseException(responseToClient);
            }
        }
예제 #12
0
 public byte[] DownloadFile(string fileId)
 {
     var drive = new GoogleDrive();
     return drive.DownloadFile(fileId);
 }