public void StartTransfer(bool isSaveForOffline = false)
        {
            switch (Type)
            {
            case TransferType.Download:
            {
                // Download all nodes with the App instance of the SDK and authorize nodes to be downloaded with this SDK instance.
                // Needed to allow transfers resumption of folder link nodes.
                App.MegaSdk.startDownloadWithAppData(this.MegaSdk.authorizeNode(SelectedNode.OriginalMNode),
                                                     FilePath, TransfersService.CreateTransferAppDataString(isSaveForOffline, DownloadFolderPath));
                this.IsSaveForOfflineTransfer = isSaveForOffline;
                break;
            }

            case TransferType.Upload:
            {
                // Start uploads with the flag of temporary source activated to always automatically delete the
                // uploaded file from the upload temporary folder in the sandbox of the app
                App.MegaSdk.startUploadWithDataTempSource(FilePath, SelectedNode.OriginalMNode, String.Empty, true);
                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #2
0
        private async Task RecursiveRemoveForOffline(String sfoPath, String nodeName)
        {
            String newSfoPath = Path.Combine(sfoPath, nodeName);

            // Search if the folder has a pending transfer for offline and cancel it on this case
            TransfersService.CancelPendingNodeOfflineTransfers(String.Concat(newSfoPath, "\\"), this.IsFolder);

            IEnumerable <string> childFolders = Directory.GetDirectories(newSfoPath);

            if (childFolders != null)
            {
                foreach (var folder in childFolders)
                {
                    if (folder != null)
                    {
                        await RecursiveRemoveForOffline(newSfoPath, folder);

                        SavedForOffline.DeleteNodeByLocalPath(Path.Combine(newSfoPath, folder));
                    }
                }
            }

            IEnumerable <string> childFiles = Directory.GetFiles(newSfoPath);

            if (childFiles != null)
            {
                foreach (var file in childFiles)
                {
                    if (file != null)
                    {
                        SavedForOffline.DeleteNodeByLocalPath(Path.Combine(newSfoPath, file));
                    }
                }
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            NavigationParameter navParam = NavigateService.ProcessQueryString(NavigationContext.QueryString);

            if (navParam == NavigationParameter.Downloads)
            {
                TransfersPivot.SelectedItem = DownloadsPivot;
            }

            if (navParam == NavigationParameter.PictureSelected)
            {
                NavigationService.RemoveBackEntry();
            }

            if (navParam == NavigationParameter.AlbumSelected || navParam == NavigationParameter.SelfieSelected)
            {
                NavigationService.RemoveBackEntry();
                NavigationService.RemoveBackEntry();
            }

            if (!NetworkService.IsNetworkAvailable())
            {
                UpdateGUI(false);
                return;
            }

            // Needed on every UI interaction
            App.MegaSdk.retryPendingConnections();

            TransfersService.UpdateMegaTransfersList(App.MegaTransfers);
            _transfersViewModel.MegaTransfers = App.MegaTransfers;
        }
        public async Task RemoveForOffline(AutoResetEvent waitEventRequest = null)
        {
            String parentNodePath = ((new DirectoryInfo(this.NodePath)).Parent).FullName;

            String sfoRootPath = Path.Combine(ApplicationData.Current.LocalFolder.Path,
                                              AppResources.DownloadsDirectory.Replace("\\", ""));

            if (this.IsFolder)
            {
                await RecursiveRemoveForOffline(parentNodePath, this.Name);

                FolderService.DeleteFolder(this.NodePath, true);
            }
            else
            {
                // Search if the file has a pending transfer for offline and cancel it on this case
                TransfersService.CancelPendingNodeOfflineTransfers(this.NodePath, this.IsFolder);

                FileService.DeleteFile(this.NodePath);
            }

            SavedForOffline.DeleteNodeByLocalPath(this.NodePath);

            if (this.ParentCollection != null)
            {
                this.ParentCollection.Remove((IOfflineNode)this);
            }

            if (waitEventRequest != null)
            {
                waitEventRequest.Set();
            }
        }
        public void onTransferTemporaryError(MegaSDK api, MTransfer transfer, MError e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (DebugService.DebugSettings.IsDebugMode || Debugger.IsAttached)
                {
                    if (ProgressService.GetProgressBarBackgroundColor() != (Color)Application.Current.Resources["MegaRedColor"])
                    {
                        ProgressService.ChangeProgressBarBackgroundColor((Color)Application.Current.Resources["MegaRedColor"]);
                    }
                }
            });

            switch (e.getErrorCode())
            {
            case MErrorType.API_EGOINGOVERQUOTA: // Not enough quota
            case MErrorType.API_EOVERQUOTA:      // Overquota error
                ProcessOverquotaError(api, e);
                break;
            }

            // Extra checking to avoid NullReferenceException
            if (transfer == null)
            {
                return;
            }

            // Search the corresponding transfer in the transfers list
            var megaTransfer = TransfersService.SearchTransfer(TransfersService.MegaTransfers.SelectAll(), transfer);

            if (megaTransfer == null)
            {
                return;
            }

            var isBusy           = api.areTransfersPaused((int)transfer.getType()) ? false : true;
            var transferState    = api.areTransfersPaused((int)transfer.getType()) ? MTransferState.STATE_QUEUED : transfer.getState();
            var transferPriority = transfer.getPriority();

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Only update the values if they have changed to improve the UI performance
                if (megaTransfer.Transfer != transfer)
                {
                    megaTransfer.Transfer = transfer;
                }
                if (megaTransfer.IsBusy != isBusy)
                {
                    megaTransfer.IsBusy = isBusy;
                }
                if (megaTransfer.TransferState != transferState)
                {
                    megaTransfer.TransferState = transferState;
                }
                if (megaTransfer.TransferPriority != transferPriority)
                {
                    megaTransfer.TransferPriority = transferPriority;
                }
            });
        }
        public async Task VoteAsync_ShouldRetutnCorrectResult()
        {
            MapperInitializer.InitializeMapper();
            var context            = ApplicationDbContextInMemoryFactory.InitializeContext();
            var transferRepository = new EfDeletableEntityRepository <Transfer>(context);
            var userRepository     = new EfDeletableEntityRepository <ApplicationUser>(context);
            var transfersService   = new TransfersService(transferRepository, userRepository);
            var seeder             = new DbContextTestsSeeder();
            await seeder.SeedTransfersAsync(context);

            var result = await transfersService.VoteAsync(1);

            Assert.True(result == 1, ErrorMessage);
        }
        public async Task IsDriverAvailableByDate_ShouldRetutnFalse()
        {
            MapperInitializer.InitializeMapper();
            var context            = ApplicationDbContextInMemoryFactory.InitializeContext();
            var transferRepository = new EfDeletableEntityRepository <Transfer>(context);
            var userRepository     = new EfDeletableEntityRepository <ApplicationUser>(context);
            var transfersService   = new TransfersService(transferRepository, userRepository);
            var seeder             = new DbContextTestsSeeder();
            await seeder.SeedTransfersAsync(context);

            var result = await transfersService.IsDriverAvailableByDate(DateTime.Now, "bcd");

            Assert.False(result, ErrorMessage);
        }
