Exemple #1
0
        public async Task <FilterDetailsDto> Update(int id, FilterUpdateDto updateDto)
        {
            var updateFilter = _domainService.Find(id);

            if (updateFilter == null)
            {
                throw SocialExceptions.FilterNotExists(id);
            }
            if (updateDto.IfPublic == false && updateFilter.IfPublic == true)
            {
                updateFilter.CreatedBy = UserContext.UserId;
            }
            _domainService.DeleteConditons(updateFilter);
            Mapper.Map(updateDto, updateFilter);
            _domainService.UpdateFilter(updateFilter, Mapper.Map <List <FilterConditionCreateDto>, List <FilterCondition> >(updateDto.Conditions.ToList()).ToArray());
            using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                CurrentUnitOfWork.SaveChanges();
                uow.Complete();
            }
            await _notificationManager.NotifyUpdateFilter(updateFilter.SiteId, updateFilter.Id);

            var filterDto = Mapper.Map <FilterDetailsDto>(updateFilter);
            List <FilterDetailsDto> filterDtos = new List <FilterDetailsDto>();

            filterDtos.Add(filterDto);
            _agentService.FillCreatedByName(filterDtos);
            return(filterDto);
        }
Exemple #2
0
        public IList <FilterManageDto> SortingFilters([Required] IList <FilterSortDto> sortDtoList)
        {
            if (!sortDtoList.Any())
            {
                throw SocialExceptions.BadRequest("sortDtoList is required.");
            }

            return(_appService.Sorting(sortDtoList));
        }
Exemple #3
0
 public void CheckIfCanReopenWhenReply(Conversation conversation)
 {
     if (conversation.Status == ConversationStatus.Closed)
     {
         if (!IfCanReopen(conversation))
         {
             throw SocialExceptions.OnlyOneOpenConversationAllowedForPrivateMessage();
         }
     }
 }
        protected override Expression <Func <Conversation, bool> > After(string date)
        {
            DateTime value;

            if (!DateTime.TryParse(date, out value))
            {
                throw SocialExceptions.BadRequest("The value of date time is invalid");
            }
            return(t => t.LastMessageSentTime > value);
        }
Exemple #5
0
        public bool HasConversation(int filterId, int conversationId)
        {
            var filter = _domainService.Find(filterId);

            if (filter == null)
            {
                throw SocialExceptions.FilterNotExists(filterId);
            }
            return(_domainService.HasConversation(filter, conversationId));
        }
Exemple #6
0
        protected override Expression <Func <Conversation, bool> > Before(string date)
        {
            DateTime value;

            if (!DateTime.TryParse(date, out value))
            {
                throw SocialExceptions.BadRequest("The value of date time is invalid");
            }
            return(t => t.ModifiedTime.HasValue && t.ModifiedTime.Value < value);
        }
Exemple #7
0
 private void CheckIfCanReopenWhenUpdate(Conversation oldEntity, Conversation newEntity)
 {
     if (oldEntity.Status == ConversationStatus.Closed && newEntity.Status != ConversationStatus.Closed)
     {
         if (!IfCanReopen(oldEntity))
         {
             throw SocialExceptions.OnlyOneOpenConversationAllowedForPrivateMessage();
         }
     }
 }
Exemple #8
0
        public FacebookPageDto GetPage(int id)
        {
            var entity = _socialAccountService.FindAccount(id, SocialUserSource.Facebook);

            if (entity == null)
            {
                throw SocialExceptions.FacebookPageNotExists(id);
            }
            return(Mapper.Map <FacebookPageDto>(entity));
        }
