Beispiel #1
0
        public static async void ShowOverquotaAlert()
        {
            var result = await ShowOkCancelAsync(
                ResourceService.AppMessages.GetString("AM_OverquotaAlert_Title"),
                ResourceService.AppMessages.GetString("AM_OverquotaAlert"),
                TwoButtonsDialogType.YesNo);

            if (!result)
            {
                return;
            }

            UiService.OnUiThread(() =>
            {
                NavigateService.Instance.Navigate(typeof(MyAccountPage), false,
                                                  NavigationObject.Create(typeof(MainViewModel), NavigationActionType.Upgrade));
            });
        }
Beispiel #2
0
 /// <summary>
 /// Clear all the account details info
 /// </summary>
 public static void ClearAccountDetails()
 {
     UiService.OnUiThread(() =>
     {
         AccountDetails.AccountType           = MAccountType.ACCOUNT_TYPE_FREE;
         AccountDetails.StorageState          = MStorageState.STORAGE_STATE_GREEN;
         AccountDetails.TotalSpace            = 0;
         AccountDetails.UsedSpace             = 0;
         AccountDetails.CloudDriveUsedSpace   = 0;
         AccountDetails.RubbishBinUsedSpace   = 0;
         AccountDetails.TransferQuota         = 0;
         AccountDetails.UsedTransferQuota     = 0;
         AccountDetails.IsInStorageOverquota  = false;
         AccountDetails.IsInTransferOverquota = false;
         AccountDetails.PaymentMethod         = string.Empty;
         AccountDetails.SubscriptionRenewDate = string.Empty;
         AccountDetails.ProExpirationDate     = string.Empty;
     });
 }
Beispiel #3
0
        /// <summary>
        /// Show toast alert notification with a warning icon.
        /// </summary>
        /// <param name="title">Title to show in the notification.</param>
        /// <param name="text">Text to show in the notification.</param>
        public static void ShowAlertNotification(string title, string text)
        {
            var visual = new ToastVisual
            {
                BindingGeneric = new ToastBindingGeneric
                {
                    Children =
                    {
                        new AdaptiveText {
                            Text = title
                        },
                        new AdaptiveText {
                            Text = text
                        }
                    },

                    AppLogoOverride = new ToastGenericAppLogo
                    {
                        Source   = WarningUri,
                        HintCrop = ToastGenericAppLogoCrop.Circle
                    }
                }
            };

            var toastContent = new ToastContent
            {
                Visual = visual,
                Audio  = new ToastAudio()
                {
                    Silent = false
                },
            };

            var toast = new ToastNotification(toastContent.GetXml());

            try { ToastNotificationManager.CreateToastNotifier().Show(toast); }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "Error showing toast notification", e);
                UiService.OnUiThread(async() => await DialogService.ShowAlertAsync(title, text));
            }
        }
Beispiel #4
0
        /// <summary>
        /// Share a link with other external app
        /// </summary>
        /// <param name="link">Link to share</param>
        public static void ShareLink(string link)
        {
            DataTransferManager.GetForCurrentView().DataRequested += (sender, args) =>
            {
                args.Request.Data.Properties.Title       = ResourceService.AppMessages.GetString("AM_ShareLinkFromMega_Title");
                args.Request.Data.Properties.Description = ResourceService.AppMessages.GetString("AM_ShareLinkFromMega");
                args.Request.Data.SetText(link);
            };

            try { DataTransferManager.ShowShareUI(); }
            catch (Exception)
            {
                UiService.OnUiThread(async() =>
                {
                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_ShareLinkFromMegaFailed_Title"),
                        ResourceService.AppMessages.GetString("AM_ShareLinkFromMegaFailed"));
                });
            }
        }
