Пример #1
0
        private BatchUpdateDocumentRequest GenerateGoogleDocText(string transcription)
        {
            var endOfSegment      = new EndOfSegmentLocation();
            var inserttextRequest = new InsertTextRequest
            {
                Text = transcription,
                EndOfSegmentLocation = endOfSegment
            };

            var request = new Request
            {
                InsertText = inserttextRequest
            };

            var requestList = new List <Request>()
            {
                request
            };

            var updateRequest = new BatchUpdateDocumentRequest
            {
                Requests = requestList
            };

            return(updateRequest);
        }
Пример #2
0
        private void Write()
        {
            string[] Scopes = { DocsService.Scope.Documents, DocsService.Scope.DriveFile, DocsService.Scope.Drive };

            UserCredential credential;

            using (var stream = new FileStream($"/Users/mathiasgammelgaard/credentials/credentials.json", FileMode.Open, FileAccess.Read)) {
                string credPath = "/Users/mathiasgammelgaard/credentials/token.json";

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            DocsService service = new DocsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential
            });

            // Define request parameters.
            String documentId = "1tldY_DpX5IM9wPqIKN9FVgwfBT2Ueq__F8pwOI8dLVI";

            DocumentsResource.GetRequest documentRequest = service.Documents.Get(documentId);
            Document doc = documentRequest.Execute();

            List <Request> requests = new List <Request>();

            DeleteAllContent(requests, doc, service, documentId);

            foreach (Course course in courses)
            {
                //AddHeaderLine(course.title, requests, 1);
                foreach (Section section in course.sections)
                {
                    if (section.description != null)
                    {
                        AddHeaderLine(section.name, requests, 3);
                        AddParagraph(section.description.levels[0].description, requests);
                    }
                    else
                    {
                        AddHeaderLine(section.name, requests, 3, false);
                        AddQuizQuestions(section.quiz.levels[0], requests);
                    }
                }
            }



            BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();

            body.Requests = requests;
            DocumentsResource.BatchUpdateRequest updateRequest = service.Documents.BatchUpdate(body, documentId);

            updateRequest.Execute();
        }
Пример #3
0
        public void InsertImage(string docId, string imagePath)
        {
            var doc             = GetDoc(docId);
            var docElementCount = doc.InlineObjects.Count;
            //var docContentCount = doc.PositionedObjects?.Count ?? 0;
            //Console.WriteLine($"{docElementCount} / {docContentCount}");

            List <Request> requests = new List <Request>();

            var image = new InsertInlineImageRequest();

            image.Uri      = imagePath;
            image.Location = new Location()
            {
                Index = docElementCount + 1
            };
            //image.ObjectSize = new Size() { Width = new Dimension() { Magnitude = 10, Unit = "PT" } };



            var request = new Request()
            {
                InsertInlineImage = image
            };                                                         //, UpdateParagraphStyle = { ParagraphStyle = { Alignment="CENTER" } } };

            requests.Add(request);

            BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();

            body.Requests = requests;

            BatchUpdateDocumentResponse response = this.service.Documents.BatchUpdate(body, docId).Execute();
        }
Пример #4
0
        private static void mergeText(DocsService service, string documentId)
        {
            String customerName = "Alice";
            String date         = DateTime.Now.ToString("yyyy/MM/dd");

            List <Request> requests            = new List <Request>();
            var            customerNameRequest = new Request();

            customerNameRequest.ReplaceAllText = new ReplaceAllTextRequest();
            customerNameRequest.ReplaceAllText.ContainsText = (new SubstringMatchCriteria()
            {
                Text = "{{customer-name}}",
                MatchCase = true
            });
            customerNameRequest.ReplaceAllText.ReplaceText = (customerName);
            requests.Add(customerNameRequest);
            var dateRequest = new Request();

            dateRequest.ReplaceAllText = new ReplaceAllTextRequest();
            dateRequest.ReplaceAllText.ContainsText = (new SubstringMatchCriteria()
            {
                Text = "{{date}}",
                MatchCase = true
            });
            dateRequest.ReplaceAllText.ReplaceText = (date);
            requests.Add(dateRequest);
            BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();

            body.Requests = requests;
            service.Documents.BatchUpdate(body, documentId).Execute();
        }
        public void WriteFile(string content)
        {
            logger.LogTrace("Updating doc");
            var location          = GetLastLocationFromFile();
            var insertTextRequest = CreateInsertTextRequest(content, location, out var req);

            req.InsertText = insertTextRequest;
            var requests = new List <Request>()
            {
                req
            };

            var body = new BatchUpdateDocumentRequest
            {
                Requests = requests
            };

            service.Documents.BatchUpdate(body, DocumentId).Execute();
            logger.LogTrace("Updating doc - Done");
        }