Exemple #9
0
        public void CheckFieldValue(List <FilterCondition> filterConditons)
        {
            var conversationField = _conversationFieldOptionService.FindAllAndFillOptions().Where(t => filterConditons.Select(f => f.FieldId).Contains(t.Id)).ToList();

            foreach (var filterConditon in filterConditons)
            {
                if (conversationField.Where(t => t.Id == filterConditon.FieldId).FirstOrDefault().DataType == FieldDataType.DateTime)
                {
                    if (conversationField.Where(t => t.Id == filterConditon.FieldId && t.Options.Any(o => o.Value == filterConditon.Value)).Count() == 0)
                    {
                        if (filterConditon.MatchType == ConditionMatchType.Between)
                        {
                            string[] value = filterConditon.Value.Split('|');
                            DateTime DateTime1;
                            if (!DateTime.TryParse(value[0], out DateTime1))
                            {
                                throw SocialExceptions.BadRequest("The value of date time is invalid");
                            }
                            DateTime DateTime2;
                            if (!DateTime.TryParse(value[1], out DateTime2))
                            {
                                throw SocialExceptions.BadRequest("The value of date time is invalid");
                            }
                        }
                        else
                        {
                            DateTime date;
                            if (!DateTime.TryParse(filterConditon.Value, out date))
                            {
                                throw SocialExceptions.BadRequest($"The value's type is not DateTime : '{filterConditon.Value}' ");
                            }
                        }
                    }
                }
                else if (conversationField.Where(t => t.Id == filterConditon.FieldId).FirstOrDefault().DataType == FieldDataType.Number)
                {
                    int number;
                    if (!int.TryParse(filterConditon.Value, out number))
                    {
                        throw SocialExceptions.BadRequest($"The value's type is not Number : '{filterConditon.Value}' ");
                    }
                }
                else if (conversationField.Where(t => t.Id == filterConditon.FieldId).FirstOrDefault().DataType == FieldDataType.Option)
                {
                    if (conversationField.Where(t => t.Id == filterConditon.FieldId && t.Options.Any(o => o.Value == filterConditon.Value)).Count() == 0)
                    {
                        if ((!departmentAddOptions.Contains(filterConditon.Value) || !departmentFieldNames.Contains(conversationField.Where(t => t.Id == filterConditon.FieldId).FirstOrDefault().Name)) &&
                            (!agentAddOptions.Contains(filterConditon.Value) || !agentsFieldNames.Contains(conversationField.Where(t => t.Id == filterConditon.FieldId).FirstOrDefault().Name)))
                        {
                            throw SocialExceptions.BadRequest($"The value's type is not Option : '{filterConditon.Value}' ");
                        }
                    }
                }
            }
        }
        public async Task DeleteAccountAsync(int id)
        {
            var entity = _socialAccountService.FindAccount(id, SocialUserSource.Twitter);

            if (entity == null)
            {
                throw SocialExceptions.TwitterAccountNotExists(id);
            }

            await _socialAccountService.DeleteAsync(entity);
        }
        public TwitterAccountDto GetAccount(int id)
        {
            var entity = _socialAccountService.FindAccount(id, SocialUserSource.Twitter);

            if (entity == null)
            {
                throw SocialExceptions.TwitterAccountNotExists(id);
            }

            return(Mapper.Map <TwitterAccountDto>(entity));
        }
Exemple #12
0
        public async Task Delete(int id)
        {
            var filter = _domainService.Find(id);

            if (filter == null)
            {
                throw SocialExceptions.FilterNotExists(id);
            }
            _domainService.Delete(id);
            await _notificationManager.NotifyDeleteFilter(filter.SiteId, filter.Id);
        }