Beispiel #5
0
        /// <summary>
        /// Open a folder in the file explorer
        /// </summary>
        /// <param name="folderPath">Path of the folder to open</param>
        /// <returns>TRUE if the folder could be opened or FALSE if something failed</returns>
        public static async Task <bool> OpenFolder(string folderPath)
        {
            try
            {
                var folder = await StorageFolder.GetFolderFromPathAsync(folderPath);

                return(await Launcher.LaunchFolderAsync(folder));
            }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error opening folder", e);
                UiService.OnUiThread(async() =>
                {
                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_OpenFolderFailed_Title"),
                        ResourceService.AppMessages.GetString("AM_OpenFolderFailed"));
                });

                return(false);
            }
        }
Beispiel #6
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)
            {
                UiService.OnUiThread(() =>
                {
                    var img = new BitmapImage()
                    {
                        CreateOptions = BitmapCreateOptions.IgnoreImageCache,
                        UriSource     = new Uri(UserData.AvatarPath)
                    };
                    UserData.AvatarUri = img.UriSource;
                });
            }
            else
            {
                UiService.OnUiThread(() => UserData.AvatarUri = null);
            }
        }
Beispiel #7
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);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Method that should be called when an action required for
        /// enable/disable the debug mode is done.
        /// </summary>
        public static void ChangeStatusAction()
        {
            if (_changeStatusActionCounter == 0)
            {
                UiService.OnUiThread(() =>
                {
                    if (_timerDebugMode == null)
                    {
                        _timerDebugMode          = new DispatcherTimer();
                        _timerDebugMode.Interval = new TimeSpan(0, 0, 5);
                        _timerDebugMode.Tick    += (obj, args) => StopDebugModeTimer();
                    }
                    _timerDebugMode.Start();
                });
            }

            _changeStatusActionCounter++;

            if (_changeStatusActionCounter >= 5)
            {
                StopDebugModeTimer();
                DebugSettings.IsDebugMode = !DebugSettings.IsDebugMode;
            }
        }
Beispiel #9
0
        /// <summary>
        /// Gets the user avatar color
        /// </summary>
        public static void GetUserAvatarColor()
        {
            var avatarColor = UiService.GetColorFromHex(SdkService.MegaSdk.getUserAvatarColor(SdkService.MegaSdk.getMyUser()));

            UiService.OnUiThread(() => UserData.AvatarColor = avatarColor);
        }
Beispiel #10
0
 /// <summary>
 /// Gets the user email
 /// </summary>
 public static async Task GetUserEmail()
 {
     await UiService.OnUiThreadAsync(() => UserData.UserEmail = SdkService.MegaSdk.getMyEmail());
 }
Beispiel #11
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 contact = new ContactViewModel(
                            SdkService.MegaSdk.getContact(mails.get(m)), 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();
            });
        }