Beispiel #8
0
        public async Task <bool> RemoveForOffline()
        {
            bool result;

            MNode parentNode = SdkService.MegaSdk.getParentNode(this.OriginalMNode);

            String parentNodePath = Path.Combine(ApplicationData.Current.LocalFolder.Path,
                                                 AppResources.DownloadsDirectory.Replace("\\", ""),
                                                 (SdkService.MegaSdk.getNodePath(parentNode)).Remove(0, 1).Replace("/", "\\"));

            String sfoRootPath = Path.Combine(ApplicationData.Current.LocalFolder.Path,
                                              AppResources.DownloadsDirectory.Replace("\\", ""));

            var nodePath = Path.Combine(parentNodePath, this.Name);

            if (this.IsFolder)
            {
                await RecursiveRemoveForOffline(parentNodePath, this.Name);

                result = FolderService.DeleteFolder(nodePath, true);
            }
            else
            {
                // Search if the file has a pending transfer for offline and cancel it on this case
                TransfersService.CancelPendingNodeOfflineTransfers(nodePath, this.IsFolder);

                result = FileService.DeleteFile(nodePath);
            }

            SavedForOffline.DeleteNodeByLocalPath(nodePath);
            this.IsAvailableOffline = this.IsSelectedForOffline = false;

            // Check if the previous folders of the path are empty and
            // remove from the offline and the DB on this case
            while (String.Compare(parentNodePath, sfoRootPath) != 0)
            {
                var folderPathToRemove = parentNodePath;
                parentNodePath = ((new DirectoryInfo(parentNodePath)).Parent).FullName;

                if (FolderService.IsEmptyFolder(folderPathToRemove))
                {
                    result = result & FolderService.DeleteFolder(folderPathToRemove);
                    SavedForOffline.DeleteNodeByLocalPath(folderPathToRemove);
                }
            }

            return(result);
        }
        public async Task GetByUserAsync_ShouldReturnAllReservationsForUser(string clientId, int?reservationsPerPage, int skip)
        {
            MapperInitializer.InitializeMapper();
            var context            = ApplicationDbContextInMemoryFactory.InitializeContext();
            var transferRepository = new EfDeletableEntityRepository <Transfer>(context);
            var userRepository     = new EfDeletableEntityRepository <ApplicationUser>(context);
            var transfersService   = new TransfersService(transferRepository, userRepository);
            var seeder             = new DbContextTestsSeeder();
            await seeder.SeedTransfersAsync(context);

            await seeder.SeedUsersAsync(context);

            var result = await transfersService.GetByUserAsync(clientId, reservationsPerPage, skip);

            Assert.True(result.ToList().Count == 3, ErrorMessage);
        }
