Пример #1
0
 /// <summary>
 /// Method called when a network status changed event is triggered
 /// </summary>
 /// <param name="sender">Object that sent the event</param>
 private void OnNetworkStatusChanged(object sender)
 {
     LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Network status has changed.");
     NetworkService.CheckNetworkChange();
     UpdateConnectionInformation();
     NetworkStatusChanged?.Invoke(this, EventArgs.Empty);
 }
Пример #2
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.
        /// Other entry points will be used in specific cases, such as when the
        /// application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            NetworkService.CheckNetworkChange();

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
            // Load product xml for IAP testing
            await LicenseService.LoadSimulatorAsync();
#endif
            Frame rootFrame = CreateRootFrame();

            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //TODO: Load state from previously suspended application
            }

            if (e.PrelaunchActivated == false)
            {
                // When the navigation stack isn't restored navigate to the first page, configuring
                // the new page by passing required information as a navigation parameter
                if (rootFrame.Content == null)
                {
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }

                // Ensure the current window is active
                Window.Current.Activate();
            }
        }
Пример #3
0
 // Code to execute when the application is activated (brought to foreground)
 // This code will not execute when the application is first launched
 private void Application_Activated(object sender, ActivatedEventArgs e)
 {
     // Telerik Diagnostics
     ApplicationUsageHelper.OnApplicationActivated();
     AppInformation.IsStartupModeActivate = true;
     AppInformation.HasPinLockIntroduced  = false;
     NetworkService.CheckNetworkChange();
 }
Пример #4
0
        // Code to execute when the application detects a Network change.
        private static void NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            switch (e.NotificationType)
            {
            case NetworkNotificationType.InterfaceConnected:
            case NetworkNotificationType.CharacteristicUpdate:
                NetworkService.CheckNetworkChange();
                break;

            case NetworkNotificationType.InterfaceDisconnected:
            default:
                break;
            }
        }
Пример #5
0
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            // Initialize Telerik Diagnostics with the actual app version information
            ApplicationUsageHelper.Init(AppService.GetAppVersion());
            AppInformation.HasPinLockIntroduced = false;
            NetworkService.CheckNetworkChange();

            #if WINDOWS_PHONE_81
            // Code to intercept files that are send to MEGA as share target
            var shareEventArgs = e as ShareLaunchingEventArgs;
            if (shareEventArgs != null)
            {
                this.ShareOperation = shareEventArgs.ShareTargetActivatedEventArgs.ShareOperation;
            }
            #endif
        }
Пример #6
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            // Initialisation SDK succeeded
            scheduledAgent = this;

            // Check for network changes
            NetworkService.CheckNetworkChange();

            // Set the API to use depending on the settings
            if (SettingsService.LoadSetting <bool>("{BA40B745-D0F5-4AD5-A539-44B1403A9EB8}", false))
            {
                SdkService.MegaSdk.changeApiUrl("https://staging.api.mega.co.nz/");
            }
            else if (SettingsService.LoadSetting <bool>("{E53E24D2-5CD9-410C-BC3A-6DD2A88C81EE}", false))
            {
                SdkService.MegaSdk.changeApiUrl("https://staging.api.mega.co.nz:444/", true);
            }
            else
            {
                SdkService.MegaSdk.changeApiUrl("https://g.api.mega.co.nz/");
            }

            // Log message to indicate that the service is invoked and the last exit reason
            LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Service invoked. Last exit reason: " +
                           task.LastExitReason);

            // Add notifications listener
            SdkService.MegaSdk.addGlobalListener(new MegaGlobalListener());

            // Notify complete when storage quota exceeded error is raised in the transferlistener
            // Notify complete will retry in the next task run
            var megaTransferListener = new MegaTransferListener();

            megaTransferListener.StorageQuotaExceeded += (sender, args) =>
            {
                scheduledAgent.NotifyComplete();
            };

            // Add transfers listener
            SdkService.MegaSdk.addTransferListener(megaTransferListener);

            // Fast login with session token that was saved during MEGA app initial login
            FastLogin();
        }
Пример #7
0
        /// <summary>
        /// Handle protocol activations.
        /// </summary>
        /// <param name="e">Details about the activate request and process.</param>
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            NetworkService.CheckNetworkChange();

            if (e.Kind == ActivationKind.Protocol)
            {
                // Handle URI activation
                ProtocolActivatedEventArgs eventArgs = e as ProtocolActivatedEventArgs;

                // Initialize the links information
                LinkInformationService.Reset();

                bool      validUri  = true;
                Exception exception = null;
                try
                {
                    validUri = eventArgs.Uri.IsWellFormedOriginalString();
                    if (validUri)
                    {
                        // Use OriginalString to keep uppercase and lowercase letters
                        LinkInformationService.ActiveLink = UriService.ReformatUri(eventArgs.Uri.OriginalString);
                    }
                }
                catch (UriFormatException ex)
                {
                    validUri  = false;
                    exception = ex;
                }
                finally
                {
                    if (!validUri)
                    {
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Invalid URI detected during app activation", exception);
                        await DialogService.ShowAlertAsync(ResourceService.AppMessages.GetString("AM_InvalidUri_Title"),
                                                           ResourceService.AppMessages.GetString("AM_InvalidUri"));
                    }
                }

                Frame rootFrame = CreateRootFrame();

                if (eventArgs.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // When the navigation stack isn't restored navigate to the first page, configuring
                // the new page by passing required information as a navigation parameter
                if (rootFrame.Content == null)
                {
                    rootFrame.Navigate(typeof(MainPage), eventArgs);
                }

                // Ensure the current window is active
                Window.Current.Activate();

                // Check session and special navigation
                await AppService.CheckActiveAndOnlineSessionAsync();

                // Validate product subscription license on background thread
                var task = Task.Run(() => LicenseService.ValidateLicensesAsync());
            }
        }
