Beispiel #1
0
        private static EventHandler <Realms.ErrorEventArgs> HandlerRealmSyncErrors(Uri realmDatabaseUri)
        {
            return(async(s, errorArgs) =>
            {
                var sessionException = (SessionException)errorArgs.Exception;

                if (sessionException.ErrorCode.IsClientResetError())
                {
                    Analytics.TrackEvent("Realm client reset");

                    DeleteOnlineRealm(realmDatabaseUri);
                    await RealmHelpers.RemoveCachedUsers();

                    return;
                }

                switch (sessionException.ErrorCode)
                {
                case ErrorCode.AccessTokenExpired:
                case ErrorCode.BadUserAuthentication:
                case ErrorCode.PermissionDenied:
                    await RealmHelpers.RemoveCachedUsers();

                    break;
                }

                Crashes.TrackError(sessionException, new Dictionary <string, string> {
                    { "ErrorType", sessionException.ErrorCode.ToString() },
                    { "Realm fatal error", "unknown" },
                    { "Error description", $"Realm sync error reported by realm. See {sessionException.Message}" }
                });
            });
        }
Beispiel #2
0
        public static async Task InitializeCloudSync(string realmServer, string realmDatabase)
        {
            Console.WriteLine("Initialize cloud sync");

            var realmDatabaseUrl = new Uri($"realms://{realmServer}/{realmDatabase}");

            var shouldCleanOnlineRealm = VersionTracking.IsFirstLaunchForCurrentBuild;

#if DEBUG
            shouldCleanOnlineRealm = true;
#endif
            if (shouldCleanOnlineRealm)
            {
                DeleteOnlineRealm(realmDatabaseUrl);
                try
                {
                    await RealmHelpers.RemoveCachedUsers();
                }
                catch (Exception e)
                {
                    Crashes.TrackError(e, new Dictionary <string, string>
                    {
                        { "Realm fatal error", "false" },
                        { "Error description", $"Failed to remove cached users. See {e.Message}" }
                    });
                }
            }

            Realms.Sync.Session.Error      += HandlerRealmSyncErrors(realmDatabaseUrl);
            SyncConfigurationBase.UserAgent = $"{AppInfo.Name} ({AppInfo.PackageName} {AppInfo.VersionString})";

            var realmServerUri = new Uri($"https://{realmServer}");
            OnlineRealm = await GetCloudRealm(realmServerUri, realmDatabaseUrl);
        }
Beispiel #3
0
        /// <summary>
        /// Tries to remove a media item from the store
        /// </summary>
        /// <param name="item">The item to remove</param>
        /// <returns>A value indicating whether or not the operation was successful</returns>
        public async Task <bool> TryRemoveMediaAsync(Media item)
        {
            // Check that the file to import exists
            if (!File.Exists(item.FilePath) || !File.Exists(item.ThumbPath))
            {
                Log.Information("Remove - Could not find the file to remove: {id}", item.Id);
                ShowErrorDialog("An error occured while removing the file");
                return(false);
            }

            try
            {
                string filePath  = item.FilePath;
                string thumbPath = item.ThumbPath;
                int    id        = item.Id;
                await Task.Run(() =>
                {
                    File.Delete(filePath);
                    File.Delete(thumbPath);
                }).ConfigureAwait(true);

                Realm realm = RealmHelpers.GetRealmInstance();
                await realm.WriteAsync((r) => r.Remove(r.All <Media>().First(m => m.Id == id))).ConfigureAwait(true);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error removing file");
                ShowErrorDialog("An error occured while removing the file");
                return(false);
            }
        }
Beispiel #4
0
        public ImageDisplayView()
        {
            InitializeComponent();
            _realmInstance   = RealmHelpers.GetRealmInstance();
            _userPreferences = RealmHelpers.GetUserPreferences(_realmInstance);

            SldrThumbnailSize.Value = _userPreferences.ImageThumbnailSize;
        }
Beispiel #5
0
        public HubView()
        {
            InitializeComponent();
            _realmInstance   = RealmHelpers.GetRealmInstance();
            _userPreferences = RealmHelpers.GetUserPreferences(_realmInstance);

            if (_userPreferences.DarkModeEnabled)
            {
                EnableDarkMode(this, null);
                TglBtnDarkMode.IsChecked = true;
            }
        }