Beispiel #10
0
        public void onTransferStart(MegaSDK api, MTransfer transfer)
        {
            TransferObjectModel megaTransfer = null;

            if (transfer.getType() == MTransferType.TYPE_DOWNLOAD)
            {
                // If is a public node
                MNode node = transfer.getPublicMegaNode();
                if (node == null) // If not
                {
                    node = api.getNodeByHandle(transfer.getNodeHandle());
                }

                if (node != null)
                {
                    megaTransfer = new TransferObjectModel(api,
                                                           NodeService.CreateNew(api, App.AppInformation, node, ContainerType.CloudDrive),
                                                           TransferType.Download, transfer.getPath());
                }
            }
            else
            {
                megaTransfer = new TransferObjectModel(api, App.MainPageViewModel.CloudDrive.FolderRootNode,
                                                       TransferType.Upload, transfer.getPath());
            }

            if (megaTransfer != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    TransfersService.GetTransferAppData(transfer, megaTransfer);

                    megaTransfer.Transfer                      = transfer;
                    megaTransfer.Status                        = TransferStatus.Queued;
                    megaTransfer.CancelButtonState             = true;
                    megaTransfer.TransferButtonIcon            = new Uri("/Assets/Images/cancel transfers.Screen-WXGA.png", UriKind.Relative);
                    megaTransfer.TransferButtonForegroundColor = new SolidColorBrush(Colors.White);
                    megaTransfer.IsBusy                        = true;
                    megaTransfer.TotalBytes                    = transfer.getTotalBytes();
                    megaTransfer.TransferedBytes               = transfer.getTransferredBytes();
                    megaTransfer.TransferSpeed                 = transfer.getSpeed().ToStringAndSuffixPerSecond();

                    App.MegaTransfers.Add(megaTransfer);
                    Transfers.Add(megaTransfer);
                });
            }
        }
        public async Task PayByIdAsync_ShouldRetutnCorrectResult_RankPlatinumUser()
        {
            MapperInitializer.InitializeMapper();
            var context            = ApplicationDbContextInMemoryFactory.InitializeContext();
            var transferRepository = new EfDeletableEntityRepository <Transfer>(context);
            var userRepository     = new EfDeletableEntityRepository <ApplicationUser>(context);
            var transfersService   = new TransfersService(transferRepository, userRepository);
            var seeder             = new DbContextTestsSeeder();
            await seeder.SeedTransfersAsync(context);

            await seeder.SeedUsersAsync(context);

            var transfer = transferRepository.GetByIdWithDeletedAsync(8);
            var result   = await transfersService.PayByIdAsync(7, "efg");

            Assert.True(result == 9, ErrorMessage);
        }