Пример #8
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            // Check for network changes
            NetworkService.CheckNetworkChange();

            // Set the API to use depending on the settings
            if (SettingsService.LoadSetting(ResourceService.SettingsResources.GetString("SR_UseStagingServer"), false))
            {
                SdkService.MegaSdk.changeApiUrl("https://staging.api.mega.co.nz/");
            }
            else if (SettingsService.LoadSetting(ResourceService.SettingsResources.GetString("SR_UseStagingServerPort444"), false))
            {
                SdkService.MegaSdk.changeApiUrl("https://staging.api.mega.co.nz:444/", true);
            }
            else
            {
                SdkService.MegaSdk.changeApiUrl("https://g.api.mega.co.nz/");
            }

            // Log message to indicate that the service is invoked
            LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Service invoked.");

            // Load the connection upload settings
            CameraUploadsConnectionType cameraUploadsConnectionType = CameraUploadsConnectionType.EthernetWifiOnly;

            try
            {
                cameraUploadsConnectionType = (CameraUploadsConnectionType)await SettingsService.LoadSettingFromFileAsync <int>("CameraUploadsSettingsHowKey");
            }
            catch (Exception e)
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Could not load settings", e);
            }

            if (!CheckNetWork(cameraUploadsConnectionType))
            {
                LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Task finished: connection type");
                _deferral.Complete();
                return;
            }

            SdkService.InitializeSdkParams();

            var loggedIn = await LoginAsync();

            if (loggedIn)
            {
                var fetched = await FetchNodesAsync();

                if (fetched)
                {
                    // Add notifications listener
                    var megaGlobalListener = new MegaGlobalListener();
                    SdkService.MegaSdk.addGlobalListener(megaGlobalListener);

                    // Enable the transfers resumption for the Camera Uploads service
                    await megaGlobalListener.ExecuteAsync(() => SdkService.MegaSdk.enableTransferResumption());

                    var cameraUploadRootNode = await SdkService.GetCameraUploadRootNodeAsync();

                    if (cameraUploadRootNode == null)
                    {
                        // No camera upload node found or created
                        // Just finish this run and try again next time
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "No Camera Uploads folder detected/created");
                        _deferral.Complete();
                        return;
                    }

                    // Load the file upload settings
                    CameraUploadsFileType cameraUploadsFileType = CameraUploadsFileType.PhotoAndVideo;
                    try
                    {
                        cameraUploadsFileType = (CameraUploadsFileType)await SettingsService.LoadSettingFromFileAsync <int>("CameraUploadsSettingsFileKey");
                    }
                    catch (Exception e)
                    {
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Could not load settings", e);
                    }

                    var uploadFolders = new List <StorageFolder>();
                    switch (cameraUploadsFileType)
                    {
                    case CameraUploadsFileType.PhotoAndVideo:
                        uploadFolders.Add(KnownFolders.PicturesLibrary);
                        uploadFolders.Add(KnownFolders.VideosLibrary);
                        break;

                    case CameraUploadsFileType.PhotoOnly:
                        uploadFolders.Add(KnownFolders.PicturesLibrary);
                        break;

                    case CameraUploadsFileType.VideoOnly:
                        uploadFolders.Add(KnownFolders.VideosLibrary);
                        break;
                    }

                    // Get the IMAGE and/or VIDEO files to upload to MEGA
                    var fileToUpload = await TaskService.GetAvailableUploadAsync(
                        TaskService.ImageDateSetting, uploadFolders.ToArray());

                    foreach (var storageFile in fileToUpload)
                    {
                        // Skip the current file if it has failed more than the max error count
                        if (await ErrorHandlingService.SkipFileAsync(
                                storageFile.Name,
                                ErrorHandlingService.ImageErrorFileSetting,
                                ErrorHandlingService.ImageErrorCountSetting))
                        {
                            continue;
                        }

                        if (!CheckNetWork(cameraUploadsConnectionType))
                        {
                            break;
                        }

                        // Calculate time for fingerprint check and upload
                        ulong mtime = TaskService.CalculateMtime(storageFile.DateCreated.DateTime);
                        try
                        {
                            using (var fs = await storageFile.OpenStreamForReadAsync())
                            {
                                var isUploaded = SdkService.IsAlreadyUploaded(storageFile, fs, cameraUploadRootNode, mtime);
                                if (isUploaded)
                                {
                                    await TaskService.SaveLastUploadDateAsync(storageFile, TaskService.ImageDateSetting);

                                    continue;
                                }
                                await UploadAsync(storageFile, fs, cameraUploadRootNode, mtime);

                                // No error, clear error storage
                                await ErrorHandlingService.ClearAsync(ErrorHandlingService.ImageErrorFileSetting,
                                                                      ErrorHandlingService.ImageErrorCountSetting);
                            }
                        }
                        catch (OutOfMemoryException e)
                        {
                            // Something went wrong (could be memory limit)
                            // Just finish this run and try again next time
                            LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Out of memory while uploading", e);
                            break;
                        }
                        catch (Exception e)
                        {
                            LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error uploading item", e);
                            await ErrorHandlingService.SetFileErrorAsync(storageFile.Name,
                                                                         ErrorHandlingService.ImageErrorFileSetting, ErrorHandlingService.ImageErrorCountSetting);
                        }
                    }
                }
                else
                {
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Failed to fetch nodes");
                }
            }
            else
            {
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Failed to login");
            }

            _deferral.Complete();
        }
Пример #9
0
 private void OnNetworkStatusChanged(object sender)
 {
     NetworkService.CheckNetworkChange();
     UpdateConnectionInformation();
 }