Beispiel #12
0
        /// <summary>
        /// Gets all the account details info
        /// </summary>
        public static async void GetAccountDetails()
        {
            var accountDetailsRequestListener = new GetAccountDetailsRequestListenerAsync();
            var accountDetails = await accountDetailsRequestListener.ExecuteAsync(() =>
            {
                SdkService.MegaSdk.getAccountDetails(accountDetailsRequestListener);
            });

            if (accountDetails == null)
            {
                return;
            }

            UiService.OnUiThread(() =>
            {
                AccountDetails.AccountType = accountDetails.getProLevel();
                AccountDetails.TotalSpace  = accountDetails.getStorageMax();
                AccountDetails.UsedSpace   = accountDetails.getStorageUsed();

                var rootNode = SdkService.MegaSdk.getRootNode();
                if (rootNode != null)
                {
                    AccountDetails.CloudDriveUsedSpace = accountDetails.getStorageUsed(rootNode.getHandle());
                }

                var rubbishNode = SdkService.MegaSdk.getRubbishNode();
                if (rubbishNode != null)
                {
                    AccountDetails.RubbishBinUsedSpace = accountDetails.getStorageUsed(rubbishNode.getHandle());
                }

                AccountDetails.IncomingSharesUsedSpace = GetIncomingSharesUsedSpace();

                AccountDetails.TransferQuota     = accountDetails.getTransferMax();
                AccountDetails.UsedTransferQuota = accountDetails.getTransferOwnUsed();

                GetTransferOverquotaDetails();

                AccountDetails.PaymentMethod = accountDetails.getSubscriptionMethod();
            });

            // If there is a valid subscription
            if (accountDetails.getSubscriptionStatus() == MSubscriptionStatus.SUBSCRIPTION_STATUS_VALID)
            {
                // If is a valid and active subscription (auto renewable subscription)
                if (accountDetails.getSubscriptionRenewTime() != 0)
                {
                    GetSubscriptionDetails(accountDetails);
                }
                // If is a valid but non active subscription (canceled subscription)
                else if (accountDetails.getProExpiration() != 0)
                {
                    GetNonSubscriptionDetails(accountDetails);
                }
            }
            // If is a pro account without subscription
            else if (accountDetails.getProExpiration() != 0)
            {
                GetNonSubscriptionDetails(accountDetails);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Navigates to the corresponding page depending on the current state or the active link.
        /// </summary>
        /// <returns>TRUE if navigates or FALSE in other case.</returns>
        private static async Task <bool> SpecialNavigation()
        {
            if (LinkInformationService.ActiveLink.Contains("#newsignup"))
            {
                UiService.OnUiThread(() =>
                                     NavigateService.Instance.Navigate(typeof(LoginAndCreateAccountPage), true));
                return(true);
            }

            if (LinkInformationService.ActiveLink.Contains("#confirm"))
            {
                var signUp = new QuerySignUpLinkRequestListenerAsync();
                var result = await signUp.ExecuteAsync(() =>
                {
                    SdkService.MegaSdk.querySignupLink(LinkInformationService.ActiveLink, signUp);
                });

                switch (result)
                {
                case SignUpLinkType.Valid:
                    UiService.OnUiThread(() =>
                                         NavigateService.Instance.Navigate(typeof(ConfirmAccountPage), true,
                                                                           new NavigationObject
                    {
                        Action     = NavigationActionType.Default,
                        Parameters = new Dictionary <NavigationParamType, object>
                        {
                            { NavigationParamType.Email, signUp.EmailAddress },
                            { NavigationParamType.Data, LinkInformationService.ActiveLink },
                        }
                    }));
                    return(true);

                case SignUpLinkType.AutoConfirmed:
                    UiService.OnUiThread(() =>
                                         NavigateService.Instance.Navigate(typeof(LoginAndCreateAccountPage), true,
                                                                           new NavigationObject
                    {
                        Action     = NavigationActionType.Login,
                        Parameters = new Dictionary <NavigationParamType, object>
                        {
                            { NavigationParamType.Email, signUp.EmailAddress },
                        }
                    }));
                    return(true);

                case SignUpLinkType.AlreadyConfirmed:
                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_AlreadyConfirmedAccount_Title"),
                        ResourceService.AppMessages.GetString("AM_AlreadyConfirmedAccount"));

                    break;

                case SignUpLinkType.Expired:
                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_SignUpLinkExpired_Title"),
                        ResourceService.AppMessages.GetString("AM_SignUpLinkExpired"));

                    break;

                case SignUpLinkType.Unknown:
                case SignUpLinkType.Invalid:
                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_InvalidSignUpLink_Title"),
                        ResourceService.AppMessages.GetString("AM_InvalidSignUpLink"));

                    break;
                }

                return(false);
            }

            if (LinkInformationService.ActiveLink.Contains("#verify"))
            {
                UiService.OnUiThread(() =>
                                     NavigateService.Instance.Navigate(typeof(ConfirmChangeEmailPage), true));
                return(true);
            }

            if (LinkInformationService.ActiveLink.Contains("#recover"))
            {
                // Check if it is recover or park account
                var query  = new QueryPasswordLinkRequestListenerAsync();
                var result = await query.ExecuteAsync(() =>
                {
                    SdkService.MegaSdk.queryResetPasswordLink(LinkInformationService.ActiveLink, query);
                });

                switch (result)
                {
                case RecoverLinkType.Recovery:
                    UiService.OnUiThread(() => NavigateService.Instance.Navigate(typeof(RecoverPage), true));
                    return(true);

                case RecoverLinkType.ParkAccount:
                    UiService.OnUiThread(() => NavigateService.Instance.Navigate(typeof(ConfirmParkAccountPage), true));
                    return(true);

                case RecoverLinkType.Expired:
                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_RecoveryLinkExpired_Title"),
                        ResourceService.AppMessages.GetString("AM_RecoveryLinkExpired"));

                    break;

                case RecoverLinkType.Unknown:

                    await DialogService.ShowAlertAsync(
                        ResourceService.AppMessages.GetString("AM_InvalidRecoveryLink_Title"),
                        ResourceService.AppMessages.GetString("AM_InvalidRecoveryLink"));

                    break;
                }
            }

            if (LinkInformationService.ActiveLink.Contains("#F!"))
            {
                LinkInformationService.UriLink = UriLinkType.Folder;

                // Navigate to the folder link page
                UiService.OnUiThread(() =>
                                     NavigateService.Instance.Navigate(typeof(FolderLinkPage)));
                return(true);
            }

            if (LinkInformationService.ActiveLink.Contains("#!"))
            {
                LinkInformationService.UriLink = UriLinkType.Folder;

                // Navigate to the file link page
                UiService.OnUiThread(() =>
                                     NavigateService.Instance.Navigate(typeof(FileLinkPage)));
                return(true);
            }

            return(false);
        }