Beispiel #12
0
        public async Task TestMultipleTask()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);
            var service   = new TransfersService(dbContext);

            await dbContext.Transfers.AddAsync(new Transfer { Credits = 5, ReceiverId = "pesho", SenderId = "gosho", Id = "transfer1", Message = "helloWorld" });

            await dbContext.Transfers.AddAsync(new Transfer { Credits = 5, ReceiverId = "misho", SenderId = "mitko", Id = "transfer2", Message = "helloWorld2" });

            await dbContext.Transfers.AddAsync(new Transfer { Credits = 5, ReceiverId = "ivan", SenderId = "dragan", Id = "transfer3", Message = "helloWorld3" });

            await dbContext.SaveChangesAsync();

            Assert.Equal(3, service.GetAll().Count());
            Assert.IsAssignableFrom <IEnumerable <Transfer> >(service.GetAll());
            Assert.IsType <List <Transfer> >(service.GetByReceiverId("gosho"));
            Assert.IsType <List <Transfer> >(service.GetBySenderId("pesho"));
            Assert.Empty(service.GetByReceiverId("hh"));
        }
        public void onTransferStart(MegaSDK api, MTransfer transfer)
        {
            // Extra checking to avoid NullReferenceException
            if (transfer == null)
            {
                return;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var megaTransfer = TransfersService.AddTransferToList(TransfersService.MegaTransfers, transfer);
                if (megaTransfer != null)
                {
                    TransfersService.GetTransferAppData(transfer, megaTransfer);

                    megaTransfer.Transfer           = transfer;
                    megaTransfer.IsBusy             = api.areTransfersPaused((int)transfer.getType()) ? false : true;
                    megaTransfer.TransferState      = api.areTransfersPaused((int)transfer.getType()) ? MTransferState.STATE_QUEUED : transfer.getState();
                    megaTransfer.TotalBytes         = transfer.getTotalBytes();
                    megaTransfer.TransferPriority   = transfer.getPriority();
                    megaTransfer.TransferButtonIcon = new Uri("/Assets/Images/cancel transfers.Screen-WXGA.png", UriKind.Relative);
                }
            });
        }