Exemple #13
0
        protected override Expression <Func <Conversation, bool> > Is(string date)
        {
            DateTime value;

            if (!DateTime.TryParse(date, out value))
            {
                throw SocialExceptions.BadRequest("The value of date time is invalid");
            }
            return(t => t.ModifiedTime.HasValue && ((DateTime)t.ModifiedTime.Value).Year == value.Year &&
                   ((DateTime)t.ModifiedTime.Value).Month == value.Month &&
                   ((DateTime)t.ModifiedTime.Value).Day == value.Day);
        }
        public SocialAccount MarkAsEnable(int id, bool?ifEnable = true)
        {
            var account = this.Find(id);

            if (account == null)
            {
                throw SocialExceptions.SocialUserIdNotExists(id);
            }
            account.IfEnable = ifEnable.Value;
            this.Update(account);
            return(account);
        }
        public async Task <SocialAccount> AddFacebookPageAsync(SocialAccount socialAccount, string originalId)
        {
            if (IsDupliated(SocialUserSource.Facebook, originalId))
            {
                throw SocialExceptions.BadRequest($"'{socialAccount.SocialUser.Name}' has already been added.");
            }

            await _fbClient.SubscribeApp(originalId, socialAccount.Token);

            var socialUser = _socialUserRepo.FindAll()
                             .Where(t => t.OriginalId == originalId && t.Source == SocialUserSource.Facebook)
                             .OrderByDescending(t => t.Id)
                             .FirstOrDefault();

            if (socialUser == null)
            {
                // create a new integraton account.
                await this.InsertAsync(socialAccount);
            }
            else
            {
                // if the user was a customer or a deleted integration account.
                socialUser.Type          = SocialUserType.IntegrationAccount; // make sure convert a customer to integration account.
                socialUser.IsDeleted     = false;                             // make sure to restore a deleted integration account.
                socialUser.Avatar        = socialAccount.SocialUser.Avatar;
                socialUser.Email         = socialAccount.SocialUser.Email;
                socialUser.OriginalLink  = socialAccount.SocialUser.OriginalLink;
                socialAccount.Id         = socialUser.Id;
                socialAccount.SocialUser = socialUser;
                if (socialUser.SocialAccount == null)
                {
                    socialUser.SocialAccount = socialAccount;
                }
                else
                {
                    socialUser.SocialAccount.Token = socialAccount.Token;
                    socialUser.SocialAccount.FacebookPageCategory = socialAccount.FacebookPageCategory;
                    socialUser.SocialAccount.FacebookSignInAs     = socialAccount.FacebookSignInAs;
                }
                socialUser.SocialAccount.IsDeleted = false;
                socialUser.SocialAccount.IfEnable  = true;
                socialUser.SocialAccount.IfConvertMessageToConversation     = true;
                socialUser.SocialAccount.IfConvertVisitorPostToConversation = true;
                socialUser.SocialAccount.IfConvertWallPostToConversation    = true;
                _socialUserRepo.Update(socialUser);

                await this.InsertSocialAccountInGeneralDb(SocialUserSource.Facebook, originalId);
            }

            CurrentUnitOfWork.SaveChanges();
            return(this.Find(socialAccount.Id));
        }
Exemple #16
0
        public async Task UnSubscribeApp(string pageId, string pageToken)
        {
            FacebookClient client = new FacebookClient();

            try
            {
                await client.DeleteTaskAsync($"https://graph.facebook.com/v2.9/{pageId}/subscribed_apps?access_token={pageToken}");
            }
            catch (FacebookOAuthException ex)
            {
                throw SocialExceptions.FacebookOauthException(ex);
            }
        }
Exemple #17
0
        public async Task DeletePageAsync(int id)
        {
            var entity = _socialAccountService.FindAccount(id, SocialUserSource.Facebook);

            if (entity == null)
            {
                throw SocialExceptions.FacebookPageNotExists(id);
            }

            await _socialAccountService.DeleteAsync(entity);

            await _fbClient.UnSubscribeApp(entity.SocialUser.OriginalId, entity.Token);
        }
Exemple #18
0
        public FilterDetailsDto Find(int id)
        {
            var filter = _domainService.Find(id);

            if (filter == null)
            {
                throw SocialExceptions.FilterNotExists(id);
            }
            var filterDto = Mapper.Map <FilterDetailsDto>(filter);

            filterDto.CreatedByName = _agentService.GetDisplayName(filterDto.CreatedBy);
            return(filterDto);
        }
