예제 #1
0
        public async Task <JsonResult> UpdateTask(int id, TaskIn model)
        {
            var notify = false;
            var task   = ContentService.Get <TaskItem>(model.Id);

            if (model.AssignedTo.HasValue && model.AssignedTo != task.AssignedTo && model.AssignedTo != User.Id)
            {
                notify = true;
            }

            task.Name        = model.Name;
            task.Description = model.Description;
            task.Completed   = model.Completed;
            task.DueDate     = model.DueDate;
            task.AssignedTo  = model.AssignedTo;
            task.Priority    = model.Priority;

            var updated = ContentService.Update <TaskItem>(task);

            // notify
            if (notify)
            {
                NotificationService.Insert(
                    new Notification(model.AssignedTo.Value, $@"{User.GetTitle()} assigned you to the task <strong>{task.Name}</strong>")
                {
                    Link = task
                }
                    );
            }

            // push realtime event
            await PushService.Push("task_updated", task);

            return(Json(updated));
        }
예제 #2
0
            public async void SingleConfiguration_Options_PushFailed()
            {
                var config = new PushChannelConfiguration()
                {
                    ChannelType = TestChannelType, Id = "TestId"
                };
                var ex = new PushException("test");

                var providerMock = new Mock <IPushProvider>(MockBehavior.Strict);

                providerMock.Setup(v => v.PushAsync(It.IsAny <string>(), It.IsAny <PushOptions>()))
                .Throws(ex);

                var pushService = new PushService(MockByConfigs(new[] { config }),
                                                  new[] { MockByProvider(new Dictionary <string, IPushProvider> {
                        { config.Id, providerMock.Object }
                    }) });

                var res = await Assert.ThrowsAsync <PushFailedException>(async() =>
                                                                         await pushService.Push("userid", new Dictionary <string, string>(), "payload", null));

                Assert.Single(res.Failures);
                Assert.Same(config, res.Failures[0].Configuration);
                Assert.Same(ex, res.Failures[0].Exception);
                Assert.Same(ex, res.InnerException);
            }
예제 #3
0
        static void Main(string[] args)
        {
            string certificatesFolder   = System.Configuration.ConfigurationManager.AppSettings["certificate_path"];
            string certificatesPassword = System.Configuration.ConfigurationManager.AppSettings["certificate_password"];

            InitFactories();

            using (var db = new NotificationsModel())
            {
                char input;
                do
                {
                    Product p0 = db.Products.Find(1);
                    p0.Price = 0.49;
                    db.SaveChanges();
                    PushService service = PushService.Instance;
                    service.Init(certificatesFolder, certificatesPassword, "", "", db.Notifications);
                    service.Push();

                    // Restore the normal state
                    p0.Price = 0.99;
                    db.SaveChanges();
                    input = Console.ReadKey().KeyChar;
                } while (input == 'c');
            }
        }
예제 #4
0
 public ActionResult Save(Push model, List <int> type)
 {
     if (model.State == 1)
     {
         return(Content(PushService.Push(model, type).ToJson()));
     }
     return(Content(PushService.Save(model, type).ToJson()));
 }
예제 #5
0
        public async Task <JsonResult> ToggleCompleted(int id)
        {
            var task = ContentService.Get <TaskItem>(id);

            task.Completed = !task.Completed;
            var updated = ContentService.Update <TaskItem>(task);

            // push realtime event
            await PushService.Push("task_toggle_completed", task);

            return(Json(updated));
        }
        public async Task <JsonResult> InsertTask(int id, TaskIn model)
        {
            var app  = GetApp(id);
            var task = ContentService.Insert <TaskItem>(new TaskItem {
                Name = model.Name
            }, app);

            // push realtime event
            await PushService.Push("task_inserted", task);

            // return json
            return(Json(task));
        }
예제 #7
0
        public async Task <JsonResult> DeleteTask(int id)
        {
            var task = ContentService.Get <TaskItem>(id);

            if (task != null)
            {
                ContentService.Delete(task.Id);
            }

            // push realtime event
            await PushService.Push("task_deleted", task);

            return(Json("Deleted"));
        }