Beispiel #14
0
        public static void Sort(ObservableCollection <TransferObjectModel> transferList,
                                TransferObjectModel transferObject)
        {
            if (transferList == null || transferObject == null)
            {
                return;
            }

            try
            {
                var existing = (transferObject.Transfer != null) ?
                               TransfersService.SearchTransfer(transferList, transferObject.Transfer) :
                               transferList.FirstOrDefault(t => (t.TransferPath != null && t.TransferPath.Equals(transferObject.TransferPath)));

                bool handled = false;
                bool move    = existing != null;
                var  index   = transferList.IndexOf(existing);
                var  count   = transferList.Count - 1;

                for (var i = 0; i <= count; i++)
                {
                    if ((int)transferObject.TransferPriority > (int)transferList[i].TransferPriority)
                    {
                        continue;
                    }

                    if (move)
                    {
                        if (index != i)
                        {
                            transferList.RemoveAt(index);
                            transferList.Insert(i, transferObject);
                        }
                    }
                    else
                    {
                        transferList.Insert(i, transferObject);
                    }
                    handled = true;
                    break;
                }

                if (handled)
                {
                    return;
                }

                if (move)
                {
                    if (index != count)
                    {
                        transferList.RemoveAt(index);
                        transferList.Insert(count, transferObject);
                    }
                }
                else
                {
                    transferList.Add(transferObject);
                }
            }
            catch (Exception e)
            {
                var message = (transferObject.DisplayName == null) ? "Error sorting transfer" :
                              string.Format("Error sorting transfer. File: '{0}'", transferObject.DisplayName);
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, message, e);
                return;
            }
        }
        public void onTransferUpdate(MegaSDK api, MTransfer transfer)
        {
            // Extra checking to avoid NullReferenceException
            if (transfer == null)
            {
                return;
            }

            // Search the corresponding transfer in the transfers list
            var megaTransfer = TransfersService.SearchTransfer(TransfersService.MegaTransfers.SelectAll(), transfer);

            if (megaTransfer == null)
            {
                return;
            }

            var isBusy            = api.areTransfersPaused((int)transfer.getType()) ? false : true;
            var transferState     = api.areTransfersPaused((int)transfer.getType()) ? MTransferState.STATE_QUEUED : transfer.getState();
            var totalBytes        = transfer.getTotalBytes();
            var transferedBytes   = transfer.getTransferredBytes();
            var transferSpeed     = transfer.getSpeed().ToStringAndSuffixPerSecond();
            var transferMeanSpeed = transfer.getMeanSpeed();
            var transferPriority  = transfer.getPriority();

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (ProgressService.GetProgressBarBackgroundColor() != (Color)Application.Current.Resources["PhoneChromeColor"])
                {
                    ProgressService.ChangeProgressBarBackgroundColor((Color)Application.Current.Resources["PhoneChromeColor"]);
                }

                // Only update the values if they have changed to improve the UI performance
                if (megaTransfer.Transfer != transfer)
                {
                    megaTransfer.Transfer = transfer;
                }
                if (megaTransfer.IsBusy != isBusy)
                {
                    megaTransfer.IsBusy = isBusy;
                }
                if (megaTransfer.TransferState != transferState)
                {
                    megaTransfer.TransferState = transferState;
                }
                if (megaTransfer.TotalBytes != totalBytes)
                {
                    megaTransfer.TotalBytes = totalBytes;
                }
                if (megaTransfer.TransferedBytes != transferedBytes)
                {
                    megaTransfer.TransferedBytes = transferedBytes;
                }
                if (megaTransfer.TransferSpeed != transferSpeed)
                {
                    megaTransfer.TransferSpeed = transferSpeed;
                }
                if (megaTransfer.TransferMeanSpeed != transferMeanSpeed)
                {
                    megaTransfer.TransferMeanSpeed = transferMeanSpeed;
                }
                if (megaTransfer.TransferPriority != transferPriority)
                {
                    megaTransfer.TransferPriority = transferPriority;
                }
            });
        }
        public async void onTransferFinish(MegaSDK api, MTransfer transfer, MError e)
        #endif
        {
            // Search the corresponding transfer in the transfers list
            var megaTransfer = TransfersService.SearchTransfer(TransfersService.MegaTransfers.SelectAll(), transfer);

            if (megaTransfer == null)
            {
                return;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                ProgressService.ChangeProgressBarBackgroundColor((Color)Application.Current.Resources["PhoneChromeColor"]);

                megaTransfer.Transfer         = transfer;
                megaTransfer.TransferState    = transfer.getState();
                megaTransfer.TransferPriority = transfer.getPriority();

                TransfersService.GetTransferAppData(transfer, megaTransfer);

                megaTransfer.TotalBytes      = transfer.getTotalBytes();
                megaTransfer.TransferedBytes = transfer.getTransferredBytes();
                megaTransfer.TransferSpeed   = string.Empty;
            });

            switch (e.getErrorCode())
            {
            case MErrorType.API_OK:
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    megaTransfer.TransferedBytes    = megaTransfer.TotalBytes;
                    megaTransfer.TransferButtonIcon = new Uri("/Assets/Images/completed transfers.Screen-WXGA.png", UriKind.Relative);
                });

                switch (megaTransfer.Type)
                {
                case MTransferType.TYPE_DOWNLOAD:
                    if (megaTransfer.IsSaveForOfflineTransfer)         //If is a save for offline download transfer
                    {
                        var node = megaTransfer.SelectedNode as NodeViewModel;
                        if (node != null)
                        {
                            // Need get the path on the transfer finish because the file name can be changed
                            // if already exists in the destiny path.
                            var newOfflineLocalPath = Path.Combine(transfer.getParentPath(), transfer.getFileName()).Replace("/", "\\");

                            var sfoNode = new SavedForOffline
                            {
                                Fingerprint          = SdkService.MegaSdk.getNodeFingerprint(node.OriginalMNode),
                                Base64Handle         = node.OriginalMNode.getBase64Handle(),
                                LocalPath            = newOfflineLocalPath,
                                IsSelectedForOffline = true
                            };

                            // If is a public node (link) the destination folder is the SFO root, so the parent handle
                            // is the handle of the root node.
                            if (node.ParentContainerType != ContainerType.PublicLink)
                            {
                                sfoNode.ParentBase64Handle = (SdkService.MegaSdk.getParentNode(node.OriginalMNode)).getBase64Handle();
                            }
                            else
                            {
                                sfoNode.ParentBase64Handle = SdkService.MegaSdk.getRootNode().getBase64Handle();
                            }

                            if (!(SavedForOffline.ExistsNodeByLocalPath(sfoNode.LocalPath)))
                            {
                                SavedForOffline.Insert(sfoNode);
                            }
                            else
                            {
                                SavedForOffline.UpdateNode(sfoNode);
                            }

                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                node.IsAvailableOffline = node.IsSelectedForOffline = true;
                                TransfersService.MoveMegaTransferToCompleted(TransfersService.MegaTransfers, megaTransfer);
                            });

                                    #if WINDOWS_PHONE_80
                            //If is download transfer of an image file
                            var imageNode = node as ImageNodeViewModel;
                            if (imageNode != null)
                            {
                                Deployment.Current.Dispatcher.BeginInvoke(() => imageNode.ImageUri = new Uri(megaTransfer.TransferPath));

                                bool exportToPhotoAlbum = SettingsService.LoadSetting <bool>(SettingsResources.ExportImagesToPhotoAlbum, false);
                                if (exportToPhotoAlbum)
                                {
                                    Deployment.Current.Dispatcher.BeginInvoke(() => imageNode.SaveImageToCameraRoll(false));
                                }
                            }
                                    #endif
                        }
                    }
                    else         //If is a standard download transfer (no for save for offline)
                    {
                        bool result = false;

                        //If is download transfer of an image file
                        var imageNode = megaTransfer.SelectedNode as ImageNodeViewModel;
                        if (imageNode != null)
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() => imageNode.ImageUri = new Uri(megaTransfer.TransferPath));

                            if (megaTransfer.AutoLoadImageOnFinish)
                            {
                                Deployment.Current.Dispatcher.BeginInvoke(() =>
                                {
                                    if (imageNode.OriginalMNode.hasPreview())
                                    {
                                        return;
                                    }
                                    imageNode.PreviewImageUri = new Uri(imageNode.PreviewPath);
                                });
                            }

                                    #if WINDOWS_PHONE_81
                            try
                            {
                                result = await megaTransfer.FinishDownload(megaTransfer.TransferPath, imageNode.Name);
                            }
                            catch (Exception exception)
                            {
                                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error finishing a download to an external location", exception);
                            }
                                    #endif
                        }
                                #if WINDOWS_PHONE_81
                        else         //If is a download transfer of other file type
                        {
                            var node = megaTransfer.SelectedNode as FileNodeViewModel;
                            if (node != null)
                            {
                                try
                                {
                                    result = await megaTransfer.FinishDownload(megaTransfer.TransferPath, node.Name);
                                }
                                catch (Exception exception)
                                {
                                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error finishing a download to an external location", exception);
                                }
                            }
                        }
                                #endif

                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            if (!result)
                            {
                                megaTransfer.TransferState = MTransferState.STATE_FAILED;
                            }
                            else
                            {
                                TransfersService.MoveMegaTransferToCompleted(TransfersService.MegaTransfers, megaTransfer);
                            }
                        });
                    }
                    break;

                case MTransferType.TYPE_UPLOAD:
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                                                              TransfersService.MoveMegaTransferToCompleted(TransfersService.MegaTransfers, megaTransfer));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                break;

            case MErrorType.API_EGOINGOVERQUOTA: // Not enough quota
            case MErrorType.API_EOVERQUOTA:      // Storage overquota error
                // Stop all upload transfers
                LogService.Log(MLogLevel.LOG_LEVEL_INFO,
                               string.Format("Storage quota exceeded ({0}) - Canceling uploads", e.getErrorCode().ToString()));
                api.cancelTransfers((int)MTransferType.TYPE_UPLOAD);

                // Disable the "camera upload" service if is enabled
                if (MediaService.GetAutoCameraUploadStatus())
                {
                    LogService.Log(MLogLevel.LOG_LEVEL_INFO,
                                   string.Format("Storage quota exceeded ({0}) - Disabling CAMERA UPLOADS service", e.getErrorCode().ToString()));
                    MediaService.SetAutoCameraUpload(false);
                    SettingsService.SaveSetting(SettingsResources.CameraUploadsIsEnabled, false);
                }

                Deployment.Current.Dispatcher.BeginInvoke(() => DialogService.ShowOverquotaAlert());
                break;

            case MErrorType.API_EINCOMPLETE:
                Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.TransferState = MTransferState.STATE_CANCELLED);
                break;

            default:
                Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.TransferState = MTransferState.STATE_FAILED);
                switch (megaTransfer.Type)
                {
                case MTransferType.TYPE_DOWNLOAD:
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        new CustomMessageDialog(
                            AppMessages.DownloadNodeFailed_Title,
                            String.Format(AppMessages.DownloadNodeFailed, e.getErrorString()),
                            App.AppInformation,
                            MessageDialogButtons.Ok).ShowDialog();
                    });

                    break;

                case MTransferType.TYPE_UPLOAD:
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        new CustomMessageDialog(
                            AppMessages.UploadNodeFailed_Title,
                            String.Format(AppMessages.UploadNodeFailed, e.getErrorString()),
                            App.AppInformation,
                            MessageDialogButtons.Ok).ShowDialog();
                    });

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                break;
            }
        }