Beispiel #14
0
 /// <summary>
 /// Stops the timer to detect an API URL change.
 /// </summary>
 private static void StopChangeApiUrlTimer() =>
 UiService.OnUiThread(() => timerChangeApiUrl?.Stop());
Beispiel #15
0
        /// <summary>
        /// Creates the sort menu with all the sort options.
        /// </summary>
        /// <param name="folder">Folder to sort.</param>
        /// <returns>The flyout menu with the sort options.</returns>
        public static MenuFlyout CreateSortMenu(BaseFolderViewModel folder)
        {
            var currentSortOrder = UiService.GetSortOrder(folder?.FolderRootNode?.Base64Handle, folder?.FolderRootNode?.Name);

            MenuFlyout menuFlyout = new MenuFlyout();

            menuFlyout.Items?.Add(new MenuFlyoutItem()
            {
                Text       = ResourceService.UiResources.GetString("UI_SortOptionName"),
                Foreground = GetSortMenuItemForeground(currentSortOrder, NodesSortOrderType.ORDER_NAME),
                Command    = new RelayCommand(() =>
                {
                    var newOrder = folder != null && folder.ItemCollection.IsCurrentOrderAscending ?
                                   MSortOrderType.ORDER_ALPHABETICAL_ASC : MSortOrderType.ORDER_ALPHABETICAL_DESC;
                    if (folder == null)
                    {
                        return;
                    }
                    UiService.SetSortOrder(folder.FolderRootNode.Base64Handle, newOrder);
                    folder.LoadChildNodes();
                })
            });

            menuFlyout.Items?.Add(new MenuFlyoutItem()
            {
                Text       = ResourceService.UiResources.GetString("UI_SortOptionSize"),
                Foreground = GetSortMenuItemForeground(currentSortOrder, NodesSortOrderType.ORDER_SIZE),
                Command    = new RelayCommand(() =>
                {
                    var newOrder = folder != null && folder.ItemCollection.IsCurrentOrderAscending ?
                                   MSortOrderType.ORDER_SIZE_ASC : MSortOrderType.ORDER_SIZE_DESC;
                    if (folder == null)
                    {
                        return;
                    }
                    UiService.SetSortOrder(folder.FolderRootNode.Base64Handle, newOrder);
                    folder.LoadChildNodes();
                })
            });

            menuFlyout.Items?.Add(new MenuFlyoutItem()
            {
                Text       = ResourceService.UiResources.GetString("UI_SortOptionDateModified"),
                Foreground = GetSortMenuItemForeground(currentSortOrder, NodesSortOrderType.ORDER_MODIFICATION),
                Command    = new RelayCommand(() =>
                {
                    var newOrder = folder != null && folder.ItemCollection.IsCurrentOrderAscending ?
                                   MSortOrderType.ORDER_MODIFICATION_ASC : MSortOrderType.ORDER_MODIFICATION_DESC;
                    if (folder == null)
                    {
                        return;
                    }
                    UiService.SetSortOrder(folder.FolderRootNode.Base64Handle, newOrder);
                    folder.LoadChildNodes();
                })
            });

            menuFlyout.Items?.Add(new MenuFlyoutItem()
            {
                Text       = ResourceService.UiResources.GetString("UI_SortOptionType"),
                Foreground = GetSortMenuItemForeground(currentSortOrder, NodesSortOrderType.ORDER_TYPE),
                Command    = new RelayCommand(() =>
                {
                    var newOrder = folder != null && folder.ItemCollection.IsCurrentOrderAscending ?
                                   MSortOrderType.ORDER_DEFAULT_ASC : MSortOrderType.ORDER_DEFAULT_DESC;
                    if (folder == null)
                    {
                        return;
                    }
                    UiService.SetSortOrder(folder.FolderRootNode.Base64Handle, newOrder);
                    folder.LoadChildNodes();
                })
            });

            return(menuFlyout);
        }
