/// <summary> /// Change the API URL. /// </summary> private static async void ChangeApiUrl() { StopChangeApiUrlTimer(); var useStagingServer = SettingsService.Load(ResourceService.SettingsResources.GetString("SR_UseStagingServer"), false) || SettingsService.Load(ResourceService.SettingsResources.GetString("SR_UseStagingServerPort444"), false); if (!useStagingServer) { var result = await DialogService.ShowChangeToStagingServerDialog(); if (!result) { return; } } else { SettingsService.Save(ResourceService.SettingsResources.GetString("SR_UseStagingServer"), false); SettingsService.Save(ResourceService.SettingsResources.GetString("SR_UseStagingServerPort444"), false); MegaSdk.changeApiUrl(ResourceService.AppResources.GetString("AR_ApiUrl")); MegaSdkFolderLinks.changeApiUrl(ResourceService.AppResources.GetString("AR_ApiUrl")); } // Reset the "Camera Uploads" service if is enabled if (TaskService.IsBackGroundTaskActive(CameraUploadService.TaskEntryPoint, CameraUploadService.TaskName)) { LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Resetting CAMERA UPLOADS service (API URL changed)"); await TaskService.RegisterBackgroundTaskAsync( CameraUploadService.TaskEntryPoint, CameraUploadService.TaskName, new TimeTrigger(CameraUploadService.TaskTimeTrigger, false)); } OnApiUrlChanged(); }
/// <summary> /// Locate or create the Camera Uploads folder node to use as parent for the uploads /// </summary> /// <returns>Camera Uploads root folder node</returns> public static async Task <MNode> GetCameraUploadRootNodeAsync() { // First try to retrieve the Cloud Drive root node var rootNode = MegaSdk.getRootNode(); if (rootNode == null) { return(null); } // Locate the camera upload node var cameraUploadNode = FindCameraUploadNode(rootNode); // If node found, return the node if (cameraUploadNode != null) { return(cameraUploadNode); } // If node not found and the service is enabled, create a new Camera Uploads node if (TaskService.IsBackGroundTaskActive(CameraUploadService.TaskEntryPoint, CameraUploadService.TaskName)) { var createFolder = new CreateFolderRequestListenerAsync(); var result = await createFolder.ExecuteAsync(() => { MegaSdk.createFolder("Camera Uploads", rootNode, createFolder); }); return(result ? FindCameraUploadNode(rootNode) : null); } return(null); }
public async void GetPricing() { this.UpgradeAccount.InAppPaymentMethodAvailable = await LicenseService.IsAvailable(); MegaSdk.getPaymentMethods(new GetPaymentMethodsRequestListener(UpgradeAccount)); MegaSdk.getPricing(new GetPricingRequestListener()); }
public void Update(MNode megaNode, ContainerType parentContainerType) { OriginalMNode = megaNode; this.Handle = megaNode.getHandle(); this.Base64Handle = megaNode.getBase64Handle(); this.Type = megaNode.getType(); this.ParentContainerType = parentContainerType; this.Name = megaNode.getName(); this.Size = MegaSdk.getSize(megaNode); this.SizeText = this.Size.ToStringAndSuffix(2); this.IsExported = megaNode.isExported(); this.CreationTime = ConvertDateToString(megaNode.getCreationTime()).ToString("dd MMM yyyy"); if (this.Type == MNodeType.TYPE_FILE) { this.ModificationTime = ConvertDateToString(megaNode.getModificationTime()).ToString("dd MMM yyyy"); } else { this.ModificationTime = this.CreationTime; } if (!SdkService.MegaSdk.isInShare(megaNode) && this.ParentContainerType != ContainerType.PublicLink && this.ParentContainerType != ContainerType.InShares && this.ParentContainerType != ContainerType.ContactInShares && this.ParentContainerType != ContainerType.FolderLink) { CheckAndUpdateSFO(megaNode); } }
private void GetThumbnail() { if (Convert.ToBoolean(MegaSdk.isLoggedIn()) || ParentContainerType == ContainerType.FolderLink) { this.MegaSdk.getThumbnail(OriginalMNode, ThumbnailPath, new GetThumbnailRequestListener(this)); } }
public void GetSentContactRequests() { // User must be online to perform this operation if (!IsUserOnline()) { return; } SetEmptyContentTemplate(true); this.SentContactRequests.Clear(); MContactRequestList outgoingContactRequestsList = MegaSdk.getOutgoingContactRequests(); for (int i = 0; i < outgoingContactRequestsList.size(); i++) { // To avoid null values if (outgoingContactRequestsList.get(i) == null) { continue; } ContactRequest contactRequest = new ContactRequest(outgoingContactRequestsList.get(i)); this.SentContactRequests.Add(contactRequest); if (!String.IsNullOrWhiteSpace(contactRequest.Email)) { MegaSdk.getUserAvatar(MegaSdk.getContact(contactRequest.Email), contactRequest.AvatarPath, new GetContactAvatarRequestListener(contactRequest)); } } SetEmptyContentTemplate(false); }
public void GetReceivedContactRequests() { // User must be online to perform this operation if (!IsUserOnline()) { return; } SetEmptyContentTemplate(true); this.ReceivedContactRequests.Clear(); MContactRequestList incomingContactRequestsList = MegaSdk.getIncomingContactRequests(); for (int i = 0; i < incomingContactRequestsList.size(); i++) { // To avoid null values if (incomingContactRequestsList.get(i) == null) { continue; } ContactRequest contactRequest = new ContactRequest(incomingContactRequestsList.get(i)); this.ReceivedContactRequests.Add(contactRequest); MegaSdk.getUserAvatar(MegaSdk.getContact(contactRequest.Email), contactRequest.AvatarPath, new GetContactAvatarRequestListener(contactRequest)); } SetEmptyContentTemplate(false); }
public async Task <bool> MultipleDeleteContacts() { int count = MegaContactsList.Count(n => n.IsMultiSelected); if (count < 1) { return(false); } var customMessageDialog = new CustomMessageDialog( AppMessages.DeleteMultipleContactsQuestion_Title, String.Format(AppMessages.DeleteMultipleContactsQuestion, count), App.AppInformation, MessageDialogButtons.OkCancel); customMessageDialog.OkOrYesButtonTapped += (sender, args) => { Deployment.Current.Dispatcher.BeginInvoke(() => ProgressService.SetProgressIndicator(true, ProgressMessages.RemoveContact)); var helperList = new List <Contact>(count); helperList.AddRange(MegaContactsList.Where(n => n.IsMultiSelected)); foreach (var contact in helperList) { MegaSdk.removeContact(MegaSdk.getContact(contact.Email), new RemoveContactRequestListener(this, contact)); } Deployment.Current.Dispatcher.BeginInvoke(() => ProgressService.SetProgressIndicator(false)); this.IsMultiSelectActive = false; }; return(await customMessageDialog.ShowDialogAsync() == MessageDialogResult.OkYes); }
private async Task <bool> SaveFileForOffline(String sfoPath, NodeViewModel node) { if (FileService.FileExists(Path.Combine(sfoPath, node.Name))) { return(true); } var existingNode = SavedForOffline.ReadNodeByFingerprint(MegaSdk.getNodeFingerprint(node.OriginalMNode)); if (existingNode != null) { bool result = await FileService.CopyFile(existingNode.LocalPath, sfoPath); if (!result) { return(false); } SavedForOffline.Insert(node.OriginalMNode, true); } else { TransfersService.MegaTransfers.Add(node.Transfer); node.Transfer.ExternalDownloadPath = sfoPath; node.Transfer.StartTransfer(true); } return(true); }
private void ShareRecoveryKey(object obj) { var shareStatusTask = new ShareStatusTask { Status = MegaSdk.exportMasterKey() }; shareStatusTask.Show(); }
public void GetAccountDetails() { if (!AccountDetails.IsDataLoaded) { AccountService.GetAccountDetails(); MegaSdk.creditCardQuerySubscriptions(new GetAccountDetailsRequestListener()); AccountDetails.IsDataLoaded = true; } }
private void OnInSharedFolderRemoved(object sender, MNode megaNode) { var user = MegaSdk.getUserFromInShare(megaNode); if (user.getEmail().Equals(this.Contact.getEmail())) { this.OnSharedFolderRemoved(sender, megaNode); } }
public async void Logout() { if (await AccountService.ShouldShowPasswordReminderDialogAsync(true)) { DialogService.ShowPasswordReminderDialog(true); return; } MegaSdk.logout(new LogOutRequestListener()); }
private async void ApiUrlChanged(object sender, EventArgs e) { // If the user is logged in, do a new login with the current session if (Convert.ToBoolean(MegaSdk.isLoggedIn())) { await this.FastLoginAsync(ResourceService.ProgressMessages.GetString("PM_Reloading")); } SettingsService.ReloadSettings(); ToastService.ShowTextNotification("API URL changed"); }
public void GetContactSharedFolders() { // User must be online to perform this operation if (!IsUserOnline()) { return; } // First cancel any other loading task that is busy CancelLoad(); // Create the option to cancel CreateLoadCancelOption(); OnUiThread(() => InShares.ChildNodes.Clear()); MNodeList inSharesList = MegaSdk.getInShares(MegaSdk.getContact(_selectedContact.Email)); Task.Factory.StartNew(() => { try { Deployment.Current.Dispatcher.BeginInvoke(() => { for (int i = 0; i < inSharesList.size(); i++) { // If the task has been cancelled, stop processing if (LoadingCancelToken.IsCancellationRequested) { LoadingCancelToken.ThrowIfCancellationRequested(); } // To avoid null values if (inSharesList.get(i) == null) { continue; } var _inSharedFolder = NodeService.CreateNew(this.MegaSdk, this.AppInformation, inSharesList.get(i), ContainerType.InShares, InShares.ChildNodes); _inSharedFolder.DefaultImagePathData = VisualResources.FolderTypePath_shared; InShares.ChildNodes.Add(_inSharedFolder); } OnPropertyChanged("NumberOfInSharedFolders"); OnPropertyChanged("NumberOfInSharedFoldersText"); }); } catch (OperationCanceledException) { // Do nothing. Just exit this background process because a cancellation exception has been thrown } }, LoadingCancelToken, TaskCreationOptions.PreferFairness, TaskScheduler.Current); }
private async Task RecursiveSaveForOffline(String sfoPath, NodeViewModel node) { if (!FolderService.FolderExists(sfoPath)) { FolderService.CreateFolder(sfoPath); } String newSfoPath = Path.Combine(sfoPath, node.Name); if (!FolderService.FolderExists(newSfoPath)) { FolderService.CreateFolder(newSfoPath); } if (!SavedForOffline.ExistsNodeByLocalPath(newSfoPath)) { SavedForOffline.Insert(node.OriginalMNode, true); } else { SavedForOffline.UpdateNode(node.OriginalMNode, true); } MNodeList childList = MegaSdk.getChildren(node.OriginalMNode); for (int i = 0; i < childList.size(); i++) { // To avoid pass null values to CreateNew if (childList.get(i) == null) { continue; } var childNode = NodeService.CreateNew(this.MegaSdk, this.AppInformation, childList.get(i), this.ParentContainerType); // If node creation failed for some reason, continue with the rest and leave this one if (childNode == null) { continue; } if (childNode.IsFolder) { await RecursiveSaveForOffline(newSfoPath, childNode); } else { await SaveFileForOffline(newSfoPath, childNode); } } }
/// <summary> /// Copy the node from its current location to a new folder destination /// </summary> /// <param name="newParentNode">The new destination folder</param> /// <returns>Result of the action</returns> public async Task <NodeActionResult> CopyAsync(MNode newParentNode) { // User must be online to perform this operation if (!await IsUserOnlineAsync()) { return(NodeActionResult.NotOnline); } var copyNode = new CopyNodeRequestListenerAsync(); var result = await copyNode.ExecuteAsync(() => MegaSdk.copyNode(OriginalMNode, newParentNode, copyNode)); return(result ? NodeActionResult.Succeeded : NodeActionResult.Failed); }
public void AddContact() { if (!IsUserOnline()) { return; } // Only 1 CustomInputDialog should be open at the same time. if (this.AppInformation.PickerOrAsyncDialogIsOpen) { return; } var inputDialog = new CustomInputDialog(UiResources.AddContact, UiResources.CreateContact, this.AppInformation); inputDialog.OkButtonTapped += (sender, args) => { if (String.IsNullOrWhiteSpace(args.InputText) || !ValidationService.IsValidEmail(args.InputText)) { Deployment.Current.Dispatcher.BeginInvoke(() => { new CustomMessageDialog( AppMessages.InviteContactAddFailed_Title.ToUpper(), AppMessages.AM_IncorrectEmailFormat, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); }); return; } if (args.InputText.Equals(SdkService.MegaSdk.getMyEmail())) { Deployment.Current.Dispatcher.BeginInvoke(() => { new CustomMessageDialog( AppMessages.InviteContactAddFailed_Title.ToUpper(), AppMessages.InviteContactAddFailedOwnEmail, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); }); return; } MegaSdk.inviteContact(args.InputText, "", MContactRequestInviteActionType.INVITE_ACTION_ADD, new InviteContactRequestListener()); }; inputDialog.ShowDialog(); }
/// <summary> /// Use custom DNS servers in all the SDK instances. /// </summary> /// <param name="refresh">Indicates if should refresh the previously stored addresses.</param> public static async void SetDnsServers(bool refresh = true) { var dnsServers = NetworkService.GetSystemDnsServers(refresh); if (string.IsNullOrWhiteSpace(dnsServers)) { dnsServers = await NetworkService.GetMegaDnsServersAsync(refresh); } if (!string.IsNullOrWhiteSpace(dnsServers)) { MegaSdk.setDnsServers(dnsServers); MegaSdkFolderLinks.setDnsServers(dnsServers); } }
/// <summary> /// Checks if a node exists by its name. /// </summary> /// <param name="searchNode">The parent node of the tree to explore.</param> /// <param name="name">Name of the node to search.</param> /// <param name="isFolder">True if the node to search is a folder or false in other case.</param> /// <param name="recursive">True if you want to seach recursively in the node tree.</param> /// <returns>True if the node exists or false in other case.</returns> public static bool ExistsNodeByName(MNode searchNode, string name, bool isFolder, bool recursive = false) { var searchResults = MegaSdk.search(searchNode, name, recursive); for (var i = 0; i < searchResults.size(); i++) { var node = searchResults.get(i); if (node.isFolder() == isFolder && node.getName().ToLower().Equals(name.ToLower())) { return(true); } } return(false); }
/// <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) || !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.LoadSetting <bool>(SettingsResources.UseStagingServer, false)) { MegaSdk.changeApiUrl(AppResources.AR_StagingUrl); MegaSdkFolderLinks.changeApiUrl(AppResources.AR_StagingUrl); } else if (SettingsService.LoadSetting <bool>(SettingsResources.UseStagingServerPort444, false)) { MegaSdk.changeApiUrl(AppResources.AR_StagingUrlPort444, true); MegaSdkFolderLinks.changeApiUrl(AppResources.AR_StagingUrlPort444, true); } }
private void DeleteContact(object obj) { if (FocusedContact != null) { var customMessageDialog = new CustomMessageDialog( AppMessages.DeleteContactQuestion_Title, String.Format(AppMessages.DeleteContactQuestion, FocusedContact.Email), App.AppInformation, MessageDialogButtons.OkCancel); customMessageDialog.OkOrYesButtonTapped += (sender, args) => { MegaSdk.removeContact(MegaSdk.getContact(FocusedContact.Email), new RemoveContactRequestListener(this, FocusedContact)); }; customMessageDialog.ShowDialog(); } }
public void GetAccountDetails() { if (!_accountDetails.IsDataLoaded) { MegaSdk.getAccountDetails(new GetAccountDetailsRequestListener(AccountDetails)); MegaSdk.creditCardQuerySubscriptions(new GetAccountDetailsRequestListener(AccountDetails)); OnUiThread(() => { AccountDetails.HasAvatarImage = UserData.HasAvatarImage; AccountDetails.AvatarUri = UserData.AvatarUri; AccountDetails.Firstname = UserData.Firstname; AccountDetails.Lastname = UserData.Lastname; }); _accountDetails.IsDataLoaded = true; } }
/// <summary> /// Move the node from its current location to a new folder destination /// </summary> /// <param name="newParentNode">The new destination folder</param> /// <returns>Result of the action</returns> public async Task <NodeActionResult> MoveAsync(MNode newParentNode) { // User must be online to perform this operation if (!await IsUserOnlineAsync()) { return(NodeActionResult.NotOnline); } if (MegaSdk.checkMove(OriginalMNode, newParentNode).getErrorCode() != MErrorType.API_OK) { return(NodeActionResult.Failed); } var moveNode = new MoveNodeRequestListenerAsync(); var result = await moveNode.ExecuteAsync(() => MegaSdk.moveNode(OriginalMNode, newParentNode, moveNode)); return(result ? NodeActionResult.Succeeded : NodeActionResult.Failed); }
private void CopyClipboard() { try { Clipboard.SetText(MegaSdk.exportMasterKey()); new CustomMessageDialog( AppMessages.AM_RecoveryKeyCopied_Title, AppMessages.AM_RecoveryKeyCopied, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); } catch (Exception) { new CustomMessageDialog( AppMessages.AM_RecoveryKeyClipboardFailed_Title, AppMessages.AM_RecoveryKeyClipboardFailed, App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); } }
public void CleanRubbishBin() { if (this.RubbishBin.ChildNodes.Count < 1) { return; } var customMessageDialog = new CustomMessageDialog( UiResources.ClearRubbishBin, AppMessages.CleanRubbishBinQuestion, App.AppInformation, MessageDialogButtons.OkCancel, MessageDialogImage.RubbishBin); customMessageDialog.OkOrYesButtonTapped += (sender, args) => { MegaSdk.cleanRubbishBin(new CleanRubbishBinRequestListener()); }; customMessageDialog.ShowDialog(); }
/// <summary> /// Locate the Camera Uploads folder node in the specified root /// </summary> /// <param name="rootNode">Current root node</param> /// <returns>Camera Uploads folder node in</returns> private static MNode FindCameraUploadNode(MNode rootNode) { var childs = MegaSdk.getChildren(rootNode); for (var x = 0; x < childs.size(); x++) { var node = childs.get(x); // Camera Uploads is a folder if (node.getType() != MNodeType.TYPE_FOLDER) { continue; } // Check the folder name if (!node.getName().ToLower().Equals("camera uploads")) { continue; } return(node); } return(null); }
/// <summary> /// Change the API URL. /// </summary> private static async void ChangeApiUrl() { StopChangeApiUrlTimer(); var useStagingServer = SettingsService.Load(ResourceService.SettingsResources.GetString("SR_UseStagingServer"), false); if (!useStagingServer) { var result = await DialogService.ShowOkCancelAsync("Change to a testing server?", "Are you sure you want to change to a testing server? Your account may run irrecoverable problems."); if (!result) { return; } } useStagingServer = !useStagingServer; var newApiUrl = useStagingServer ? ResourceService.AppResources.GetString("AR_StagingUrl") : ResourceService.AppResources.GetString("AR_ApiUrl"); MegaSdk.changeApiUrl(newApiUrl); MegaSdkFolderLinks.changeApiUrl(newApiUrl); SettingsService.Save(ResourceService.SettingsResources.GetString("SR_UseStagingServer"), useStagingServer); // Reset the "Camera Uploads" service if is enabled if (TaskService.IsBackGroundTaskActive(CameraUploadService.TaskEntryPoint, CameraUploadService.TaskName)) { LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Resetting CAMERA UPLOADS service (API URL changed)"); await TaskService.RegisterBackgroundTaskAsync( CameraUploadService.TaskEntryPoint, CameraUploadService.TaskName, new TimeTrigger(CameraUploadService.TaskTimeTrigger, false)); } OnApiUrlChanged(); }
public async Task CreateRootNodeIfNotExists() { MNode cameraUploadsNode = NodeService.FindCameraUploadNode(this.MegaSdk, this.MegaSdk.getRootNode()); if (cameraUploadsNode != null) { return; } var tcs = new TaskCompletionSource <bool>(); var createFolderListener = new CreateCameraUploadsRequestListener(); createFolderListener.RequestFinished += (sender, args) => { tcs.TrySetResult(args.Succeeded); }; MegaSdk.createFolder("Camera Uploads", this.MegaSdk.getRootNode(), createFolderListener); await tcs.Task; }
public async void SaveForOffline() { // User must be online to perform this operation if (!await IsUserOnlineAsync()) { return; } var offlineParentNodePath = OfflineService.GetOfflineParentNodePath(this.OriginalMNode); if (!FolderService.FolderExists(offlineParentNodePath)) { FolderService.CreateFolder(offlineParentNodePath); } var existingNode = SavedForOfflineDB.SelectNodeByFingerprint(MegaSdk.getNodeFingerprint(this.OriginalMNode)); if (existingNode != null) { bool result = this.IsFolder ? await FolderService.CopyFolderAsync(existingNode.LocalPath, offlineParentNodePath) : await FileService.CopyFileAsync(existingNode.LocalPath, offlineParentNodePath); if (result) { SavedForOfflineDB.InsertNode(this.OriginalMNode); } } else { TransferService.MegaTransfers.Add(this.OfflineTransfer); this.OfflineTransfer.StartTransfer(true); } this.IsSavedForOffline = true; OfflineService.CheckOfflineNodePath(this.OriginalMNode); }