Beispiel #17
0
        public async void onTransferFinish(MegaSDK api, MTransfer transfer, MError e)
        #endif
        {
            // Extra checking to avoid NullReferenceException
            if (transfer == null)
            {
                return;
            }

            // Use a temp variable to avoid InvalidOperationException
            var transfersList = Transfers.ToList();

            // Extra checking during finding to avoid NullReferenceException
            var megaTransfer = transfersList.FirstOrDefault(t =>
                                                            (t.Transfer != null) && (t.Transfer.getTag() == transfer.getTag()));

            if (megaTransfer != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ProgressService.ChangeProgressBarBackgroundColor((Color)Application.Current.Resources["PhoneChromeColor"]);

                    TransfersService.GetTransferAppData(transfer, megaTransfer);

                    megaTransfer.TotalBytes        = transfer.getTotalBytes();
                    megaTransfer.TransferedBytes   = transfer.getTransferredBytes();
                    megaTransfer.TransferSpeed     = transfer.getSpeed().ToStringAndSuffixPerSecond();
                    megaTransfer.IsBusy            = false;
                    megaTransfer.CancelButtonState = false;
                });

                switch (e.getErrorCode())
                {
                case MErrorType.API_OK:
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            megaTransfer.TransferedBytes               = megaTransfer.TotalBytes;
                            megaTransfer.TransferButtonIcon            = new Uri("/Assets/Images/completed transfers.Screen-WXGA.png", UriKind.Relative);
                            megaTransfer.TransferButtonForegroundColor = (SolidColorBrush)Application.Current.Resources["MegaRedSolidColorBrush"];
                        });

                    switch (megaTransfer.Type)
                    {
                    case TransferType.Download:
                        if (megaTransfer.IsSaveForOfflineTransfer)             //If is a save for offline download transfer
                        {
                            var node = megaTransfer.SelectedNode as NodeViewModel;
                            if (node != null)
                            {
                                // Need get the path on the transfer finish because the file name can be changed
                                // if already exists in the destiny path.
                                var newOfflineLocalPath = Path.Combine(transfer.getParentPath(), transfer.getFileName()).Replace("/", "\\");

                                var sfoNode = new SavedForOffline
                                {
                                    Fingerprint          = App.MegaSdk.getNodeFingerprint(node.OriginalMNode),
                                    Base64Handle         = node.OriginalMNode.getBase64Handle(),
                                    LocalPath            = newOfflineLocalPath,
                                    IsSelectedForOffline = true
                                };

                                // If is a public node (link) the destination folder is the SFO root, so the parent handle
                                // is the handle of the root node.
                                if (node.ParentContainerType != ContainerType.PublicLink)
                                {
                                    sfoNode.ParentBase64Handle = (App.MegaSdk.getParentNode(node.OriginalMNode)).getBase64Handle();
                                }
                                else
                                {
                                    sfoNode.ParentBase64Handle = App.MegaSdk.getRootNode().getBase64Handle();
                                }

                                if (!(SavedForOffline.ExistsNodeByLocalPath(sfoNode.LocalPath)))
                                {
                                    SavedForOffline.Insert(sfoNode);
                                }
                                else
                                {
                                    SavedForOffline.UpdateNode(sfoNode);
                                }

                                Deployment.Current.Dispatcher.BeginInvoke(() => node.IsAvailableOffline = node.IsSelectedForOffline = true);

                                            #if WINDOWS_PHONE_80
                                //If is download transfer of an image file
                                var imageNode = node as ImageNodeViewModel;
                                if (imageNode != null)
                                {
                                    Deployment.Current.Dispatcher.BeginInvoke(() => imageNode.ImageUri = new Uri(megaTransfer.FilePath));

                                    bool exportToPhotoAlbum = SettingsService.LoadSetting <bool>(SettingsResources.ExportImagesToPhotoAlbum, false);
                                    if (exportToPhotoAlbum)
                                    {
                                        Deployment.Current.Dispatcher.BeginInvoke(() => imageNode.SaveImageToCameraRoll(false));
                                    }
                                }
                                            #endif
                            }
                        }
                        else             //If is a standard download transfer (no for save for offline)
                        {
                            //If is download transfer of an image file
                            var imageNode = megaTransfer.SelectedNode as ImageNodeViewModel;
                            if (imageNode != null)
                            {
                                Deployment.Current.Dispatcher.BeginInvoke(() => imageNode.ImageUri = new Uri(megaTransfer.FilePath));

                                if (megaTransfer.AutoLoadImageOnFinish)
                                {
                                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                                        {
                                            if (imageNode.OriginalMNode.hasPreview())
                                            {
                                                return;
                                            }
                                            imageNode.PreviewImageUri = new Uri(imageNode.PreviewPath);
                                            imageNode.IsBusy          = false;
                                        });
                                }

                                            #if WINDOWS_PHONE_81
                                if (!await megaTransfer.FinishDownload(megaTransfer.FilePath, imageNode.Name))
                                {
                                    Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.Status = TransferStatus.Error);
                                    break;
                                }
                                            #endif
                            }
                                        #if WINDOWS_PHONE_81
                            else             //If is a download transfer of other file type
                            {
                                var node = megaTransfer.SelectedNode as FileNodeViewModel;
                                if (node != null)
                                {
                                    if (!await megaTransfer.FinishDownload(megaTransfer.FilePath, node.Name))
                                    {
                                        Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.Status = TransferStatus.Error);
                                        break;
                                    }
                                }
                            }
                                        #endif
                        }

                        Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.Status = TransferStatus.Downloaded);
                        break;

                    case TransferType.Upload:
                        Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.Status = TransferStatus.Uploaded);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    break;
                }

                case MErrorType.API_EOVERQUOTA:
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            // Stop all upload transfers
                            api.cancelTransfers((int)MTransferType.TYPE_UPLOAD);

                            // Disable the "camera upload" service
                            MediaService.SetAutoCameraUpload(false);
                            SettingsService.SaveSetting(SettingsResources.CameraUploadsIsEnabled, false);

                            DialogService.ShowOverquotaAlert();
                        });

                    break;
                }

                case MErrorType.API_EINCOMPLETE:
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.Status = TransferStatus.Canceled);
                    break;
                }

                default:
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => megaTransfer.Status = TransferStatus.Error);
                    switch (megaTransfer.Type)
                    {
                    case TransferType.Download:
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                new CustomMessageDialog(
                                    AppMessages.DownloadNodeFailed_Title,
                                    String.Format(AppMessages.DownloadNodeFailed, e.getErrorString()),
                                    App.AppInformation,
                                    MessageDialogButtons.Ok).ShowDialog();
                            });

                        break;

                    case TransferType.Upload:
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                new CustomMessageDialog(
                                    AppMessages.UploadNodeFailed_Title,
                                    String.Format(AppMessages.UploadNodeFailed, e.getErrorString()),
                                    App.AppInformation,
                                    MessageDialogButtons.Ok).ShowDialog();
                            });

                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    break;
                }
                }
            }
        }
 private void CleanTransfers(object obj)
 {
     TransfersService.UpdateMegaTransferList(TransfersService.MegaTransfers, this.Type, true);
 }
 public void UpdateTransfers(bool cleanTransfers = false)
 {
     TransfersService.UpdateMegaTransferList(TransfersService.MegaTransfers, this.Type, cleanTransfers);
 }
 private void OnCleanUpTransfersClick(object sender, EventArgs e)
 {
     TransfersService.UpdateMegaTransfersList(App.MegaTransfers);
 }