Example #1
0
        private string ZipperExtractFileToPath(string destRootPath, System.IO.Compression.ZipArchiveEntry item)
        {
            var destFilename = CleanFilenameString(System.IO.Path.Combine(destRootPath, item.Name));

            FileStorageHelper.DeleteFile(destFilename);
            FileStorageHelper.CreateDirectory(System.IO.Path.GetDirectoryName(destFilename));
            //
            var count = 5;

            do
            {
                try
                {
                    item.ExtractToFile(destFilename, true);
                    if (System.IO.File.Exists(destFilename))
                    {
                        var fileInfo = new System.IO.FileInfo(destFilename);
                        fileInfo.LastWriteTime = DateTime.Now;
                    }
                    break;
                }
                catch
                {
                    if (--count <= 0)
                    {
                        throw;
                    }
                    Threading.ThreadingHelper.Sleep(200);
                }
            } while (true);
            //
            return(destFilename);
        }
Example #2
0
        /// <summary>
        /// Load state
        /// </summary>
        public async Task LoadState()
        {
            try
            {
                if (!FileStorageHelper.IsFileExists("currentPlaylist.js"))
                {
                    return;
                }

                var json = await FileStorageHelper.ReadText("currentPlaylist.js");

                if (!string.IsNullOrEmpty(json))
                {
                    _currentPlaylist.Deserialize(json);

                    if (_currentPlaylist.CurrentItem != null)
                    {
                        UpdateTransportControl();
                        CurrentAudioChanged?.Invoke(this, EventArgs.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load AudioService state");
            }
        }
Example #3
0
        public void TestBackgroundEventFromString()
        {
            string s = "{\"1\":{\"time\":1429192800000,\"event\":1},\"2\":{\"time\":1429192800000,\"event\":1}}";
            Dictionary <string, Dictionary <string, long> > dict = new Dictionary <string, Dictionary <string, long> >
            {
                {
                    "1", new Dictionary <string, long> {
                        { "time", 1429192800000 }, { "event", (long)BeaconEventType.Enter }
                    }
                },
                {
                    "2", new Dictionary <string, long> {
                        { "time", 1429192800000 }, { "event", (long)BeaconEventType.Enter }
                    }
                }
            };
            Dictionary <string, Dictionary <string, long> > readDict = FileStorageHelper.BackoundEventsFromString(s);

            Assert.AreEqual(dict.Count, readDict.Count, "Not same element count");
            CollectionAssert.AreEqual(dict["1"], readDict["1"]);
            CollectionAssert.AreEqual(dict["2"], readDict["2"]);


            Assert.IsNull(FileStorageHelper.BackoundEventsFromString(null));
        }
Example #4
0
        public void TestActionToString()
        {
            string s = FileStorageHelper.ActionToString("1", "1", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1");

            Assert.AreEqual("1,1,1429192800000,1,False,False,1\n", s);
            s = FileStorageHelper.ActionToString("1", "1", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1234235235");
            Assert.AreEqual("1,1,1429192800000,1,False,False,1234235235\n", s);
            s = FileStorageHelper.ActionToString("1", "1", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "");
            Assert.AreEqual("1,1,1429192800000,1,False,False,\n", s);
            s = FileStorageHelper.ActionToString("1", "1", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.Enter, null);
            Assert.AreEqual("1,1,1429192800000,1,False,False,\n", s);


            s = FileStorageHelper.ActionToString(new HistoryAction()
            {
                EventId = "1", BeaconId = "1", ActionTime = DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000").ToString(History.Timeformat), Trigger = (int)BeaconEventType.Enter, Delivered = false
            });
            Assert.AreEqual("1,1,1429192800000,1,False,False,\n", s);
            s = FileStorageHelper.ActionToString(new HistoryAction()
            {
                EventId = "1", BeaconId = "1", ActionTime = DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000").ToString(History.Timeformat), Trigger = (int)BeaconEventType.Enter, Delivered = false, Location = ""
            });
            Assert.AreEqual("1,1,1429192800000,1,False,False,\n", s);
            s = FileStorageHelper.ActionToString(new HistoryAction()
            {
                EventId = "1", BeaconId = "1", ActionTime = DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000").ToString(History.Timeformat), Trigger = (int)BeaconEventType.Enter, Delivered = false, Location = "1234567"
            });
            Assert.AreEqual("1,1,1429192800000,1,False,False,1234567\n", s);
        }
Example #5
0
        public async Task <HttpResponseMessage> SendVideoMessage(VideoMessage videoMessage)
        {
            ResponseBase <IList <MMPro.MM.UploadVideoResponse> > response = new ResponseBase <IList <MMPro.MM.UploadVideoResponse> >();

            try
            {
                IList <MMPro.MM.UploadVideoResponse> list = new List <MMPro.MM.UploadVideoResponse>();
                byte[] buffer = await FileStorageHelper.DownloadToBufferAsync(videoMessage.ObjectName);

                byte[] imageBuffer = await FileStorageHelper.DownloadToBufferAsync(videoMessage.ImageObjectName);

                foreach (var item in videoMessage.ToWxIds)
                {
                    var result = wechat.SendVideoMessage(videoMessage.WxId, item, videoMessage.PlayLength, buffer, imageBuffer);
                    list.Add(result);
                }
                response.Data = list;
            }
            catch (ExpiredException ex)
            {
                response.Success = false;
                response.Code    = "401";
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Code    = "500";
                response.Message = ex.Message;
            }
            return(await response.ToHttpResponseAsync());
        }
Example #6
0
        public bool IsFileCached(string key, string path = null)
        {
            string fileName = GetFileNameForKey(key);
            string filePath = Path.Combine(path ?? string.Empty, fileName);

            return(FileStorageHelper.IsFileExists(filePath));
        }
        public ResponseModel <Product> Update([FromForm] InputProductModel product)
        {
            ResponseModel <Product> productResult = new ResponseModel <Product>();

            try
            {
                productResult = _productManager.Update(new Product {
                    CategoryID = product.CategoryID, ProductName = product.ProductName, UnitStock = product.UnitStock, Price = product.Price, ProductDescription = product.ProductDescription
                });
                var photo         = photoManager.GetByProductId(productResult.result.ProductID);
                var photoResult   = FileStorageHelper.UpdateFile(product.Photo, Path.Combine(Environment.CurrentDirectory, "wwwroot", photo.result.PhotoUrl));
                var photoDBResult = photoManager.Update(new Photo
                {
                    PhotoID   = photo.result.PhotoID,
                    PhotoUrl  = photoResult.result,
                    ProductID = photo.result.ProductID,
                    isMain    = photo.result.isMain
                });
                return(productResult);
            }
            catch (Exception ex)
            {
                productResult.Success = false;
                productResult.Message = ex.Message;
            }


            return(productResult);
        }
Example #8
0
        public async Task <HttpResponseMessage> SendFriendCircleImage(SendFriendCircleImage sendFriendCircleImage)
        {
            ResponseBase <IList <micromsg.SnsUploadResponse> > response = new ResponseBase <IList <micromsg.SnsUploadResponse> >();

            try
            {
                IList <micromsg.SnsUploadResponse> list = new List <micromsg.SnsUploadResponse>();
                foreach (var item in sendFriendCircleImage.ObjectNames)
                {
                    var buffer = await FileStorageHelper.DownloadToBufferAsync(item);

                    var result = wechat.SnsUpload(sendFriendCircleImage.WxId, new MemoryStream(buffer));
                    if (result == null)
                    {
                        throw new Exception("上传失败");
                    }
                    list.Add(result);
                }
                response.Data    = list;
                response.Message = "上传成功";
            }
            catch (ExpiredException ex)
            {
                response.Success = false;
                response.Code    = "401";
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Code    = "500";
                response.Message = ex.Message;
            }
            return(await response.ToHttpResponseAsync());
        }
        public ResponseModel <Product> Add([FromForm] InputProductModel inputProductModel)
        {
            //  var photoListFromForm = HttpContext.Request.Form.Files["photoList"];


            ResponseModel <Product> productResult = new ResponseModel <Product>();

            try
            {
                var photoResult = FileStorageHelper.UploadFile(inputProductModel.Photo);
                productResult = _productManager.Add(new Product {
                    ProductName = inputProductModel.ProductName, ProductDescription = inputProductModel.ProductDescription, Price = inputProductModel.Price, UnitStock = inputProductModel.UnitStock, CategoryID = inputProductModel.CategoryID
                });
                var photoDBResult = photoManager.Add(new Photo {
                    ProductID = productResult.result.ProductID, PhotoUrl = photoResult.result
                });
            }
            catch (Exception ex)
            {
                productResult.Success = false;
                productResult.Message = ex.Message;
            }


            return(productResult);
        }
        public ResponseModel <Product> Delete([FromForm] Product product)
        {
            ResponseModel <Product> productResult = new ResponseModel <Product>();

            try
            {
                productResult = _productManager.Delete(product);
                var photo         = photoManager.GetByProductId(productResult.result.ProductID);
                var photoResult   = FileStorageHelper.DeleteFile(Path.Combine(Environment.CurrentDirectory, "wwwroot", photo.result.PhotoUrl));
                var photoDBResult = photoManager.Delete(new Photo
                {
                    PhotoID   = photo.result.PhotoID,
                    PhotoUrl  = photo.result.PhotoUrl,
                    ProductID = photo.result.ProductID,
                    isMain    = photo.result.isMain
                });
                return(productResult);
            }
            catch (Exception ex)
            {
                productResult.Success = false;
                productResult.Message = ex.Message;
            }
            return(productResult);
        }
        public async Task CleanupActionDatabaseTest()
        {
            await storage.InitStorage();

            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)));

            var historyActions = await storage.GetUndeliveredActions();

            await storage.SetActionsAsDelivered(historyActions);

            await storage.CleanupDatabase();

//            Assert.AreEqual(0, (await storage.GetActions("1")).Count, "Action found, not all actions where removed");


            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "3",
                                                                                            DateTimeOffset.Parse(string.Format("{0}-{1}-{2}T14:00:00.000+0000", DateTime.Now.AddDays(-2).Year, DateTime.Now.AddDays(-2).Month, DateTime.Now.AddDays(-2).Day)),
                                                                                            BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "2",
                                                                                            DateTimeOffset.Parse(string.Format("{0}-{1}-{2}T14:00:00.000+0000", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)), BeaconEventType.EnterExit, null)));

            historyActions = await storage.GetUndeliveredActions();

            await storage.SetActionsAsDelivered(historyActions);

            await storage.CleanupDatabase();