예제 #8
0
            public async void MultiConfiguration_All_PushFailed()
            {
                var config1 = new PushChannelConfiguration()
                {
                    ChannelType = TestChannelType, Id = "1"
                };
                var config2 = new PushChannelConfiguration()
                {
                    ChannelType = TestChannelType, Id = "2"
                };
                var ex1 = new PushException("test");
                var ex2 = new PushException("test");

                var providerMock1 = new Mock <IPushProvider>(MockBehavior.Strict);

                providerMock1.Setup(v => v.PushAsync(It.IsAny <string>(), It.IsAny <PushOptions>()))
                .Throws(ex1);
                var providerMock2 = new Mock <IPushProvider>(MockBehavior.Strict);

                providerMock2.Setup(v => v.PushAsync(It.IsAny <string>(), It.IsAny <PushOptions>()))
                .Throws(ex2);

                var pushService = new PushService(MockByConfigs(new[] { config1, config2 }),
                                                  new[] { MockByProvider(new Dictionary <string, IPushProvider> {
                        { config1.Id, providerMock1.Object },
                        { config2.Id, providerMock2.Object }
                    }) });

                var res = await Assert.ThrowsAsync <PushFailedException>(async() =>
                                                                         await pushService.Push("userid", new Dictionary <string, string>(), "payload", null));

                Assert.Equal(2, res.Failures.Length);
                Assert.Collection(res.Failures,
                                  v =>
                {
                    Assert.Same(config1, v.Configuration);
                    Assert.Same(ex1, v.Exception);
                },
                                  v =>
                {
                    Assert.Same(config2, v.Configuration);
                    Assert.Same(ex2, v.Exception);
                });
                Assert.Collection(res.InnerExceptions, v => Assert.Same(ex1, v), v => Assert.Same(ex2, v));
            }
예제 #9
0
        public bool SendMessage(string sessionKey, Shared.Dto.Message msg)
        {
            var dbContext = DbContextFactory.GetContext();

            var sessionService = new SessionService();
            var user           = sessionService.GetUser(sessionKey);

            if (user == null)
            {
                return(false);
            }

            User recipient;

            try
            {
                recipient =
                    dbContext.Users.Single(u => u.Id == msg.ReceiverId);
            }
            catch (Exception)
            {
                return(false);
            }

            var newMsg = new Message
            {
                Content    = msg.Body,
                Sender     = user,
                Recipient  = recipient,
                SentTime   = msg.DateSent,
                Signature  = msg.DigitalSignature,
                SessionKey = msg.SymmetricKey,
                InitVector = msg.Iv
            };

            var userService = new PushService();

            userService.Push(recipient, "You have new message");

            dbContext.Add(newMsg);
            dbContext.SaveChanges();

            return(true);
        }
