Ejemplo n.º 1
0
        /// <summary>
        /// Gets the user avatar
        /// </summary>
        public static async void GetUserAvatar()
        {
            var userAvatarRequestListener = new GetUserAvatarRequestListenerAsync();
            var userAvatarResult          = await userAvatarRequestListener.ExecuteAsync(() =>
                                                                                         SdkService.MegaSdk.getOwnUserAvatar(UserData.AvatarPath, userAvatarRequestListener));

            if (userAvatarResult && UserData?.AvatarPath != null)
            {
                UiService.OnUiThread(() =>
                {
                    var img = new BitmapImage()
                    {
                        CreateOptions = BitmapCreateOptions.IgnoreImageCache,
                        UriSource     = new Uri(UserData.AvatarPath)
                    };
                    UserData.AvatarUri = img.UriSource;
                });
            }
            else
            {
                LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error getting user avatar");
                UiService.OnUiThread(() => UserData.AvatarUri = null);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Save the unique receipt id to local user settings
        /// </summary>
        /// <param name="receipt">Windows Store receipt xml</param>
        /// <returns>True if save succeeded, else False</returns>
        private static bool SaveUniqueReceiptId(string receipt)
        {
            try
            {
                var key        = ResourceService.SettingsResources.GetString("SR_Receipts");
                var currentIds = SettingsService.Load(key, string.Empty);
                var id         = GetUniqueReceiptId(receipt);

                if (id == null)
                {
                    return(false);
                }

                currentIds += id + ";";
                SettingsService.Save(key, currentIds);

                return(true);
            }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Failed to save receipt ID", e);
                return(false);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initialize all the SDK parameters
        /// </summary>
        public static void InitializeSdkParams()
        {
            //The next line enables a custom logger, if this function is not used OutputDebugString() is called
            //in the native library and log messages are only readable with the native debugger attached.
            //The default behavior of MegaLogger() is to print logs using Debug.WriteLine() but it could
            //be used to sends log to a file, for example.
            LogService.AddLoggerObject(LogService.MegaLogger);

            //You can select the maximum output level for debug messages.
            //By default FATAL, ERROR, WARNING and INFO will be enabled
            //DEBUG and MAX can only be enabled in Debug builds, they are ignored in Release builds
            MegaSDK.setLogLevel(MLogLevel.LOG_LEVEL_DEBUG);

            //You can send messages to the logger using MEGASDK.log(), those messages will be received
            //in the active logger
            LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Example log message");

            // Set the ID for statistics
            MegaSDK.setStatsID(DeviceService.GetDeviceId());

            // Set the language code used by the app
            var appLanguageCode = AppService.GetAppLanguageCode();

            if (!MegaSdk.setLanguage(appLanguageCode) || !MegaSdkFolderLinks.setLanguage(appLanguageCode))
            {
                LogService.Log(MLogLevel.LOG_LEVEL_WARNING,
                               string.Format("Invalid app language code '{0}'", appLanguageCode));
            }

            // Change the API URL if required by settings
            if (SettingsService.Load(ResourceService.SettingsResources.GetString("SR_UseStagingServer"), false))
            {
                MegaSdk.changeApiUrl(ResourceService.AppResources.GetString("AR_StagingUrl"));
                MegaSdkFolderLinks.changeApiUrl(ResourceService.AppResources.GetString("AR_StagingUrl"));
            }
        }
Ejemplo n.º 4
0
        public static ulong GetAppCacheSize()
        {
            var files = new List <string>();

            try { files.AddRange(Directory.GetFiles(GetThumbnailDirectoryPath())); }
            catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error getting thumbnails cache.", e); }

            try { files.AddRange(Directory.GetFiles(GetPreviewDirectoryPath())); }
            catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error getting previews cache.", e); }

            try { files.AddRange(Directory.GetFiles(GetUploadDirectoryPath())); }
            catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error getting uploads cache.", e); }

            try { files.AddRange(GetDownloadDirectoryFiles(GetDownloadDirectoryPath())); }
            catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error getting uploads cache.", e); }

            ulong totalSize = 0;

            foreach (var file in files)
            {
                if (FileService.FileExists(file))
                {
                    try
                    {
                        var fileInfo = new FileInfo(file);
                        totalSize += (ulong)fileInfo.Length;
                    }
                    catch (Exception e)
                    {
                        LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error getting app cache size.", e);
                    }
                }
            }

            return(totalSize);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initialize all the SDK parameters
        /// </summary>
        public static void InitializeSdkParams()
        {
            //The next line enables a custom logger, if this function is not used OutputDebugString() is called
            //in the native library and log messages are only readable with the native debugger attached.
            //The default behavior of MegaLogger() is to print logs using Debug.WriteLine() but it could
            //be used to sends log to a file, for example.
            LogService.AddLoggerObject(LogService.MegaLogger);

            //You can select the maximum output level for debug messages.
            //By default FATAL, ERROR, WARNING and INFO will be enabled
            //DEBUG and MAX can only be enabled in Debug builds, they are ignored in Release builds
            MegaSDK.setLogLevel(MLogLevel.LOG_LEVEL_DEBUG);

            //You can send messages to the logger using MEGASDK.log(), those messages will be received
            //in the active logger
            LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Example log message");

            // Set the ID for statistics
            try
            {
                MegaSDK.setStatsID(Convert.ToBase64String((byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId")));
            }
            catch (NotSupportedException e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error setting the device unique ID for statistics", e);
            }

            // Set the language code used by the app
            var appLanguageCode = AppService.GetAppLanguageCode();

            if (!MegaSdk.setLanguage(appLanguageCode))
            {
                LogService.Log(MLogLevel.LOG_LEVEL_WARNING,
                               string.Format("Invalid app language code '{0}'", appLanguageCode));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Purchase a MEGA product/subscription
        /// </summary>
        /// <param name="product">MEGA product/subscription/plan</param>
        public static async Task PurchaseProduct(Product product)
        {
            try
            {
                if (product == null)
                {
                    throw new ArgumentNullException("product");
                }

                var products = await GetProducts();

                if (products == null || !products.Any())
                {
                    throw new Exception("Failed to retrieve products");
                }

                switch (product.AccountType)
                {
                case MAccountType.ACCOUNT_TYPE_PROI:
                    switch (product.Months)
                    {
                    case 1:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.Pro1Month)).Value.ProductId);

                        break;

                    case 12:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.Pro1Year)).Value.ProductId);

                        break;
                    }
                    break;

                case MAccountType.ACCOUNT_TYPE_PROII:
                    switch (product.Months)
                    {
                    case 1:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.Pro2Month)).Value.ProductId);

                        break;

                    case 12:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.Pro2Year)).Value.ProductId);

                        break;
                    }
                    break;

                case MAccountType.ACCOUNT_TYPE_PROIII:
                    switch (product.Months)
                    {
                    case 1:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.Pro3Month)).Value.ProductId);

                        break;

                    case 12:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.Pro3Year)).Value.ProductId);

                        break;
                    }
                    break;

                case MAccountType.ACCOUNT_TYPE_LITE:
                    switch (product.Months)
                    {
                    case 1:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.ProLiteMonth)).Value.ProductId);

                        break;

                    case 12:
                        await PurchaseProduct(products.First(p => p.Key.Equals(AppResources.ProLiteYear)).Value.ProductId);

                        break;
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Failure purchasing product", e);
                new CustomMessageDialog(
                    AppMessages.AM_PurchaseFailed_Title,
                    AppMessages.AM_PurchaseFailed,
                    App.AppInformation).ShowDialog();
            }
        }