//            Assert.AreEqual(1, (await storage.GetActions("1")).Count, "Not 1 action found");
        }
Example #12
0
        public async Task <HttpResponseMessage> SendVoiceMessage(VoiceMessage voiceMessage)
        {
            ResponseBase <IList <MMPro.MM.UploadVoiceResponse> > response = new ResponseBase <IList <MMPro.MM.UploadVoiceResponse> >();

            try
            {
                IList <MMPro.MM.UploadVoiceResponse> list = new List <MMPro.MM.UploadVoiceResponse>();
                byte[] buffer = await FileStorageHelper.DownloadToBufferAsync(voiceMessage.ObjectName);

                foreach (var item in voiceMessage.ToWxIds)
                {
                    var result = wechat.SendVoiceMessage(voiceMessage.WxId, item, buffer, voiceMessage.FileName.GetVoiceType(), voiceMessage.VoiceSecond * 100);
                    list.Add(result);
                }
                response.Data = list;
            }
            catch (ExpiredException ex)
            {
                response.Success = false;
                response.Code    = "401";
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Code    = "500";
                response.Message = ex.Message;
            }
            return(await response.ToHttpResponseAsync());
        }
        public async Task HistoryEventTest()
        {
            await storage.InitStorage();

            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T15:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T16:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("2", DateTimeOffset.Parse("2016-04-16T17:00:00.000+0000"), BeaconEventType.Enter, null)));

            IList <HistoryEvent> historyEvents = await storage.GetUndeliveredEvents();

            HistoryEvent historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-16T15:00:00.000+00:00");

            Assert.AreEqual("1", historyEvent.BeaconId, "Wrong pid");
            Assert.AreEqual("2016-04-16T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date");
            Assert.AreEqual((int)BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger");



            await storage.SetEventsAsDelivered(historyEvents);

            historyEvents = await storage.GetUndeliveredEvents();

            Assert.AreEqual(0, historyEvents.Count, "not all events as delivered marked");
        }