Exemple #19
0
        public Message ReplyTwitterDirectMessage(int conversationId, string message, bool isCloseConversation = false)
        {
            var twitterService = DependencyResolver.Resolve <ITwitterService>();

            Conversation conversation = _conversationService.CheckIfExists(conversationId);

            if (conversation.Source != ConversationSource.TwitterDirectMessage)
            {
                throw SocialExceptions.BadRequest("Conversation source must be twitter direct message.");
            }

            _conversationService.CheckIfCanReopenWhenReply(conversation);

            var           messages       = Repository.FindAll().Include(t => t.Sender).Include(t => t.Receiver).Where(t => t.ConversationId == conversation.Id).ToList();
            SocialAccount twitterAccount = GetSocialAccountFromMessages(messages);

            if (twitterAccount == null)
            {
                throw SocialExceptions.BadRequest($"Twitter account has been deleted.");
            }

            var customer = messages.Where(t => t.IsDeleted == false && t.Sender.Type == SocialUserType.Customer)
                           .OrderByDescending(t => t.SendTime).Select(t => t.Sender).FirstOrDefault();

            if (customer == null)
            {
                throw new NotSupportedException($"Cant't find last message from conversation. Conversation Id={conversationId}.");
            }

            IUser prviousTwitterUser = twitterService.GetUser(twitterAccount, long.Parse(customer.OriginalId));

            if (prviousTwitterUser == null)
            {
                throw new NotSupportedException($"Cant't find twitter user. Conversation Id={conversationId}.");
            }

            // publish twitter direct message
            IMessage twitterDirectMessage = twitterService.PublishMessage(twitterAccount, prviousTwitterUser, message);

            // create message to db
            Message directMessage = TwitterConverter.ConvertToMessage(twitterDirectMessage);

            directMessage.ConversationId = conversation.Id;
            directMessage.SenderId       = twitterAccount.Id;
            directMessage.SendAgentId    = UserContext.UserId;
            directMessage.ReceiverId     = customer.Id;

            Save(directMessage, isCloseConversation);

            return(this.Find(directMessage.Id));
        }
        public TwitterAccountDto UpdateAccount(int id, UpdateTwitterAccountDto dto)
        {
            var socialAccount = _socialAccountService.FindAccount(id, SocialUserSource.Twitter);

            if (socialAccount == null)
            {
                throw SocialExceptions.TwitterAccountNotExists(id);
            }

            socialAccount = Mapper.Map(dto, socialAccount);
            _socialAccountService.Update(socialAccount);

            return(Mapper.Map <TwitterAccountDto>(socialAccount));
        }
Exemple #21
0
        public Conversation CheckIfExists(int id)
        {
            var conversation = Repository.Find(id);

            if (conversation == null)
            {
                throw SocialExceptions.ConversationIdNotExists(id);
            }
            if (conversation.IsDeleted)
            {
                throw SocialExceptions.ConversationIdDelete(id);
            }
            return(conversation);
        }
Exemple #22
0
        public FacebookPageDto UpdatePage(int id, UpdateFacebookPageDto dto)
        {
            var socialAccount = _socialAccountService.FindAccount(id, SocialUserSource.Facebook);

            if (socialAccount == null)
            {
                throw SocialExceptions.FacebookPageNotExists(id);
            }

            socialAccount = Mapper.Map(dto, socialAccount);
            _socialAccountService.Update(socialAccount);

            return(Mapper.Map <FacebookPageDto>(socialAccount));
        }
Exemple #23
0
        public void CheckFieldIdExist(List <FilterCondition> filterConditons)
        {
            List <int> fieldIds = new List <int>();

            foreach (var filterCondition in filterConditons)
            {
                fieldIds.Add(filterCondition.FieldId);
            }
            fieldIds.RemoveAll(a => _conversationFieldRepo.FindAll().Where(t => fieldIds.Contains(t.Id)).Select(t => t.Id).ToList().Contains(a));
            if (fieldIds.Count != 0)
            {
                throw SocialExceptions.BadRequest($"FieldId '{fieldIds[0]}' not exists");
            }
        }
Exemple #24
0
        public FilterListDto FindSummary(int id)
        {
            var filter = _domainService.Find(id);

            if (filter == null)
            {
                throw SocialExceptions.FilterNotExists(id);
            }

            var dto = Mapper.Map <FilterListDto>(filter);

            dto.ConversationNum = _domainService.GetConversationNum(filter);
            dto.CreatedByName   = _agentService.GetDisplayName(dto.CreatedBy);

            return(dto);
        }
Exemple #25
0
        public Message ReplyFacebookMessage(int conversationId, string content, bool isCloseConversation = false)
        {
            var conversation = _conversationService.CheckIfExists(conversationId);

            if (conversation.Source != ConversationSource.FacebookMessage)
            {
                throw SocialExceptions.BadRequest("Conversation source must be facebook message.");
            }

            _conversationService.CheckIfCanReopenWhenReply(conversation);

            var           messages      = Repository.FindAll().Include(t => t.Sender).Include(t => t.Receiver).Where(t => t.ConversationId == conversation.Id).ToList();
            SocialAccount socialAccount = GetSocialAccountFromMessages(messages);

            if (socialAccount == null)
            {
                throw SocialExceptions.BadRequest("Facebook integration account can't be found from conversation.");
            }

            SocialUser recipient = messages.Where(t => t.Sender.Type == SocialUserType.Customer)
                                   .OrderByDescending(t => t.SendTime)
                                   .Select(t => t.Sender).FirstOrDefault();

            // publish message to facebook
            string fbMessageId = _fbClient.PublishMessage(socialAccount.Token, conversation.OriginalId, content);

            if (string.IsNullOrWhiteSpace(fbMessageId))
            {
                return(null);
            }
            // create message
            var message = new Message
            {
                ConversationId = conversation.Id,
                Content        = content,
                SenderId       = socialAccount.Id,
                ReceiverId     = recipient != null ? recipient.Id : socialAccount.Id,
                SendAgentId    = UserContext.UserId,
                SendTime       = DateTime.UtcNow,
                OriginalId     = fbMessageId,
                Source         = MessageSource.FacebookMessage
            };

            Save(message, isCloseConversation);

            return(this.Find(message.Id));
        }