Ejemplo n.º 7
0
        public static bool SetAutoCameraUpload(bool onOff)
        {
            var resourceIntensiveTask = ScheduledActionService.Find("ScheduledCameraUploadTaskAgent") as ResourceIntensiveTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update
            // the schedule.
            if (resourceIntensiveTask != null)
            {
                try
                {
                    ScheduledActionService.Remove("ScheduledCameraUploadTaskAgent");
                }
                catch (InvalidOperationException e)
                {
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error disabling CAMERA UPLOADS service", e);
                    return(false);
                }
            }

            if (!onOff)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Disable CAMERA UPLOADS service");
                return(false);
            }

            resourceIntensiveTask = new ResourceIntensiveTask("ScheduledCameraUploadTaskAgent")
            {
                // The description is required for periodic agents. This is the string that the user
                // will see in the background services Settings page on the device.
                Description = AppMessages.ResourceIntensiveTaskDescription
            };

            // Place the call to Add in a try block in case the user has disabled agents.
            Exception exception;

            try
            {
                ScheduledActionService.Add(resourceIntensiveTask);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
                #if DEBUG
                ScheduledActionService.LaunchForTest("ScheduledCameraUploadTaskAgent", TimeSpan.FromSeconds(5));
                #endif

                LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Enable CAMERA UPLOADS service");
                return(true);
            }
            catch (InvalidOperationException e)
            {
                exception = e;
                if (e.Message.Contains("BNS Error: The action is disabled"))
                {
                    new CustomMessageDialog(AppMessages.BackgroundAgentDisabled_Title,
                                            AppMessages.BackgroundAgentDisabled, App.AppInformation).ShowDialog();
                }
            }
            catch (SchedulerServiceException e) { exception = e; }
            catch (ArgumentException e) { exception = e; }

            LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error enabling CAMERA UPLOADS service", exception);
            return(false);
        }
