示例#1
0
        /// <summary>
        /// Save the filename and error count of that specific file
        /// </summary>
        /// <param name="fileName">The file that failed</param>
        /// <returns></returns>
        private static int SetFileError(string fileName)
        {
            try
            {
                // Load filename last error
                var lastErrorFileName = SettingsService.LoadSettingFromFile <string>("ErrorFileName");

                // Check if it is the same file that has an error again
                if (!string.IsNullOrEmpty(lastErrorFileName))
                {
                    if (lastErrorFileName.Equals(fileName))
                    {
                        // If the same file, add to the error count
                        var count = SettingsService.LoadSettingFromFile <int>("FileErrorCount");
                        count++;
                        SettingsService.SaveSettingToFile("FileErrorCount", count);
                        return(count);
                    }
                }

                // New file error. Save the name and set the error count to one.
                SettingsService.SaveSettingToFile("ErrorFileName", fileName);
                SettingsService.SaveSettingToFile("FileErrorCount", 1);
                return(1);
            }
            catch (Exception)
            {
                // Do not let the error process cause the main service to generate a fault
                return(0);
            }
        }
示例#2
0
        /// <summary>
        /// Fast login to MEGA account with user session token
        /// </summary>
        private void FastLogin()
        {
            string sessionToken = null;

            try
            {
                // Try to load shared session token file
                sessionToken = SettingsService.LoadSettingFromFile <string>("{85DBF3E5-51E8-40BB-968C-8857B4FC6EF4}");
            }
            catch (Exception)
            {
                // Failed to load shared session token file
                // Notify complete and try next run to load the session string
                this.NotifyComplete();
                return;
            }


            if (String.IsNullOrEmpty(sessionToken) || String.IsNullOrWhiteSpace(sessionToken))
            {
                // No shred session token found
                // Notify complete and try next run to load the session string
                this.NotifyComplete();
                return;
            }

            // Do login
            var fastLoginListener = new MegaRequestListener();

            // After the request is finished. Check for success or failure
            fastLoginListener.RequestFinished += (sender, args) =>
            {
                if (!args.Succeeded)
                {
                    // Login failed
                    // Notify complete and try next run to load the session string
                    this.NotifyComplete();
                    return;
                }

                // Login succeeded
                // Fetch nodes. Needed to find the camera upload node later
                FetchNodes();
            };

            // Init fastlogin
            SdkService.MegaSdk.fastLogin(sessionToken, fastLoginListener);
        }
示例#3
0
        /// <summary>
        /// Upload files to MEGA Cloud Service
        /// </summary>
        public static async void Upload()
        {
            SdkService.MegaSdk.retryPendingConnections();

            // Get the date of the last uploaded file
            // Needed so that we do not upload the same file twice
            var lastUploadDate = SettingsService.LoadSettingFromFile <DateTime>("LastUploadDate");

            // Open the phone's Media Library
            MediaLibrary mediaLibrary;

            try { mediaLibrary = new MediaLibrary(); }
            catch (Exception e)
            {
                // Error opening the Media Library
                LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error opening the Media Library", e);
                scheduledAgent.NotifyComplete();
                return;
            }

            using (mediaLibrary)
            {
                List <Picture> pictures;

                var selectDate = lastUploadDate;
                // Find all pictures taken after the last upload date
                try { pictures = mediaLibrary.Pictures.Where(p => p.Date > selectDate).OrderBy(p => p.Date).ToList(); }
                catch (Exception e)
                {
                    // Error getting the pictures taken after the last upload date
                    LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error getting pictures from the media library", e);
                    scheduledAgent.NotifyComplete();
                    return;
                }

                if (!pictures.Any())
                {
                    // No pictures is not an error. Maybe all pictures have already been uploaded
                    // Just finish the task for this run
                    LogService.Log(MLogLevel.LOG_LEVEL_INFO, "No new items to upload");
                    scheduledAgent.NotifyComplete();
                    return;
                }

                var cameraUploadNode = await scheduledAgent.GetCameraUploadsNode();

                if (cameraUploadNode == 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");
                    scheduledAgent.NotifyComplete();
                    return;
                }

                // Loop all available pictures for upload action
                foreach (var picture in pictures)
                {
                    try
                    {
                        // Retreive the picture bytes as stream
                        using (var imageStream = picture.GetImage())
                        {
                            // Make sure the stream pointer is at the start of the stream
                            imageStream.Position = 0;

                            // Calculate time for fingerprint check
                            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                            TimeSpan diff   = picture.Date.ToUniversalTime() - origin;
                            ulong    mtime  = (ulong)Math.Floor(diff.TotalSeconds);

                            // Get the unique fingerprint of the file
                            string fingerprint = SdkService.MegaSdk.getFileFingerprint(new MegaInputStream(imageStream), mtime);

                            // Check if the fingerprint is already in the subfolders of the Camera Uploads
                            var mNode = SdkService.MegaSdk.getNodeByFingerprint(fingerprint, cameraUploadNode);

                            // If node already exists then save the node date and proceed with the next node
                            if (mNode != null)
                            {
                                SettingsService.SaveSettingToFile <DateTime>("LastUploadDate", picture.Date);
                                continue; // skip to next picture
                            }

                            // Create a temporary local path to save the picture for upload
                            string newFilePath = Path.Combine(scheduledAgent.GetTemporaryUploadFolder(), picture.Name);

                            // Reset back to start
                            // Because fingerprint action has moved the position
                            imageStream.Position = 0;

                            // Copy file to local storage to be able to upload
                            using (var fs = new FileStream(newFilePath, FileMode.Create))
                            {
                                await imageStream.CopyToAsync(fs);

                                await fs.FlushAsync();

                                fs.Close();
                            }

                            // Init the upload
                            SdkService.MegaSdk.startUploadWithMtimeTempSource(newFilePath, cameraUploadNode, mtime, true);
                            break;
                        }
                    }
                    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, "Error during the item upload", e);
                        scheduledAgent.NotifyComplete();
                    }
                    catch (Exception e)
                    {
                        // Send log, process the error and try again
                        LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error during the item upload", e);
                        ErrorProcessingService.ProcessFileError(picture.Name, picture.Date);
                        Upload();
                        return;
                    }
                }
            }
        }