Exemple #26
0
        public IQueryable <Conversation> ApplyFilter(IQueryable <Conversation> conversations, int?filterId)
        {
            if (filterId != null)
            {
                var filter = _filterRepo.Find(filterId.Value);
                if (filter != null)
                {
                    conversations = ApplyFilter(conversations, filter);
                }
                else
                {
                    throw SocialExceptions.BadRequest($"filterId '{filterId}' not exists.");
                }
            }

            return(conversations);
        }
Exemple #27
0
        protected override Expression <Func <Conversation, bool> > Between(string date)
        {
            string[] value = date.Split('|');
            DateTime DateTime1;

            if (!DateTime.TryParse(value[0], out DateTime1))
            {
                throw SocialExceptions.BadRequest("The value of date time is invalid");
            }
            DateTime DateTime2;

            if (!DateTime.TryParse(value[1], out DateTime2))
            {
                throw SocialExceptions.BadRequest("The value of date time is invalid");
            }
            return(t => t.ModifiedTime.HasValue && t.ModifiedTime.Value >= DateTime1 && t.ModifiedTime.Value <= DateTime2);
        }
Exemple #28
0
        public async Task <FbToken> GetApplicationToken()
        {
            if (_applicationTokenCache != null && _applicationTokenCache.Item2 > DateTime.UtcNow)
            {
                return(_applicationTokenCache.Item1);
            }

            FacebookClient client  = new FacebookClient();
            FbToken        fbToken = null;

            try
            {
                dynamic result = client.Post("oauth/access_token", new
                {
                    client_id     = AppSettings.FacebookClientId,
                    client_secret = AppSettings.FacebookClientSecret,
                    grant_type    = "client_credentials",
                });
                fbToken = new FbToken
                {
                    AccessToken = result.access_token,
                    Type        = result.token_type,
                    ExpiresIn   = result.expires_in
                };
            }
            catch (FacebookOAuthException ex)
            {
                throw SocialExceptions.FacebookOauthException(ex);
            }

            //HttpClient client = new HttpClient();
            //string url =
            //    string.Format(
            //        "https://graph.facebook.com/v2.9/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials",
            //        AppSettings.FacebookClientId,
            //        AppSettings.FacebookClientSecret
            //        );

            //HttpResponseMessage response = await client.GetAsync(url);
            //response.EnsureSuccessStatusCode();
            //var jsonRes = await response.Content.ReadAsStringAsync();
            //var fbToken = JsonConvert.DeserializeObject<FbToken>(jsonRes);

            _applicationTokenCache = new Tuple <FbToken, DateTime>(fbToken, DateTime.UtcNow.AddHours(1));
            return(fbToken);
        }
        public IList <ConversationDto> FindConversations(int socialUserId)
        {
            SocialUser user = _domainService.Find(socialUserId);

            if (user == null)
            {
                throw SocialExceptions.SocialUserIdNotExists(socialUserId);
            }

            ConversationSearchDto searchDto = new ConversationSearchDto();

            if (user != null)
            {
                searchDto.UserId = user.Id;
                return(_conversationService.Find(searchDto));
            }
            return(null);
        }
Exemple #30
0
        public string GetUserToken(string code, string redirectUri)
        {
            FacebookClient client = new FacebookClient();

            try
            {
                dynamic result = client.Post("oauth/access_token", new
                {
                    client_id     = AppSettings.FacebookClientId,
                    client_secret = AppSettings.FacebookClientSecret,
                    redirect_uri  = redirectUri,
                    code          = code
                });
                return(result.access_token);
            }
            catch (FacebookOAuthException ex)
            {
                throw SocialExceptions.FacebookOauthException(ex);
            }
        }