예제 #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("My horse is amazing!");

            // ToDo: Dependency injection
            // ToDo: Hide this information
            var endpointSettings = new ApiSettings
            {
                BaseUrl = "",
                MaximumRetryNumberLimit = 5,
                User           = "",
                Password       = "",
                CanAppEndpoint = "",
                RecEndpoint    = "",
                RequEndpoint   = ""
            };

            var pushService = new PushService();

            try
            {
                var token = pushService.GetAuthenticationToken(endpointSettings).WaitAndUnwrapException();

                if (token != null && !string.IsNullOrEmpty(token.AccessToken))
                {
                    pushService.Push(endpointSettings, token).WaitAndUnwrapException();
                }
                else
                {
                    Console.WriteLine(PushConstants.MissingTokenMessage);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            //var _response = new APIGatewayProxyResponse
            //{
            //    StatusCode = (int) HttpStatusCode.OK,
            //    Headers = new Dictionary<string, string> {{"Content-Type", "text/plain"}}
            //};
        }
예제 #11
0
        public async Task Should_Merge_Result_From_Both_Services()
        {
            var token = "abc";
            Predicate <Assessment> predicate = a => true;
            Assessment             savedAssessment;
            var saveOrUpdate = SetupSaveOrUpdate(token, predicate, out savedAssessment);

            Assessment removedAssessment;
            var        removal = SetupRemoval(token, predicate, out removedAssessment);

            var pushService = new PushService(saveOrUpdate, removal);

            var result = await pushService.Push(token, predicate);

            var success = result.SuccessfulItems.ToList();

            Assert.That(success.Contains(savedAssessment));
            Assert.That(success.Contains(removedAssessment));
        }
예제 #12
0
        public bool SendContact(string sessionKey, Shared.Dto.Contact contact)
        {
            var dbContext = DbContextFactory.GetContext();

            var sessionService = new SessionService();
            var user           = sessionService.GetUser(sessionKey);

            if (user == null)
            {
                return(false);
            }


            User recipient;

            try
            {
                recipient =
                    dbContext.Users.Single(u => u.Id == contact.ReceiverId);
            }
            catch (Exception)
            {
                return(false);
            }

            var newContact = new Contact
            {
                PublicKey = contact.PublicKey,
                Name      = contact.Name,
                Sender    = user,
                Recipient = recipient
            };

            dbContext.Add(newContact);
            dbContext.SaveChanges();

            var userService = new PushService();

            userService.Push(recipient, "Recieved new contact!");

            return(true);
        }
예제 #13
0
        public async Task SendMessageToRoomAsyc(string body, string roomId)
        {
            User user = await _dbContext.Users.FindAsync(UserId);

            Message message = new Message
            {
                Body      = body,
                CreatedAt = DateTime.UtcNow,
                RoomId    = roomId,
                SenderId  = UserId
            };

            var sw = new Stopwatch();

            sw.Start();

            // 디비에 메시지 저장
            _dbContext.Messages.Add(message);
            await _dbContext.SaveChangesAsync();

            _logger.LogWarning($"Save To DB: {sw.ElapsedMilliseconds}");

            sw.Restart();

            // 접속중인 디바이스는 일단 다 보낸다.
            await Clients.Group(roomId).SendAsync("ReceiveMessage", user.Name, body, message.Id, UserId, message.CreatedAt, roomId);

            _logger.LogWarning($"Send to Connected Devices: {sw.ElapsedMilliseconds} millisecond");
            _logger.LogWarning($"Message id: {message?.Id ?? -1}");

            // production에서만 푸시
            // TODO: DeviceType에 simulator/emulator/vertual을 추가해서 개발 도중에도 푸시 받을 수 있도록 한다.
            if (_env.IsDevelopment())
            {
                sw.Stop();
                return;
            }

            sw.Restart();

            #region push
            // 룸에 속한 유저의 디바이스들 중 !IsOn인 디바이스는 푸시
            var room = await _dbContext.Rooms
                       .Include(room => room.Enrollments)
                       .ThenInclude(enrollment => enrollment.User)
                       .ThenInclude(user => user.Devices)
                       .AsNoTracking()
                       .FirstOrDefaultAsync(r => r.Id == roomId);

            _logger.LogWarning($"Select un-connected devices: {sw.ElapsedMilliseconds}");

            sw.Restart();

            var pushDic = new Dictionary <string, string>();

            foreach (Enrollment enroll in room.Enrollments)
            {
                if (enroll.UserId != UserId)
                {
                    foreach (Device device in enroll.User.Devices)
                    {
                        if (enroll.User.UserType == UserType.Consumer)
                        {
                            if (!device.IsOn && device.IsActive && (device.DeviceType == Core.Data.DeviceType.iOS || device.DeviceType == Core.Data.DeviceType.Android))
                            {
                                pushDic.Add(device.Id, device.DeviceType == Core.Data.DeviceType.iOS ? "iOS" : "Android");
                            }
                        }
                        else // UserType.Staff, UserType.Admin, UserType.Super
                        {
                            if (!device.IsOn && device.IsActive && (device.DeviceType == Core.Data.DeviceType.iOS || device.DeviceType == Core.Data.DeviceType.Android))
                            {
                                pushDic.Add(device.Id, device.DeviceType == Core.Data.DeviceType.iOS ? "staff-iOS" : "staff-Android");
                            }
                        }
                    }
                }
            }

            //if (pushDic.Count > 0 && false)
            if (pushDic.Count > 0)
            {
                var customDataDic = new Dictionary <string, string>();
                customDataDic.Add("sound", "default");
                customDataDic.Add("room", roomId);
                customDataDic.Add("body", body);
                customDataDic.Add("sender", user.Name);

                var pushService = new PushService(pushDic);

                foreach (var push in pushDic)
                {
                    _logger.LogWarning($"Push message to [{push.Key}]({push.Value}) from {user.Name}");
                }

                var result = await pushService.Push(user.Name, body, customDataDic);

                _logger.LogWarning($"push result: {result}");
            }

            sw.Stop();
            _logger.LogWarning($"Push to unconnected Devices: {sw.ElapsedMilliseconds}");

            #endregion
        }