예제 #1
0
        public static void BackupEverything([NotNull] CerebelloEntities db, List <string> errors = null)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }
            if (errors == null)
            {
                errors = new List <string>();
            }

            using (db)
            {
                var dbWrapper        = new CerebelloEntitiesAccessFilterWrapper(db);
                var patientsToBackup = db.Patients.Where(p => p.Doctor.Users.Any(u => u.Person.GoogleUserAccoutInfoes.Any()) && !p.IsBackedUp).GroupBy(p => p.DoctorId);
                foreach (var patientGroup in patientsToBackup.ToList())
                {
                    try
                    {
                        var doctor = db.Doctors.First(d => d.Id == patientGroup.Key);
                        dbWrapper.SetCurrentUserById(doctor.Users.First().Id);
                        var doctorGoogleAccountInfo = doctor.Users.First().Person.GoogleUserAccoutInfoes.FirstOrDefault();
                        if (doctorGoogleAccountInfo != null)
                        {
                            // in this case the doctor for these patients have a Google Account associated
                            var requestAccessResult = GoogleApiHelper.RequestAccessToken(doctorGoogleAccountInfo.RefreshToken);
                            var authenticator       = GoogleApiHelper.GetAuthenticator(
                                doctorGoogleAccountInfo.RefreshToken, requestAccessResult.access_token);
                            var driveService = new DriveService(authenticator);

                            // create Cerebello folder if it does not exist
                            var  practiceGoogleDriveInfo = doctor.Practice.GoogleDrivePracticeInfoes.FirstOrDefault();
                            File cerebelloFolder         = null;
                            if (practiceGoogleDriveInfo != null)
                            {
                                try
                                {
                                    cerebelloFolder = GoogleApiHelper.GetFile(driveService, practiceGoogleDriveInfo.CerebelloFolderId);
                                    if (cerebelloFolder.Labels.Trashed.HasValue && cerebelloFolder.Labels.Trashed.Value)
                                    {
                                        cerebelloFolder = null;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var errorMessage = "Error downloading file from Google Drive. Exception message: " + ex.Message;
                                    // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                                    Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                                    errors.Add(errorMessage);
                                }
                            }
                            if (cerebelloFolder == null)
                            {
                                cerebelloFolder = GoogleApiHelper.CreateFolder(driveService, "Cerebello", "Pasta do Cerebello");
                                if (practiceGoogleDriveInfo != null)
                                {
                                    practiceGoogleDriveInfo.CerebelloFolderId = cerebelloFolder.Id;
                                }
                                else
                                {
                                    practiceGoogleDriveInfo = new GoogleDrivePracticeInfo()
                                    {
                                        CerebelloFolderId = cerebelloFolder.Id,
                                        PracticeId        = doctor.PracticeId
                                    };
                                    doctor.Practice.GoogleDrivePracticeInfoes.Add(practiceGoogleDriveInfo);
                                }
                                db.SaveChanges();
                            }

                            foreach (var patient in patientGroup)
                            {
                                try
                                {
                                    var patientBackup   = GeneratePatientBackup(dbWrapper, patient);
                                    var fileName        = string.Format("{0} (id:{1})", patient.Person.FullName, patient.Id) + ".zip";
                                    var fileDescription = string.Format(
                                        "Arquivo de backup do(a) paciente {0} (id:{1})", patient.Person.FullName, patient.Id);

                                    // check if the file exists already
                                    var  patientGoogleDriveFile = patient.GoogleDrivePatientInfoes.FirstOrDefault();
                                    File googleDrivePatientFile = null;
                                    if (patientGoogleDriveFile != null)
                                    {
                                        try
                                        {
                                            // get reference to existing file to make sure it exists
                                            var existingFile = GoogleApiHelper.GetFile(
                                                driveService, patientGoogleDriveFile.PatientBackupFileId);
                                            if (!existingFile.Labels.Trashed.HasValue || !existingFile.Labels.Trashed.Value)
                                            {
                                                googleDrivePatientFile = GoogleApiHelper.UpdateFile(
                                                    driveService,
                                                    patientGoogleDriveFile.PatientBackupFileId,
                                                    fileName,
                                                    fileDescription,
                                                    MimeTypesHelper.GetContentType(".zip"),
                                                    patientBackup);
                                                if (googleDrivePatientFile.Labels.Trashed.HasValue && googleDrivePatientFile.Labels.Trashed.Value)
                                                {
                                                    googleDrivePatientFile = null;
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            var errorMessage = "Error updating file from Google Drive. Exception message: " + ex.Message;
                                            // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                                            Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                                            errors.Add(errorMessage);
                                        }
                                    }

                                    if (googleDrivePatientFile == null)
                                    {
                                        googleDrivePatientFile = GoogleApiHelper.CreateFile(
                                            driveService,
                                            fileName,
                                            fileDescription,
                                            MimeTypesHelper.GetContentType(".zip"),
                                            patientBackup,
                                            new List <ParentReference>()
                                        {
                                            new ParentReference()
                                            {
                                                Id = cerebelloFolder.Id
                                            }
                                        });

                                        if (patientGoogleDriveFile != null)
                                        {
                                            patientGoogleDriveFile.PatientBackupFileId = googleDrivePatientFile.Id;
                                        }
                                        else
                                        {
                                            patient.GoogleDrivePatientInfoes.Add(
                                                new GoogleDrivePatientInfo()
                                            {
                                                PatientBackupFileId = googleDrivePatientFile.Id,
                                                PracticeId          = doctor.PracticeId
                                            });
                                        }
                                    }
                                    patient.IsBackedUp = true;
                                    db.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    var errorMessage = "Error synchronizing files for a specific doctor. Exception message" + ex.Message;
                                    // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                                    Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                                    errors.Add(errorMessage);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = "Error synchronizing files. Exception message" + ex.Message;
                        // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                        Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                        errors.Add(errorMessage);
                    }
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Creates a thumbnail image of a file in the storage.
        /// </summary>
        /// <param name="originalMetadataId">Metadata entry ID for the original image file.</param>
        /// <param name="maxWidth">Maximum width of the thumbnail image.</param>
        /// <param name="maxHeight">Maximum height of the thumbnail image.</param>
        /// <param name="sourceFullStorageFileName">Name of the source image file.</param>
        /// <param name="thumbFullStorageFileName">Name of the thumbnail image cache file.</param>
        /// <param name="loadFromCache">Whether to use a cached thumbnail or not.</param>
        /// <param name="storage">Storage service used to get file data.</param>
        /// <param name="fileMetadataProvider">File metadata provider used to create thumbnail image metadata.</param>
        /// <returns>Returns the result of the thumbnail creation process.</returns>
        public static CreateThumbResult TryGetOrCreateThumb(
            int originalMetadataId,
            int maxWidth,
            int maxHeight,
            string sourceFullStorageFileName,
            string thumbFullStorageFileName,
            bool loadFromCache,
            IBlobStorageManager storage,
            IFileMetadataProvider fileMetadataProvider)
        {
            var srcBlobLocation   = new BlobLocation(sourceFullStorageFileName);
            var thumbBlobLocation = new BlobLocation(thumbFullStorageFileName);

            if (loadFromCache && !string.IsNullOrEmpty(thumbFullStorageFileName))
            {
                var thumbStream = storage.DownloadFileFromStorage(thumbBlobLocation);
                if (thumbStream != null)
                {
                    using (thumbStream)
                        using (var stream = new MemoryStream((int)thumbStream.Length))
                        {
                            thumbStream.CopyTo(stream);
                            {
                                return(new CreateThumbResult(
                                           CreateThumbStatus.Ok,
                                           stream.ToArray(),
                                           MimeTypesHelper.GetContentType(Path.GetExtension(thumbFullStorageFileName))));
                            }
                        }
                }
            }

            if (!StringHelper.IsImageFileName(sourceFullStorageFileName))
            {
                return(new CreateThumbResult(CreateThumbStatus.SourceIsNotImage, null, null));
            }

            var srcStream = storage.DownloadFileFromStorage(srcBlobLocation);

            if (srcStream == null)
            {
                return(new CreateThumbResult(CreateThumbStatus.SourceFileNotFound, null, null));
            }

            string contentType;

            byte[] array;
            using (srcStream)
                using (var srcImage = Image.FromStream(srcStream))
                {
                    var imageSizeMegabytes = srcImage.Width * srcImage.Height * 4 / 1024000.0;
                    if (imageSizeMegabytes > 40.0)
                    {
                        return(new CreateThumbResult(CreateThumbStatus.SourceImageTooLarge, null, null));
                    }

                    using (var newImage = ResizeImage(srcImage, maxWidth, maxHeight, keepAspect: true, canGrow: false))
                        using (var newStream = new MemoryStream())
                        {
                            if (newImage == null)
                            {
                                srcStream.Position = 0;
                                srcStream.CopyTo(newStream);
                                contentType = MimeTypesHelper.GetContentType(Path.GetExtension(sourceFullStorageFileName));
                            }
                            else
                            {
                                var imageFormat = (newImage.Width * newImage.Height > 10000)
                            ? ImageFormat.Jpeg
                            : ImageFormat.Png;

                                contentType = (newImage.Width * newImage.Height > 10000)
                            ? "image/jpeg"
                            : "image/png";

                                newImage.Save(newStream, imageFormat);
                            }

                            array = newStream.ToArray();

                            if (loadFromCache && newImage != null && !string.IsNullOrEmpty(thumbFullStorageFileName))
                            {
                                // saving thumbnail image file metadata
                                var relationType = string.Format("thumb-{0}x{1}", maxWidth, maxHeight);
                                var metadata     = fileMetadataProvider.CreateRelated(
                                    originalMetadataId,
                                    relationType,
                                    thumbBlobLocation.ContainerName,
                                    thumbBlobLocation.FileName,
                                    thumbBlobLocation.BlobName,
                                    null);

                                fileMetadataProvider.SaveChanges();

                                storage.UploadFileToStorage(new MemoryStream(array), thumbBlobLocation);
                            }
                        }
                }

            return(new CreateThumbResult(CreateThumbStatus.Ok, array, contentType));
        }