Example #14
0
        public void TestDelayedActionToString()
        {
            ResolvedAction action = new ResolvedAction();

            action.BeaconAction         = new BeaconAction();
            action.BeaconAction.Body    = "body";
            action.BeaconAction.Id      = 1;
            action.BeaconAction.Payload = JsonObject.Parse("{\"pay\":\"load\"}");
            action.BeaconAction.Subject = "Subject";
            action.BeaconAction.Type    = BeaconActionType.InApp;
            action.BeaconAction.Url     = "http://sensorberg.com";
            action.BeaconAction.Uuid    = "uuid";
            action.Delay      = 123;
            action.BeaconPids = new List <string>()
            {
                "1", "2", "3", "4"
            };
            action.EventTypeDetectedByDevice = BeaconEventType.EnterExit;
            action.ReportImmediately         = true;
            action.SendOnlyOnce    = true;
            action.SuppressionTime = 321;
            action.Timeframes      = new List <Timeframe>()
            {
                new Timeframe()
                {
                    End = DateTimeOffset.Parse("2015-04-16T12:00:00.000+0000"), Start = DateTimeOffset.Parse("2015-04-15T12:00:00.000+0000")
                }
            };

            Guid   guid = Guid.NewGuid();
            string s    = FileStorageHelper.DelayedActionToString(action, DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), "123", BeaconEventType.Enter, guid, "123");

            Assert.AreEqual(guid + ",1429192800000,False,eyJBY3Rpb24iOnsiQmVhY29uQWN0aW9uIjp7IklkIjoxLCJUeXBlIjozLCJlaWQiOiJ1dWlkIiwiU3ViamVjdCI6IlN1YmplY3QiLCJCb2R5IjoiYm9keSIsIlVybCI6Imh0dHA6Ly9zZW5zb3JiZXJnLmNvbSIsIlBheWxvYWRTdHJpbmciOiJ7XCJwYXlcIjpcImxvYWRcIn0ifSwiYmVhY29ucyI6WyIxIiwiMiIsIjMiLCI0Il0sInRyaWdnZXIiOjMsIkRlbGF5IjoxMjMsIlNlbmRPbmx5T25jZSI6dHJ1ZSwic3VwcHJlc3Npb25UaW1lIjozMjEsIlJlcG9ydEltbWVkaWF0ZWx5Ijp0cnVlLCJUaW1lZnJhbWVzIjpbeyJTdGFydCI6IjIwMTUtMDQtMTVUMTI6MDA6MDArMDA6MDAiLCJFbmQiOiIyMDE1LTA0LTE2VDEyOjAwOjAwKzAwOjAwIn1dfSwiVGltZSI6IjIwMTUtMDQtMTZUMTQ6MDA6MDArMDA6MDAiLCJCZWFjb24iOiIxMjMiLCJFdmVudCI6MX0=,123\n", s);
        }
        public async Task GetEventInForegroundFromBackgroundStorageTest()
        {
            IStorage foregroundStorage = storage;
            await foregroundStorage.InitStorage();

            IStorage backgroundStorage = new FileStorage()
            {
                Background = true
            };
            await backgroundStorage.InitStorage();

            Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T15:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T16:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("2", DateTimeOffset.Parse("2016-04-16T17:00:00.000+0000"), BeaconEventType.Enter, null)));

            Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("3", DateTimeOffset.Parse("2016-04-15T14:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("3", DateTimeOffset.Parse("2016-04-15T15:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("3", DateTimeOffset.Parse("2016-04-15T16:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("4", DateTimeOffset.Parse("2016-04-15T17:00:00.000+0000"), BeaconEventType.Enter, null)));

            //verify every storage api accesses every data
            IList <HistoryEvent> historyEvents = await backgroundStorage.GetUndeliveredEvents();

            HistoryEvent historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-15T15:00:00.000+00:00");

            Assert.AreEqual("3", historyEvent.BeaconId, "Wrong pid");
            Assert.AreEqual("2016-04-15T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date");
            Assert.AreEqual((int)BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger");

            historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-16T15:00:00.000+00:00");
            Assert.AreEqual("1", historyEvent.BeaconId, "Wrong pid");
            Assert.AreEqual("2016-04-16T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date");
            Assert.AreEqual((int)BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger");


            historyEvents = await foregroundStorage.GetUndeliveredEvents();

            historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-15T15:00:00.000+00:00");
            Assert.AreEqual("3", historyEvent.BeaconId, "Wrong pid");
            Assert.AreEqual("2016-04-15T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date");
            Assert.AreEqual((int)BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger");

            historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-16T15:00:00.000+00:00");
            Assert.AreEqual("1", historyEvent.BeaconId, "Wrong pid");
            Assert.AreEqual("2016-04-16T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date");
            Assert.AreEqual((int)BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger");


            await backgroundStorage.SetEventsAsDelivered(historyEvents);

            historyEvents = await backgroundStorage.GetUndeliveredEvents();

            Assert.AreEqual(0, historyEvents.Count, "not all events as delivered marked - background");

            historyEvents = await foregroundStorage.GetUndeliveredEvents();

            Assert.AreEqual(0, historyEvents.Count, "not all events as delivered marked - foreground");
        }
Example #16
0
        public void GenerateAudioFileNameInvalidAudioFileIdThrows()
        {
            // Arrange
            var audioFileId = Guid.Empty;

            // Assert
            Assert.Throws <ArgumentNullException>(() => FileStorageHelper.AudioFileName(audioFileId));
        }
Example #17
0
        public void GenerateAudioFileFolderInvalidProjectIdThrows()
        {
            // Arrange
            var projectId = Guid.Empty;

            // Assert
            Assert.Throws <ArgumentNullException>(() => FileStorageHelper.AudioFileFolder(projectId));
        }
Example #18
0
 private void InitializeStore()
 {
     // clean self
     ((dodSON.Core.FileStorage.IFileStoreAdvanced) this).ResetLists();
     // only initialize if the back end store exists.
     if (System.IO.File.Exists(BackendStorageZipFilename))
     {
         // iterate all files, in all subdirectories, in the zip file
         using (var zipper = CreateZipper(System.IO.Compression.ZipArchiveMode.Read))
         {
             // process all files
             foreach (var zipItem in zipper.Entries)
             {
                 var filename = CleanFilenameString(zipItem.FullName);
                 // do not process non-files
                 if (!filename.EndsWith(@"\"))
                 {
                     // do not process the (ORIGINAL FILENAMES) file
                     if (!filename.Equals(_OriginalFilenames_Filename, StringComparison.InvariantCultureIgnoreCase))
                     {
                         // create new store item/add to self
                         var newItem = this.Add(filename, "", zipItem.LastWriteTime.UtcDateTime, zipItem.Length);
                         // clear all state flags
                         ((dodSON.Core.FileStorage.IFileStoreItemAdvanced)newItem).StateChangeTracker.ClearAll();
                         // set compressed size and uncompressed size
                         ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)newItem).SetCompressionValues(zipItem.CompressedLength);
                     }
                     else
                     {
                         // load original filenames file.
                         // extract to temp file
                         var tempFilename = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
                         try
                         {
                             zipItem.ExtractToFile(tempFilename, true);
                             // read temp file
                             using (var sr = new System.IO.StreamReader(tempFilename))
                             {
                                 // read file and convert
                                 var originalFilenames = StringToOriginalFilenames(sr.ReadToEnd());
                                 // set all original filenames
                                 ((dodSON.Core.FileStorage.IFileStoreAdvanced) this).SetOriginalFilenames(originalFilenames);
                             }
                         }
                         catch { }
                         finally
                         {
                             // delete temp file
                             FileStorageHelper.DeleteFile(tempFilename);
                         }
                     }
                 }
             }
         }
     }
 }
Example #19
0
        // FUTURE Also support other audio formats.
        // TODO This is windows coupled. See https://github.com/tabeckers/AbleSync/issues/19 and https://github.com/tabeckers/AbleSync/issues/28
        // TODO Pick correct audio file, there may be multiple mp3 files.
        /// <summary>
        ///     Execute the upload for an audio file.
        /// </summary>
        /// <remarks>
        ///     This only handles mp3.
        /// </remarks>
        /// <param name="task">The task.</param>
        /// <param name="token">The cancellation token.</param>
        public async Task ExecuteUploadAudioAsync(ProjectTask task, CancellationToken token)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }
            if (token == null)
            {
                throw new ArgumentNullException(nameof(token));
            }
            if (task.ProjectTaskType != ProjectTaskType.UploadAudio)
            {
                throw new InvalidOperationException(nameof(task.ProjectTaskType));
            }

            _logger.LogTrace($"Starting mp3 audio upload for project {task.ProjectId}");

            var project = await _projectRepository.GetAsync(task.ProjectId, token);

            var directoryInfo = DirectoryInfoHelper.GetFromProject(_options.RootDirectoryPath, project);
            var audioFiles    = directoryInfo.GetFiles().Where(x => Constants.ExportedAudioFileExtensions.Contains(x.Extension));

            // TODO Do elegantly.
            if (!audioFiles.Where(x => x.Extension == Constants.AudioMp3FileExtension).Any())
            {
                // TODO Custom exception.
                throw new InvalidOperationException("Could not get mp3 file in project folder");
            }

            // Get the actual physical file because we need its name.
            var audioFilePhysical = audioFiles.Where(x => x.Extension == Constants.AudioMp3FileExtension).First();

            // Get or create the audio file.
            var audioFileEntity = await _audioFileRepository.ExistsForProjectAsync(task.ProjectId, AudioFormat.Mp3, token)
                ? await _audioFileRepository.GetFromProjectAsync(task.ProjectId, AudioFormat.Mp3, token)
                : await _audioFileRepository.CreateGetAsync(new AudioFile
            {
                AudioFormat = AudioFormat.Mp3,
                Name        = audioFilePhysical.Name,
                ProjectId   = project.Id
            }, token);

            var fileNamePhysical   = audioFilePhysical.Name;
            var folderNamePhysical = $"{DirectoryInfoHelper.ParsePathFromProject(_options.RootDirectoryPath, project)}";

            using var fileStream = new FileStream($"{folderNamePhysical}/{fileNamePhysical}", FileMode.Open, FileAccess.Read);

            var fileNameStorage   = FileStorageHelper.AudioFileName(audioFileEntity.Id);
            var folderNameStorage = FileStorageHelper.AudioFileFolder(project.Id);
            await _blobStorageService.StoreFileAsync(folderNameStorage, fileNameStorage, Constants.ContentTypeMp3, fileStream, token);

            // Mark our synchronization
            await _audioFileRepository.MarkSyncedAsync(audioFileEntity.Id, token);

            _logger.LogTrace($"Finished mp3 audio upload for project {task.ProjectId} - uploaded {fileNamePhysical} as {fileNameStorage}");
        }
Example #20
0
 /// <summary>
 /// Will finalize the adding, updating and removing of files from the .zip file.
 /// </summary>
 /// <param name="state">A reference to an initialized System.IO.Compression.ZipArchive object. This reference, created in the <see cref="Save_Startup(out object)"/> will be destroyed and set to null in this method.</param>
 protected override void Save_Shutdown(ref object state)
 {
     try
     {
         // save state (zipper)
         if (state != null)
         {
             if (this.Count == 0)
             {
                 // #### no files left; delete back end storage
                 // dispose of zipper --> closes and commits the zip file
                 DisposeOfZipper(ref state);
                 FileStorageHelper.DeleteFile(BackendStorageZipFilename);
             }
             else
             {
                 if (_BackendChanged)
                 {
                     // #### back end has changed; save zip and update compression information
                     // dispose of zipper --> closes and commits the zip file
                     DisposeOfZipper(ref state);
                     // create a NEW zipper
                     // use a stand-in variable for the lambda expression
                     System.IO.Compression.ZipArchive zipState = CreateZipper(System.IO.Compression.ZipArchiveMode.Read);
                     // set the 'ref' object to the NEW zipper
                     state = zipState;
                     // **** update all compression information
                     ForEach(item =>
                     {
                         // reinitialize all compressed/uncompressed values
                         var found = zipState.Entries.FirstOrDefault((zf) => { return(CleanFilenameString(zf.FullName).Equals(item.RootFilename, StringComparison.InvariantCultureIgnoreCase)); });
                         if (found != null)
                         {
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionValues(found.CompressedLength);
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionStrategy(NormalizeCompressionStrategy(found));
                         }
                         else
                         {
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionValues(0);
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionStrategy(CompressionStorageStrategy.Store);
                         }
                     });
                     // **** clear the lambda stand-in variable
                     zipState        = null;
                     _BackendChanged = false;
                 }
             }
         }
     }
     finally
     {
         // #### fail-safe
         DisposeOfZipper(ref state);
     }
 }
Example #21
0
        public void GenerateAudioFileName()
        {
            // Arrange.
            var audioFileId = Guid.NewGuid();

            // Act.
            var result = FileStorageHelper.AudioFileName(audioFileId);

            // Assert.
            Assert.Equal($"{audioFileId}", result);
        }
Example #22
0
        public void GenerateAudioFileFolder()
        {
            // Arrange.
            var projectId = Guid.NewGuid();

            // Act.
            var result = FileStorageHelper.AudioFileFolder(projectId);

            // Assert.
            Assert.Equal($"{Constants.StorageProjectFolderBase}/{projectId}/{Constants.StorageAudioFilesFolder}", result);
        }
Example #23
0
        public void TestHistoryEventToString()
        {
            string s = FileStorageHelper.EventToString(new HistoryEvent()
            {
                BeaconId  = "1",
                EventTime = DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000").ToString(History.Timeformat),
                Trigger   = (int)BeaconEventType.Enter
            });

            Assert.AreEqual("1,1429192800000,1,False,\n", s);
        }
 public IHttpActionResult DownloadFile(Guid fileId)
 {
     try
     {
         var filePath = FileStorageHelper.FindFile(fileId);
         return(GetOutputFileAsResponse(filePath, FileStorageHelper.GetClearFileName(Path.GetFileName(filePath), fileId)));
     }
     catch (Exception ex)
     {
         return(HandleExceptionResult(HttpStatusCode.InternalServerError, "Failed to download file", ex));
     }
 }
Example #25
0
        public IResult Delete(CarImage carImage)
        {
            var result = FileStorageHelper.DeleteFile(_carImageDal.Get(i => i.CarImageId == carImage.CarImageId).ImagePath);

            if (!result.Success)
            {
                return(new ErrorResult("Image file remove failed!"));
            }

            _carImageDal.Delete(carImage);
            return(new SuccessResult(Messages.EntityDeleted));
        }
Example #26
0
        public async Task SaveStream(string key, Stream stream, string path = null)
        {
            string fileName = GetFileNameForKey(key);
            string filePath = Path.Combine(path ?? string.Empty, fileName);

            using (var fileStream = await FileStorageHelper.OpenFileWrite(filePath))
            {
                await stream.CopyToAsync(fileStream);

                await fileStream.FlushAsync();
            }
        }
Example #27
0
 /// <summary>
 /// Save state
 /// </summary>
 public async Task SaveState()
 {
     try
     {
         var json = _currentPlaylist.Serialize();
         await FileStorageHelper.WriteText("currentPlaylist.js", json);
     }
     catch (Exception ex)
     {
         Logger.Error(ex, "Unable to save AudioService state");
     }
 }
        public async Task StorageClearTest()
        {
            await storage.InitStorage();

            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2015-04-16T15:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2015-04-16T16:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("2", DateTimeOffset.Parse("2015-04-16T17:00:00.000+0000"), BeaconEventType.Enter, null)));

            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2015-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2015-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)));

            var historyEvents = await storage.GetUndeliveredEvents();

            Assert.AreEqual(4, historyEvents.Count, "not enough Undelivered Events found");
            IList <HistoryAction> historyActions = await storage.GetUndeliveredActions();

            Assert.AreEqual(4, historyActions.Count, "not enough Undelivered Actions found");

            await storage.SetEventsAsDelivered(historyEvents);

            await storage.SetActionsAsDelivered(historyActions);

            historyEvents = await storage.GetUndeliveredEvents();

            Assert.AreEqual(0, historyEvents.Count, "Undelivered Events found");
            Assert.AreEqual(0, (await storage.GetUndeliveredActions()).Count, "Undelivered Actions found");

            await storage.CleanDatabase();

//            Assert.AreEqual(0, (await storage.GetActions("1")).Count, "remaining Actions found");


            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2015-04-16T15:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2015-04-16T16:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("2", DateTimeOffset.Parse("2015-04-16T17:00:00.000+0000"), BeaconEventType.Enter, null)));

            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2015-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2015-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")));
            Assert.IsTrue(await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)));

            await storage.CleanDatabase();

            historyEvents = await storage.GetUndeliveredEvents();

            Assert.AreEqual(0, historyEvents.Count, "Undelivered Events found");
            Assert.AreEqual(0, (await storage.GetUndeliveredActions()).Count, "Undelivered Actions found");
        }