Beispiel #6
0
        public static async Task <Realm> GetCloudRealm(Uri realmServerUri, Uri realmDatabaseUri)
        {
            User user;

            try
            {
                user = await RealmHelpers.GetRealmUser(realmServerUri);
            }
            catch (Exception e)
            {
                Crashes.TrackError(e, new Dictionary <string, string>
                {
                    { "Realm fatal error", "true" },
                    { "Error description", $"Failed to create realm user. See {e.Message}" }
                });
                return(null);
            }

            try
            {
                var syncConfiguration = new FullSyncConfiguration(realmDatabaseUri, user);

                var cloudRealm = await OpenCloudRealm(syncConfiguration);

                if (cloudRealm != null)
                {
                    RealmSyncManager.UpdateRealm(cloudRealm, OfflineRealm);

                    cloudRealm.Error += (s, e) =>
                    {
                        Crashes.TrackError(e.Exception, new Dictionary <string, string>
                        {
                            { "Realm fatal error", "unknown" },
                            { "Error description", $"Some error reported by online realm. See {e.Exception?.Message}" }
                        });
                    };

                    cloudRealm.RealmChanged += (s, e) =>
                    {
                        try
                        {
                            RealmSyncManager.UpdateRealm(cloudRealm, OfflineRealm);
                        }
                        catch (Exception ex)
                        {
                            Crashes.TrackError(ex, new Dictionary <string, string>
                            {
                                { "Realm fatal error", "true" },
                                { "Error description", $"Failed to update offline realm. See {ex.Message}" }
                            });
                        }
                    };
                }

                return(cloudRealm);
            }
            catch (Exception e)
            {
                Crashes.TrackError(e, new Dictionary <string, string>
                {
                    { "Realm fatal error", "unknown" },
                    { "Error description", $"Error on getting cloud realm. See {e.Message}" }
                });
                return(null);
            }
        }
Beispiel #7
0
        public async Task <Media> TryImportImageAsync(string path)
        {
            AesHmacEncryptor encryptor = EncryptorAssistant.GetEncryptor();
            Media            media     = null;

            bool success = await Task.Run(() =>
            {
                // Check that the image store folder exists, and try to create one if not
                if (!CheckDirectoryExists(IMAGE_FOLDER_PATH))
                {
                    return(false);
                }

                // Check that the file to import exists
                if (!File.Exists(path))
                {
                    Log.Information("Import - Could not locate the image to import");
                    ShowErrorDialog("Could not locate the file to import. Please check it is not being used by any other programs");
                    return(false);
                }

                string errMessage = string.Empty;
                try
                {
                    // Create the new media store
                    int id = RealmHelpers.GetNextId <Media>();
                    media  = new Media(id, MediaType.Image)
                    {
                        FilePath  = GetFilePath(IMAGE_FOLDER_PATH, id),
                        Name      = Path.GetFileName(path),
                        ThumbPath = GetThumbPath(IMAGE_FOLDER_PATH, id)
                    };

                    // Load, encrypt and save the file and thumbnail
                    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                        using (FileStream imageOutput = new FileStream(media.FilePath, FileMode.CreateNew, FileAccess.ReadWrite))
                            using (FileStream thumbOutput = new FileStream(media.ThumbPath, FileMode.CreateNew, FileAccess.ReadWrite))
                                using (Image image = Image.Load(fs))
                                    using (MemoryStream imageStore = new MemoryStream())
                                        using (MemoryStream thumbStore = new MemoryStream())
                                        {
                                            // Find the thumbnail scalar
                                            double scalar;
                                            if (image.Width < image.Height)
                                            {
                                                scalar = MAX_THUMB_SIZE / image.Height;
                                            }
                                            else
                                            {
                                                scalar = MAX_THUMB_SIZE / image.Width;
                                            }

                                            // Save the image as a PNG
                                            image.SaveAsPng(imageStore);
                                            imageStore.Position = 0;
                                            encryptor.EncryptAsync(imageStore, imageOutput);

                                            // Mutate and encrypt the thumbnail
                                            image.Mutate(x => x.Resize((int)(image.Width * scalar), (int)(image.Height * scalar)));
                                            image.SaveAsPng(thumbStore);
                                            thumbStore.Position = 0;
                                            encryptor.EncryptAsync(thumbStore, thumbOutput).Wait();
                                        }
                }
                catch (FileNotFoundException fnfex)
                {
                    errMessage = "Could not locate the file to import. Please try again!";
                    App.LogError("Error importing image", fnfex);
                }
                catch (UnauthorizedAccessException uaex)
                {
                    errMessage = "You don't have access to that file, sorry!";
                    App.LogError("Error importing image", uaex);
                }
                catch (Exception ex)
                {
                    errMessage = "An error occured while importing. Please try again!";
                    App.LogError("Error importing image", ex);
                }

                if (!string.IsNullOrEmpty(errMessage))
                {
                    ShowErrorDialog(errMessage);
                    return(false);
                }
                else
                {
                    return(true);
                }
            }).ConfigureAwait(true);

            // Add the media to the realm if required
            if (success)
            {
                Realm realm = RealmHelpers.GetRealmInstance();
                await realm.WriteAsync((r) => r.Add(media)).ConfigureAwait(true);

                return(media);
            }
            else
            {
                return(null);
            }
        }