Ejemplo n.º 8
0
        public static async void GetAccountAchievements()
        {
            UiService.OnUiThread(() =>
                                 AccountAchievements.IsAchievementsEnabled = SdkService.MegaSdk.isAchievementsEnabled());

            if (!SdkService.MegaSdk.isAchievementsEnabled())
            {
                return;
            }

            var accountAchievementsRequestListener = new GetAccountAchievementsRequestListenerAsync();
            var accountAchievements = await accountAchievementsRequestListener.ExecuteAsync(() =>
            {
                SdkService.MegaSdk.getAccountAchievements(accountAchievementsRequestListener);
            });

            if (accountAchievements == null)
            {
                return;
            }

            var awards = new List <AwardClassViewModel>
            {
                // Add Base storage & transfer
                new AwardClassViewModel(null, true)
                {
                    StorageReward = accountAchievements.getBaseStorage(),
                }
            };

            var awardedClasses = new List <AwardClassViewModel>
            {
                // Add Base storage & transfer
                new AwardClassViewModel(null, true)
                {
                    StorageReward           = accountAchievements.getBaseStorage(),
                    IsTransferAmountVisible = false,
                }
            };


            // Get all the user awards
            var awardsCount = accountAchievements.getAwardsCount();

            for (uint i = 0; i < awardsCount; i++)
            {
                var awardId    = accountAchievements.getAwardId(i);
                var awardClass = (MAchievementClass)accountAchievements.getAwardClass(i);

                var awardedClass = awardedClasses.FirstOrDefault(a => a.AchievementClass == awardClass);
                if (awardedClass == null)
                {
                    awardedClass = new AwardClassViewModel(awardClass)
                    {
                        IsGranted = true
                    };
                    awardedClasses.Add(awardedClass);
                }

                var storageReward  = accountAchievements.getRewardStorageByAwardId(awardId);
                var transferReward = accountAchievements.getRewardTransferByAwardId(awardId);
                var expireDate     = accountAchievements.getAwardExpirationTs(i).ConvertTimestampToDateTime();
                var achievedOnDate = accountAchievements.getAwardTimestamp(i).ConvertTimestampToDateTime();
                var durationInDays = accountAchievements.getClassExpire((int)awardClass);
                awards.Add(new AwardClassViewModel(awardClass)
                {
                    StorageReward  = storageReward,
                    TransferReward = transferReward,
                    ExpireDate     = expireDate,
                    AchievedOnDate = achievedOnDate,
                    DurationInDays = durationInDays,
                    IsGranted      = true
                });


                if (awardClass == MAchievementClass.MEGA_ACHIEVEMENT_INVITE)
                {
                    var mails    = accountAchievements.getAwardEmails(i);
                    var mailSize = mails.size();
                    for (int m = 0; m < mailSize; m++)
                    {
                        var megaUser = SdkService.MegaSdk.getContact(mails.get(m));
                        if (megaUser == null)
                        {
                            LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "'MUser' of contact is NULL");
                            continue;
                        }

                        var contact = new ContactViewModel(megaUser, awardedClass.Contacts)
                        {
                            StorageAmount           = storageReward,
                            TransferAmount          = transferReward,
                            ReferralBonusExpireDate = expireDate,
                        };
                        awardedClass.Contacts.ItemCollection.Items.Add(contact);
                        contact.GetContactFirstname();
                        contact.GetContactLastname();
                        contact.GetContactAvatarColor();
                        contact.GetContactAvatar();
                    }

                    if (expireDate <= DateTime.Now)
                    {
                        continue;
                    }

                    awardedClass.StorageReward  += storageReward;
                    awardedClass.TransferReward += transferReward;
                }
                else
                {
                    awardedClass.ExpireDate     = expireDate;
                    awardedClass.StorageReward  = storageReward;
                    awardedClass.TransferReward = transferReward;
                    awardedClass.AchievedOnDate = achievedOnDate;
                    awardedClass.DurationInDays = durationInDays;
                }
            }

            var awardClasses    = Enum.GetValues(typeof(MAchievementClass)).OfType <MAchievementClass>();
            var availableAwards = new List <AwardClassViewModel>();

            foreach (var awardClass in awardClasses)
            {
                switch (awardClass)
                {
                case MAchievementClass.MEGA_ACHIEVEMENT_WELCOME:
                    continue;

                case MAchievementClass.MEGA_ACHIEVEMENT_INVITE:
                {
                    var inviteClass = new AwardClassViewModel(awardClass)
                    {
                        StorageReward  = accountAchievements.getClassStorage((int)awardClass),
                        TransferReward = accountAchievements.getClassTransfer((int)awardClass),
                        DurationInDays = accountAchievements.getClassExpire((int)awardClass),
                    };

                    inviteClass.Contacts.ItemCollection.Items =
                        awardedClasses.FirstOrDefault(a => a.AchievementClass == awardClass)?.Contacts.ItemCollection.Items;
                    availableAwards.Add(inviteClass);

                    continue;
                };
                }

                var available = awards.FirstOrDefault(a => a.AchievementClass == awardClass);

                if (available != null)
                {
                    continue;
                }

                availableAwards.Add(new AwardClassViewModel(awardClass)
                {
                    StorageReward  = accountAchievements.getClassStorage((int)awardClass),
                    TransferReward = accountAchievements.getClassTransfer((int)awardClass),
                    DurationInDays = accountAchievements.getClassExpire((int)awardClass)
                });
            }

            UiService.OnUiThread(() =>
            {
                if (accountAchievements.currentStorage() != -1)
                {
                    AccountAchievements.CurrentStorageQuota = (ulong)accountAchievements.currentStorage();
                }

                if (accountAchievements.currentTransfer() != -1)
                {
                    AccountAchievements.CurrentTransferQuota = (ulong)accountAchievements.currentTransfer();
                }

                AccountAchievements.Awards          = awards;
                AccountAchievements.AwardedClasses  = awardedClasses;
                AccountAchievements.AvailableAwards = availableAwards;
                AccountAchievements.CompletedAwards = awardedClasses.Where(a => a.IsGranted).ToList();
            });
        }