Example #29
0
        public void TestEventStateStorage()
        {
            string s = FileStorageHelper.BeaconEventStateToString("1", BeaconEventType.Enter, DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"));

            Assert.AreEqual("1,1,1429192800000", s);

            BackgroundEvent be = FileStorageHelper.BeaconEventStateFromString(s);

            Assert.AreEqual("1", be.BeaconId);
            Assert.AreEqual(DateTimeOffset.Parse("2015-04-16T14:00:00.000+0000"), be.EventTime);
            Assert.AreEqual(BeaconEventType.Enter, be.LastEvent);
            Assert.IsNull(FileStorageHelper.BeaconEventStateFromString(""));
            Assert.IsNull(FileStorageHelper.BeaconEventStateFromString(null));
        }
Example #30
0
        public void TestHistoryEventParsing(string query, string beaconId, string eventTime, BeaconEventType beaconEventType, bool send)
        {
            HistoryEvent e = FileStorageHelper.EventFromString(query);

            //fallback for unparsable data
            if (beaconId == null && eventTime == null)
            {
                Assert.IsNull(e);
                return;
            }

            Assert.AreEqual(beaconId, e.BeaconId);
            Assert.AreEqual(eventTime, e.EventTime);
            Assert.AreEqual((int)beaconEventType, e.Trigger);
        }