Beispiel #16
0
        /// <summary>
        /// Gets all pricing details info.
        /// </summary>
        private static async void GetPricingDetails()
        {
            // Only if they were not obtained before
            if (UpgradeAccount.Plans.Any() && UpgradeAccount.Products.Any())
            {
                return;
            }

            var pricingRequestListener = new GetPricingRequestListenerAsync();
            var pricingDetails         = await pricingRequestListener.ExecuteAsync(() =>
                                                                                   SdkService.MegaSdk.getPricing(pricingRequestListener));

            if (pricingDetails == null)
            {
                return;
            }

            int numberOfProducts = pricingDetails.getNumProducts();

            for (int i = 0; i < numberOfProducts; i++)
            {
                var accountType = (MAccountType)Enum.Parse(typeof(MAccountType),
                                                           pricingDetails.getProLevel(i).ToString());

                var product = new Product
                {
                    AccountType    = accountType,
                    FormattedPrice = string.Format("{0:N} {1}", (double)pricingDetails.getAmount(i) / 100, GetCurrencySymbol(pricingDetails.getCurrency(i))),
                    Currency       = GetCurrencySymbol(pricingDetails.getCurrency(i)),
                    GbStorage      = pricingDetails.getGBStorage(i),
                    GbTransfer     = pricingDetails.getGBTransfer(i),
                    Months         = pricingDetails.getMonths(i),
                    Handle         = pricingDetails.getHandle(i)
                };

                // Try get the local pricing details from the store
                var storeProduct = await LicenseService.GetProductAsync(product.MicrosoftStoreId);

                if (storeProduct != null)
                {
                    product.FormattedPrice = storeProduct.FormattedPrice;

                    try
                    {
                        // 'ProductListing.CurrencyCode' property was introduced on the Windows 10.0.10586 build.
                        // In previous builds like Windows 10.0.10240, it will throw an 'InvalidCastException'.
                        product.Currency = GetCurrencySymbol(
                            ApiInformation.IsPropertyPresent("Windows.ApplicationModel.Store.ProductListing", "CurrencyCode") ?
                            storeProduct.CurrencyCode : GetCurrencyFromFormattedPrice(storeProduct.FormattedPrice));
                    }
                    catch (InvalidCastException)
                    {
                        product.Currency = GetCurrencySymbol(GetCurrencyFromFormattedPrice(storeProduct.FormattedPrice));
                    }
                }

                switch (accountType)
                {
                case MAccountType.ACCOUNT_TYPE_FREE:
                    product.Name            = ResourceService.AppResources.GetString("AR_AccountTypeFree");
                    product.ProductColor    = (Color)Application.Current.Resources["MegaFreeAccountColor"];
                    product.ProductPathData = ResourceService.VisualResources.GetString("VR_AccountTypeFreePathData");
                    break;

                case MAccountType.ACCOUNT_TYPE_LITE:
                    product.Name            = ResourceService.AppResources.GetString("AR_AccountTypeLite");
                    product.ProductColor    = (Color)Application.Current.Resources["MegaProLiteAccountColor"];
                    product.ProductPathData = ResourceService.VisualResources.GetString("VR_AccountTypeProLitePathData");

                    // If product is is LITE monthly, store the price and currency for upgrade notifications purposes
                    // and include Centili and Fortumo payments methods if available
                    if (product.Months == 1)
                    {
                        product.IsCentiliPaymentMethodAvailable  = UpgradeAccount.IsCentiliPaymentMethodAvailable;
                        product.IsFortumoPaymentMethodAvailable  = UpgradeAccount.IsFortumoPaymentMethodAvailable;
                        UpgradeAccount.LiteMonthlyFormattedPrice = product.FormattedPrice;
                    }
                    break;

                case MAccountType.ACCOUNT_TYPE_PROI:
                    product.Name            = ResourceService.AppResources.GetString("AR_AccountTypePro1");
                    product.ProductColor    = (Color)Application.Current.Resources["MegaProAccountColor"];
                    product.ProductPathData = ResourceService.VisualResources.GetString("VR_AccountTypePro1PathData");
                    break;

                case MAccountType.ACCOUNT_TYPE_PROII:
                    product.Name            = ResourceService.AppResources.GetString("AR_AccountTypePro2");
                    product.ProductColor    = (Color)Application.Current.Resources["MegaProAccountColor"];
                    product.ProductPathData = ResourceService.VisualResources.GetString("VR_AccountTypePro2PathData");
                    break;

                case MAccountType.ACCOUNT_TYPE_PROIII:
                    product.Name            = ResourceService.AppResources.GetString("AR_AccountTypePro3");
                    product.ProductColor    = (Color)Application.Current.Resources["MegaProAccountColor"];
                    product.ProductPathData = ResourceService.VisualResources.GetString("VR_AccountTypePro3PathData");
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                // If CC payment method is active, include it into the product
                //product.IsCreditCardPaymentMethodAvailable = UpgradeAccount.IsCreditCardPaymentMethodAvailable;

                // If in-app payment method is active, include it into the product
                product.IsInAppPaymentMethodAvailable = UpgradeAccount.IsInAppPaymentMethodAvailable;

                await UiService.OnUiThreadAsync(() => UpgradeAccount.Products.Add(product));

                // Plans show only the information off the monthly plans
                if (pricingDetails.getMonths(i) == 1)
                {
                    var plan = new ProductBase
                    {
                        AccountType     = accountType,
                        Name            = product.Name,
                        FormattedPrice  = product.FormattedPrice,
                        Currency        = product.Currency,
                        GbStorage       = product.GbStorage,
                        GbTransfer      = product.GbTransfer,
                        ProductPathData = product.ProductPathData,
                        ProductColor    = product.ProductColor
                    };

                    await UiService.OnUiThreadAsync(() => UpgradeAccount.Plans.Add(plan));
                }
            }
        }
Beispiel #17
0
 public static MNodeList GetChildren(MegaSDK megaSdk, IMegaNode rootNode)
 {
     return(megaSdk.getChildren(rootNode.OriginalMNode, UiService.GetSortOrder(rootNode.Base64Handle, rootNode.Name)));
 }