Пример #6
0
        /// <summary>
        /// 対象ファイル内の文字列を置換します。
        /// </summary>
        /// <param name="document">対象ファイルを指定します。</param>
        /// <param name="origin">置換される文字列を指定します。</param>
        /// <param name="changed">置換後の文字列を指定します。</param>
        /// <param name="isCaseSensitive">大文字小文字を区別する場合はtrue、それ以外はfalseを指定します。</param>
        /// <returns></returns>
        public static Document ReplaceText(Document document, string origin, string changed, bool isCaseSensitive)
        {
            var req     = new BatchUpdateDocumentRequest();
            var replace = new Request();

            replace.ReplaceAllText = new ReplaceAllTextRequest()
            {
                ContainsText = new SubstringMatchCriteria()
                {
                    Text      = origin,
                    MatchCase = isCaseSensitive
                },
                ReplaceText = changed
            };

            req.Requests = new List <Request>();
            req.Requests.Add(replace);
            var updater  = Service.Documents.BatchUpdate(req, document.DocumentId);
            var response = updater.Execute();

            return(document);
        }
Пример #7
0
        private void DeleteAllContent(List <Request> requests, Document doc, DocsService service, string documentId)
        {
            DeleteContentRangeRequest deleteContentRangeRequest = new DeleteContentRangeRequest();

            Google.Apis.Docs.v1.Data.Range range = new Google.Apis.Docs.v1.Data.Range();
            range.StartIndex = 1;
            range.EndIndex   = 1000000000;

            deleteContentRangeRequest.Range = range;

            Request request = new Request();

            request.DeleteContentRange = deleteContentRangeRequest;

            try {
                BatchUpdateDocumentRequest tryBody = new BatchUpdateDocumentRequest();

                tryBody.Requests = new List <Request> {
                    request
                };
                DocumentsResource.BatchUpdateRequest tryUpdateRequest = service.Documents.BatchUpdate(tryBody, documentId);

                BatchUpdateDocumentResponse tryResponse = tryUpdateRequest.Execute();
            } catch (Exception e) {
                string[] responseData = e.Message.Split("must be less than the end index of the referenced segment, ");
                responseData = responseData[1].Split(".");

                range.EndIndex = Int32.Parse(responseData[0]) - 1;

                if (range.EndIndex - range.StartIndex != 0)
                {
                    deleteContentRangeRequest.Range = range;

                    request = new Request();
                    request.DeleteContentRange = deleteContentRangeRequest;
                    requests.Add(request);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Guarda el contenido del fichero de notas de gsNotasNET en Drive como documentos.
        /// </summary>
        /// <param name="ficNotas">El path de las notas usadas por la aplicación.</param>
        /// <param name="borrarAnt">SI para borrar PERMANENTEMENTE los ficheros existentes o NO para no eliminarlos.</param>
        /// <param name="lasNotas">
        /// Si se indica, será la colección de grupos y notas.
        /// En ese caso, no se leen las notas del fichero.
        /// </param>
        /// <returns>Devuelve el número de documentos (notas) creados.</returns>
        /// <remarks>Si se indica SI, los documentos se eliminarán permanentemente (no van a la papelera).</remarks>
        public static int GuardarNotasDrive(string ficNotas,
                                            string borrarAnt = "NO",
                                            Dictionary <string, List <string> > lasNotas = null)
        {
            OnIniciadoGuardarNotasEnDrive();

            FicNotas = ficNotas;

            UserCredential credential;
            //var credPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            // En Android usar:
            //Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "gsNotasNET.db3"
            //var credDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            //var credDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //var credDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            //var credPath = System.IO.Path.Combine(credDir, ".credentials/gsNotasNET-2.0");
            //// Eliminar la carpeta y el contenido ya que se ve que sigue estando
            //// esto solo para la que había antes
            // Dice que no encuentra parte del path
            // /data/user/0/com.elguille.gsnotasnet/files/.local/share/.credentials/gsNotasNET-2.0
            //System.IO.Directory.Delete(credPath, true);

            // La nueva carpeta para las credenciales, a partir de v1.0.0.10
            var credDir  = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var credPath = System.IO.Path.Combine(credDir, ".credentials/gsNotasNET.Android");

            using (var stream = App.ClientSecretJson)
            {
                //string credPath = "token.json";

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            // Create Google Docs API service.
            docService = new DocsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            var nombreFolderPred = "gsNotasNET";
            var folderId         = ExisteFolder(nombreFolderPred);

            if (string.IsNullOrEmpty(folderId))
            {
                folderId = CrearFolder(nombreFolderPred);
            }

            var colNotas = new Dictionary <string, List <string> >();

            // Si no se indican las notas a guardar en Drive
            // se leerán las del fichero.
            if (lasNotas is null)
            {
                colNotas = LeerNotas();
            }
            else
            {
                colNotas = lasNotas;
            }

            var total = 0;

            foreach (var folderNotas in colNotas.Keys)
            {
                Console.WriteLine();
                var subFolderId = ExisteFolder(folderNotas);
                if (string.IsNullOrEmpty(subFolderId))
                {
                    subFolderId = CrearSubFolder(folderId, folderNotas);
                    //OnGuardandoNotas($"Se ha creado la subcarpeta con el ID: {subFolderId}");
                    OnGuardandoNotas($"Se ha creado la subcarpeta {folderNotas}");
                }
                //else
                //    OnGuardandoNotas($"Ya existe la subcarpeta {folderNotas}, tiene el ID: {subFolderId}");
                //Console.WriteLine();
                if (borrarAnt == "SI")
                {
                    OnGuardandoNotas($"Borrando los documentos de la carpeta '{folderNotas}'...");
                    //Console.WriteLine();
                    var docBorrados = EliminarDocumentos(folderNotas);
                    OnGuardandoNotas($"Se han eliminado {docBorrados} de '{folderNotas}'.");
                    //Console.WriteLine();
                }
                OnGuardandoNotas($"Guardando {colNotas[folderNotas].Count} notas en '{nombreFolderPred}\\{folderNotas}'...");
                var t = 0;
                foreach (var nota in colNotas[folderNotas])
                {
                    t++;
                    total++;
                    var sDoc   = $"{folderNotas}_{t:00000}.doc";
                    var fileId = CrearFile(subFolderId, sDoc, "application/vnd.google-apps.document");

                    Document gDoc = new Document();
                    gDoc.DocumentId = fileId;
                    gDoc.Title      = sDoc;

                    //Console.WriteLine();
                    //Console.WriteLine($"El documento se creará con el nombre: {gDoc.Title}");
                    //Console.WriteLine();

                    // Añadir el contenido
                    List <Request> requests = new List <Request>();
                    var            req      = new Request
                    {
                        InsertText = new InsertTextRequest
                        {
                            Location = new Location {
                                Index = 1
                            },
                            Text = nota
                        }
                    };

                    requests.Add(req);
                    req = new Request
                    {
                        // Asignar el tipo de fuente a Roboto Mono (o el que se indique)
                        UpdateTextStyle = new UpdateTextStyleRequest
                        {
                            TextStyle = new TextStyle
                            {
                                WeightedFontFamily = new WeightedFontFamily
                                {
                                    FontFamily = "Roboto Mono"
                                }
                            },
                            Fields = "*",
                            Range  = new Range {
                                StartIndex = 1, EndIndex = nota.Length
                            }
                        }
                    };

                    requests.Add(req);

                    BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();
                    body.Requests = requests;
                    var response = docService.Documents.BatchUpdate(body, gDoc.DocumentId).Execute();

                    //OnGuardandoNotas($"Documento creado con el ID: {response.DocumentId}");
                    OnGuardandoNotas($"Documento {gDoc.Title} creado.");
                }
            }
            OnGuardandoNotas($"Se han guardado {total} notas/documentos en Google Drive.");
            OnFinalizadoGuardarNotasEnDrive();

            return(total);
        }
Пример #9
0
        /// <summary>
        /// Guarda el contenido del fichero de notas de gsNotasNET en Drive como documentos.
        /// </summary>
        /// <param name="ficNotas">El path de las notas usadas por la aplicación.</param>
        /// <param name="borrarAnt">SI para borrar PERMANENTEMENTE los ficheros existentes o NO para no eliminarlos.</param>
        /// <returns>Devuelve el número de documentos (notas) creados.</returns>
        /// <remarks>Si se indica SI, los documentos se eliminarán permanentemente (no van a la papelera).</remarks>
        public static int GuardarNotasDrive(string ficNotas, string borrarAnt = "NO")
        {
            OnIniciadoGuardarNotasEnDrive();

            FicNotas = ficNotas;

            UserCredential credential;

            var credPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            credPath = System.IO.Path.Combine(credPath, ".credentials/gsNotasNET-2.0");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;

            //Console.WriteLine("Credential file saved to: " + credPath);

            // Create Google Docs API service.
            docService = new DocsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            var nombreFolderPred = "gsNotasNET";
            var folderId         = ExisteFolder(nombreFolderPred);

            if (string.IsNullOrEmpty(folderId))
            {
                folderId = CrearFolder(nombreFolderPred);
            }

            var colNotas = LeerNotas();
            var total    = 0;

            foreach (var folderNotas in colNotas.Keys)
            {
                Console.WriteLine();
                var subFolderId = ExisteFolder(folderNotas);
                if (string.IsNullOrEmpty(subFolderId))
                {
                    subFolderId = CrearSubFolder(folderId, folderNotas);
                    OnGuardandoNotas($"Se ha creado la subcarpeta con el ID: {subFolderId}");
                }
                else
                {
                    OnGuardandoNotas($"Ya existe la subcarpeta {folderNotas}, tiene el ID: {subFolderId}");
                }
                //Console.WriteLine();
                if (borrarAnt == "SI")
                {
                    OnGuardandoNotas($"Borrando los documentos de la carpeta '{folderNotas}'...");
                    //Console.WriteLine();
                    var docBorrados = EliminarDocumentos(folderNotas);
                    OnGuardandoNotas($"Se han eliminado {docBorrados} de '{folderNotas}'.");
                    //Console.WriteLine();
                }
                OnGuardandoNotas($"Guardando {colNotas[folderNotas].Count} notas en '{nombreFolderPred}\\{folderNotas}'...");
                var t = 0;
                foreach (var nota in colNotas[folderNotas])
                {
                    t++;
                    total++;
                    var sDoc   = $"{folderNotas}_{t:00000}.doc";
                    var fileId = CrearFile(subFolderId, sDoc, "application/vnd.google-apps.document");

                    Document gDoc = new Document();
                    gDoc.DocumentId = fileId;
                    gDoc.Title      = sDoc;

                    //Console.WriteLine();
                    //Console.WriteLine($"El documento se creará con el nombre: {gDoc.Title}");
                    //Console.WriteLine();

                    // Añadir el contenido
                    List <Request> requests = new List <Request>();
                    var            req      = new Request
                    {
                        InsertText = new InsertTextRequest
                        {
                            Location = new Location {
                                Index = 1
                            },
                            Text = nota
                        }
                    };

                    requests.Add(req);
                    req = new Request
                    {
                        // Asignar el tipo de fuente a Roboto Mono (o el que se indique)
                        UpdateTextStyle = new UpdateTextStyleRequest
                        {
                            TextStyle = new TextStyle
                            {
                                WeightedFontFamily = new WeightedFontFamily
                                {
                                    FontFamily = "Roboto Mono"
                                }
                            },
                            Fields = "*",
                            Range  = new Range {
                                StartIndex = 1, EndIndex = nota.Length
                            }
                        }
                    };

                    requests.Add(req);

                    BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();
                    body.Requests = requests;
                    var response = docService.Documents.BatchUpdate(body, gDoc.DocumentId).Execute();

                    OnGuardandoNotas($"Documento creado con el ID: {response.DocumentId}");
                }
            }
            OnGuardandoNotas($"Se han guardado {total} notas/documentos en Google Drive.");
            OnFinalizadoGuardarNotasEnDrive();
            return(total);
        }