Ejemplo n.º 9
0
        public static async Task <PurchaseResponse> PurchaseProductAsync(string productId)
        {
            var purchaseReponse = new PurchaseResponse();

            // Check product id argument
            if (string.IsNullOrEmpty(productId))
            {
                purchaseReponse.Type = PurchaseResponseType.PurchaseFailed;
                return(purchaseReponse);
            }

            // Check if Windows Store product list is available
            var available = await GetIsAvailableAsync();

            if (!available)
            {
                purchaseReponse.Type = PurchaseResponseType.UnAvailable;
                return(purchaseReponse);
            }

            // Check if the user has already purchased the Windows Store product
            if (CurrentLicenseInformation.ProductLicenses[productId].IsActive)
            {
                purchaseReponse.Type = PurchaseResponseType.AlreadyPurchased;
                return(purchaseReponse);
            }

            // Check if product exists in the Windows Store
            var listing = await GetListingInformationAsync();

            if (!listing.ProductListings.ContainsKey(productId))
            {
                purchaseReponse.Type = PurchaseResponseType.UnAvailable;
                return(purchaseReponse);
            }

            try
            {
                // The actual purchase
#if DEBUG
                purchaseReponse.Result = await CurrentAppSimulator.RequestProductPurchaseAsync(productId);
#else
                purchaseReponse.Result = await CurrentApp.RequestProductPurchaseAsync(productId);
#endif
                switch (purchaseReponse.Result.Status)
                {
                case ProductPurchaseStatus.Succeeded:
                    purchaseReponse.Type = PurchaseResponseType.Succeeded;
                    break;

                case ProductPurchaseStatus.AlreadyPurchased:
                    purchaseReponse.Type = PurchaseResponseType.AlreadyPurchased;
                    break;

                case ProductPurchaseStatus.NotFulfilled:
                case ProductPurchaseStatus.NotPurchased:
                    purchaseReponse.Type = PurchaseResponseType.PurchaseFailed;
                    break;

                default:
                    purchaseReponse.Type = PurchaseResponseType.PurchaseFailed;
                    break;
                }

                return(purchaseReponse);
            }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, $"Failure purchasing product {productId}", e);
                purchaseReponse.Type = PurchaseResponseType.PurchaseFailed;
                return(purchaseReponse);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Checks if need to navigate to a page depending on the current state or the active link.
        /// </summary>
        /// <param name="hasActiveAndOnlineSession">
        /// Bool value that indicates if the user has an active and online session.
        /// </param>
        /// <returns>NULL if no active link, TRUE if navigates or FALSE in other case.</returns>
        public static async Task <bool?> CheckSpecialNavigation(bool hasActiveAndOnlineSession)
        {
            if (string.IsNullOrWhiteSpace(LinkInformationService.ActiveLink))
            {
                return(null);
            }

            if (LinkInformationService.ActiveLink.Contains("#newsignup") ||
                LinkInformationService.ActiveLink.Contains("#confirm") ||
                LinkInformationService.ActiveLink.Contains("#recover"))
            {
                if (!hasActiveAndOnlineSession)
                {
                    return(await SpecialNavigation());
                }

                var result = await DialogService.ShowOkCancelAsync(
                    ResourceService.AppMessages.GetString("AM_AlreadyLoggedInAlert_Title"),
                    ResourceService.AppMessages.GetString("AM_AlreadyLoggedInAlert"),
                    TwoButtonsDialogType.YesNo);

                if (!result)
                {
                    return(false);
                }

                // First need to log out of the current account
                var waitHandleLogout = new AutoResetEvent(false);
                SdkService.MegaSdk.logout(new LogOutRequestListener(false, waitHandleLogout));
                waitHandleLogout.WaitOne();

                return(await SpecialNavigation());
            }

            if (LinkInformationService.ActiveLink.Contains("#verify"))
            {
                if (hasActiveAndOnlineSession)
                {
                    return(await SpecialNavigation());
                }

                await DialogService.ShowAlertAsync(
                    ResourceService.UiResources.GetString("UI_ChangeEmail"),
                    ResourceService.AppMessages.GetString("AM_UserNotOnline"));
            }
            else if (LinkInformationService.ActiveLink.Contains("#F!"))
            {
                if (hasActiveAndOnlineSession)
                {
                    return(await SpecialNavigation());
                }

                await DialogService.ShowAlertAsync(
                    ResourceService.UiResources.GetString("UI_FolderLink"),
                    ResourceService.AppMessages.GetString("AM_UserNotOnline"));
            }
            else if (LinkInformationService.ActiveLink.Contains("#!"))
            {
                if (hasActiveAndOnlineSession)
                {
                    return(await SpecialNavigation());
                }

                await DialogService.ShowAlertAsync(
                    ResourceService.UiResources.GetString("UI_FileLink"),
                    ResourceService.AppMessages.GetString("AM_UserNotOnline"));
            }

            LogService.Log(MLogLevel.LOG_LEVEL_WARNING,
                           string.Format("Unsupported link: {0}", LinkInformationService.ActiveLink));
            LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Opening using the default Internet browser...");

            // Set the option to ignore app URI handlers
            var options = new LauncherOptions();

            options.IgnoreAppUriHandlers = true;

            // Open the URI with the default Internet browser
            await Launcher.LaunchUriAsync(
                new Uri(LinkInformationService.ActiveLink, UriKind.RelativeOrAbsolute),
                options);

            return(false);
        }
Ejemplo n.º 11
0
        public static async Task <bool> CopyFile(string sourcePath, string destinationFolderPath, string newFileName = null)
        {
            StorageFile copy = null;

            try
            {
                var file = await StorageFile.GetFileFromPathAsync(sourcePath);

                if (file == null)
                {
                    return(false);
                }

                var folder = await StorageFolder.GetFolderFromPathAsync(destinationFolderPath);

                if (folder == null)
                {
                    return(false);
                }

                newFileName = newFileName ?? file.Name;

                // Get file properties to determine the size in MB
                var bp = await file.GetBasicPropertiesAsync();

                var mb = (bp.Size / 1024) / 1024;

                if (mb >= 50)
                {
                    // If the file is larger than 50 MB, we will copy it using a small buffered value in a buffered stream
                    var destFile = await folder.CreateFileAsync(newFileName, CreationCollisionOption.GenerateUniqueName);

                    if (destFile == null)
                    {
                        return(false);
                    }

                    await CopyLargeFile(file, destFile);

                    return(true);
                }
                // If the file is smaller than 50 MB, let the OS decide how to copy and buffer size
                copy = await file.CopyAsync(folder, newFileName, NameCollisionOption.GenerateUniqueName);
            }
            catch (UnauthorizedAccessException e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error copying file by unauthorized access", e);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    new CustomMessageDialog(
                        AppMessages.CopyFileUnauthorizedAccessException_Title,
                        AppMessages.CopyFileUnauthorizedAccessException,
                        App.AppInformation,
                        MessageDialogButtons.Ok).ShowDialog();
                });
                return(false);
            }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error copying a file", e);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    new CustomMessageDialog(
                        AppMessages.CopyFileFailed_Title,
                        String.Format(AppMessages.CopyFileFailed, e.Message),
                        App.AppInformation,
                        MessageDialogButtons.Ok).ShowDialog();
                });
                return(false);
            }

            return(copy != null);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Change the API URL.
        /// </summary>
        private static async void ChangeApiUrl()
        {
            StopChangeApiUrlTimer();

            var usingStagingServer = SettingsService.LoadSetting <bool>(SettingsResources.UseStagingServer, false) ||
                                     SettingsService.LoadSetting <bool>(SettingsResources.UseStagingServerPort444, false);

            if (!usingStagingServer)
            {
                var result = await DialogService.ShowChangeToStagingServerDialog();

                if (!result)
                {
                    return;
                }
            }
            else
            {
                SettingsService.SaveSetting <bool>(SettingsResources.UseStagingServer, false);
                SettingsService.SaveSetting <bool>(SettingsResources.UseStagingServerPort444, false);
                MegaSdk.changeApiUrl(AppResources.AR_ApiUrl);
                MegaSdkFolderLinks.changeApiUrl(AppResources.AR_ApiUrl);
            }

            // If the user is logged in, do a new login with the current session
            if (Convert.ToBoolean(MegaSdk.isLoggedIn()))
            {
                bool fastLoginResult;
                try
                {
                    var fastLogin = new FastLoginRequestListenerAsync();
                    fastLoginResult = await fastLogin.ExecuteAsync(() =>
                                                                   MegaSdk.fastLogin(SettingsService.LoadSetting <string>(SettingsResources.UserMegaSession), fastLogin));
                }
                // Do nothing, app is already logging out
                catch (BadSessionIdException)
                {
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Login failed. Bad session ID.");
                    return;
                }

                if (fastLoginResult)
                {
                    // Fetch nodes from MEGA
                    var fetchNodes       = new FetchNodesRequestListenerAsync();
                    var fetchNodesResult = await fetchNodes.ExecuteAsync(() => MegaSdk.fetchNodes(fetchNodes));

                    if (fetchNodesResult != FetchNodesResult.Success)
                    {
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Fetch nodes failed.");
                        new CustomMessageDialog(AppMessages.FetchingNodesFailed_Title, AppMessages.FetchingNodesFailed,
                                                App.AppInformation, MessageDialogButtons.Ok).ShowDialog();
                    }
                }
                else
                {
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Resume session failed.");
                    new CustomMessageDialog(UiResources.UI_ResumeSession, AppMessages.AM_ResumeSessionFailed,
                                            App.AppInformation, MessageDialogButtons.Ok).ShowDialog();
                }
            }

            // Reset the "Camera Uploads" service if is enabled
            if (MediaService.GetAutoCameraUploadStatus())
            {
                LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Resetting CAMERA UPLOADS service (API URL changed)");
                SettingsService.SaveSetting(SettingsResources.CameraUploadsIsEnabled,
                                            MediaService.SetAutoCameraUpload(true));
            }

            LogService.Log(MLogLevel.LOG_LEVEL_INFO, "API URL changed");
            new CustomMessageDialog(null, "API URL changed",
                                    App.AppInformation, MessageDialogButtons.Ok).ShowDialog();

            OnApiUrlChanged();
        }