private List <SocialMediaImageDescription> GetFacebookImageDescriptionList(List <String> facebookAccounts, Tenant tenant) { var images = new List <SocialMediaImageDescription>(); if (facebookAccounts.Count == 0) { return(images); } try { CoreContext.TenantManager.SetCurrentTenant(tenant); var provider = new FacebookDataProvider(FacebookApiHelper.GetFacebookApiInfoForCurrentUser()); facebookAccounts = facebookAccounts.Distinct().ToList(); images.AddRange(from facebookAccount in facebookAccounts let imageUrl = provider.GetUrlOfUserImage(facebookAccount, FacebookDataProvider.ImageSize.Small) where imageUrl != null select new SocialMediaImageDescription { Identity = facebookAccount, ImageUrl = imageUrl, SocialNetwork = SocialNetworks.Facebook }); } catch (Exception ex) { _logger.Error(ex); } return(images); }
public string ShowFacebookUserRelationWindow(string userID) { try { //Process authorization if (!ProcessAuthorization(HttpContext.Current)) { AccessDenied(HttpContext.Current); return(null); } FacebookApiInfo apiInfo = FacebookApiHelper.GetFacebookApiInfoForCurrentUser(); if (apiInfo == null) { throw new SocialMediaAccountNotFound(SocialMediaResource.SocialMediaAccountNotFoundFacebook); } FacebookDataProvider provider = new FacebookDataProvider(apiInfo); FacebookUserInfo user = provider.LoadUserInfo(userID); return(GetFacebookUserInfoPage(user)); } catch (Exception ex) { throw ProcessError(ex, "ShowTwitterUserRelationWindow"); } }
private List <SocialMediaImageDescription> GetFacebookImageDescriptionList(Contact contact, Tenant tenant) { CoreContext.TenantManager.SetCurrentTenant(tenant); var images = new List <SocialMediaImageDescription>(); var facebookAccounts = Global.DaoFactory.GetContactInfoDao().GetListData(contact.ID, ContactInfoType.Facebook); if (facebookAccounts.Count == 0) { return(images); } var provider = new FacebookDataProvider(FacebookApiHelper.GetFacebookApiInfoForCurrentUser()); images.AddRange(from facebookAccount in facebookAccounts let imageUrl = provider.GetUrlOfUserImage(facebookAccount, FacebookDataProvider.ImageSize.Small) where imageUrl != null select new SocialMediaImageDescription { Identity = facebookAccount, ImageUrl = imageUrl, SocialNetwork = SocialNetworks.Facebook }); return(images); }
public string FindFacebookProfiles(string searchText) { try { //Process authorization if (!ProcessAuthorization(HttpContext.Current)) { AccessDenied(HttpContext.Current); return(null); } FacebookApiInfo apiInfo = FacebookApiHelper.GetFacebookApiInfoForCurrentUser(); if (apiInfo == null) { throw new SocialMediaAccountNotFound(SocialMediaResource.SocialMediaAccountNotFoundFacebook); } FacebookDataProvider facebookProvider = new FacebookDataProvider(apiInfo); List <FacebookUserInfo> users = facebookProvider.FindUsers(searchText); string result = JsonConvert.SerializeObject(users); return(result); } catch (Exception ex) { throw ProcessError(ex, "FindTwitterProfiles"); } }
public void UpdatePageConversations(Facebookaccounts facebookAccount) { try { var conversations = FacebookApiHelper.GetConversations(facebookAccount.AccessToken); var conversationCollections = JObject.Parse(conversations); var conversationCollection = conversationCollections.SelectTokens("data").SelectMany(x => x) .Select(item => new MongoDirectMessages { messageId = item.SelectToken("id")?.ToString(), createdDate = Convert.ToDateTime(item.SelectToken("updated_time")?.ToString() ?? DateTime.Now.ToString(CultureInfo.InvariantCulture)).ToString("yyyy/MM/dd HH:mm:ss"), ConversationLink = item.SelectToken("link")?.ToString(), type = MessageType.FacebookPagDirectMessageReceived }).ToList(); AddConversationDetailsToDb(conversationCollection); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Маршрутизатор текстовых сообщений /// </summary> /// <param name="thisQuery"></param> /// <param name="type"></param> /// <param name="Bot"></param> /// <param name="botUser"></param> /// <param name="text"></param> /// <param name="Requests"></param> /// <returns></returns> public async Task <int> SendText(string text) { TelegramBotClient telegram = null; FacebookApiHelper facebook = null; int IsError = 0; if (type == SocialNetworkType.Telegram) { telegram = (TelegramBotClient)Bot; } if (type == SocialNetworkType.Facebook) { facebook = (FacebookApiHelper)Bot; } if (type == SocialNetworkType.VK) { //var cont = new SenderContext("Z_Messages"); //cont.Message.Add(new BotMessage { BotUserVKID = botUser.BotUserVKID, Text = text, DateTime = DateTime.Now, IsSended = false }); //cont.SaveChanges(); Requests.Add(new VKApiRequestModel(ulong.Parse(botUser.BotUserVKID), text)); } if (type == SocialNetworkType.Telegram) { text = BotTextHelper.SmileCodesReplace(text); await telegram.SendTextMessageAsync(botUser.BotUserTelegramID, text); } if (type == SocialNetworkType.Facebook) { IsError = await facebook.SendMessage(botUser.BotUserFacebookID, text); } return(IsError); }
public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Models.ScheduledMessage schmessage, Domain.Socioboard.Models.User _user) { string ret = ""; var dbr = new DatabaseRepository(); try { var pageAccessToken = FacebookApiHelper.GetPageAccessToken(fbUserId, accessToken, string.Empty); var response = FacebookApiHelper.PublishPostOnPage(pageAccessToken, fbUserId, message, imagePath, link); var isPublished = response.Contains("id"); // if (isPublished) { schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated; dbr.Update(schmessage); var notify = new Notifications(); var notifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id); if (notifications == null) { notify.MsgId = schmessage.id; notify.MsgStatus = "Scheduled"; notify.notificationtime = schmessage.localscheduletime; notify.NotificationType = "Schedule Successfully"; notify.ReadOrUnread = "Unread"; notify.UserId = userId; dbr.Add(notify); if (_user.scheduleSuccessUpdates) { var sucResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword); } } } } catch (Exception ex) { schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.error; dbr.Update(schmessage); apiHitsCount = MaxapiHitsCount; var notify = new Notifications(); var notifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id); if (notifications == null) { notify.MsgId = schmessage.id; notify.MsgStatus = "Failed"; notify.notificationtime = schmessage.localscheduletime; notify.NotificationType = "Schedule Failed"; notify.ReadOrUnread = "Unread"; notify.UserId = userId; dbr.Add(notify); if (_user.scheduleFailureUpdates) { var falResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword); } } } return(ret); }
/// <summary> /// /// </summary> /// <param name="accessToken"></param> /// <param name="id"></param> /// <param name="timeInterVal"></param> public static void SchedulePagePost(string accessToken, string destinationPageId, string sourcePageId, int timeInterVal) { try { var timeIncrementer = 1; var cursorNext = string.Empty; do { var feeds = Fbpages.getFacebookPageRecentPost(accessToken, sourcePageId, cursorNext); if (string.IsNullOrEmpty(feeds) || feeds.Equals("[]")) { continue; } var fbPageNotes = JObject.Parse(feeds); try { cursorNext = fbPageNotes["paging"]["next"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.Message); cursorNext = "0"; } foreach (var obj in JArray.Parse(fbPageNotes["data"].ToString())) { try { var postId = obj["id"].ToString(); postId = postId.Split('_')[1]; var timestamp = DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow.AddMinutes(timeInterVal * timeIncrementer)); var link = "https://www.facebook.com/" + sourcePageId + "/posts/" + postId; var pageAccessToken = FacebookApiHelper.GetPageAccessToken(destinationPageId, accessToken, string.Empty); var status = FacebookApiHelper.PublishPostOnSchedule(string.Empty, accessToken, destinationPageId, link, timestamp.ToString(CultureInfo.InvariantCulture)); if (status) { timeIncrementer++; } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } while (cursorNext != "0"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public string ShareFeed(string fbAccesstoken, string feedId, string pageId, string message, string fbUserId, string fbPageName) { try { var mongoRepository = new MongoRepository("SharethonPagePost"); var link = "https://www.facebook.com/" + pageId + "/posts/" + feedId; var sharethonPagePostCollections = mongoRepository.Find <SharethonPagePost>(t => t.Facebookaccountid.Equals(fbUserId) && t.Facebookpageid.Equals(pageId) && t.PostId.Equals(feedId)); var task = Task.Run(async() => await sharethonPagePostCollections); var count = task.Result.Count; try { if (count < 1) { var pageAccessToken = FacebookApiHelper.GetPageAccessToken(pageId, fbAccesstoken, string.Empty); var response = FacebookApiHelper.PublishPostOnPage(pageAccessToken, pageId, string.Empty, string.Empty, link); var isPublished = response.Contains("id"); if (isPublished) { PageapiHitsCount++; } var objSharethonPagePost = new SharethonPagePost { Id = ObjectId.GenerateNewId(), Facebookaccountid = fbUserId, Facebookpageid = pageId, PostId = feedId, PostedTime = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow), Facebookpagename = fbPageName }; mongoRepository.Add(objSharethonPagePost); return("success"); } } catch (Exception ex) { Console.Write(ex.StackTrace); PageapiHitsCount = PageMaxapiHitsCount; return(string.Empty); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(string.Empty); }
public void UpdatePagePromotionPostDetails(Facebookaccounts facebookAccount) { try { var promotablePosts = FacebookApiHelper.GetPromotablePostsDetails(facebookAccount.AccessToken); var taggedDetailCollections = ParseTagAndPromoteDetails(facebookAccount, promotablePosts, FacebookPagePromotion.PromotablePosts).ToList(); AddedPromotionDetailsToDb(taggedDetailCollections); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static string FacebookComposeMessageRss(string message, string accessToken, string FbUserId, string title, string link, string rssFeedId) { string ret = ""; FacebookClient fb = new FacebookClient(); MongoRepository rssfeedRepo = new MongoRepository("RssFeed"); try { var pageAccessToken = FacebookApiHelper.GetPageAccessToken(FbUserId, accessToken, string.Empty); if (string.IsNullOrEmpty(pageAccessToken)) { return(string.Empty); } FacebookApiHelper.PublishPostOnPage(pageAccessToken, FbUserId, message, string.Empty, link); #region Old Methods //fb.AccessToken = accessToken; //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; //var args = new Dictionary<string, object>(); //if (message != null) //{ // args["message"] = message; //} //args["link"] = link; //ret = fb.Post("v2.7/" + FbUserId + "/feed", args).ToString(); #endregion var builders = Builders <BsonDocument> .Filter; FilterDefinition <BsonDocument> filter = builders.Eq("strId", rssFeedId); var update = Builders <BsonDocument> .Update.Set("Status", true); rssfeedRepo.Update <Domain.Socioboard.Models.Mongo.RssFeed>(update, filter); Thread.Sleep(1000 * 600); return(ret = "Messages Posted Successfully"); } catch (Exception ex) { if (ex.Message.Contains("Error validating access token: Session has expired on")) { Model.DatabaseRepository dbr = new DatabaseRepository(); Domain.Socioboard.Models.Facebookaccounts _Facebookaccounts = dbr.Find <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == FbUserId).First(); _Facebookaccounts.IsActive = false; dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(_Facebookaccounts); } Console.WriteLine(ex.Message); apiHitsCount = MaxapiHitsCount; return(ret = ""); } }
public void ParseAndUpdateAccountDetails(Facebookaccounts facebookAccount, DatabaseRepository databaseRepository) { try { var profileDetails = FacebookApiHelper.GetUserDetails(facebookAccount.AccessToken).ToString(); var profile = JObject.Parse(profileDetails); if (Convert.ToString(profile) == "Invalid Access Token") { return; } facebookAccount.Friends = FacebookApiHelper.GetFriendCounts(facebookAccount.AccessToken); ApiHitsCount++; facebookAccount.EmailId = profile.SelectToken("email")?.ToString(); facebookAccount.ProfileUrl = profile.SelectToken("link")?.ToString(); if (string.IsNullOrEmpty(facebookAccount.ProfileUrl)) { facebookAccount.ProfileUrl = profile.SelectToken("picture.data.url")?.ToString(); } facebookAccount.Gender = profile.SelectToken("gender")?.ToString(); facebookAccount.Bio = profile.SelectToken("bio")?.ToString(); facebookAccount.About = profile.SelectToken("about")?.ToString(); facebookAccount.CoverPic = profile.SelectToken("cover.source")?.ToString(); facebookAccount.Birthday = profile.SelectToken("birthday")?.ToString(); var profileEducationDetails = JArray.Parse(profile.SelectToken("education")?.ToString() ?? "[]"); facebookAccount.College = profileEducationDetails?.LastOrDefault()?.SelectToken("school.name")?.ToString(); facebookAccount.Education = profileEducationDetails?.LastOrDefault()?.SelectToken("concentration.name")?.ToString(); var profileWorkingDetails = JArray.Parse(profile["work"]?.ToString() ?? "[]"); facebookAccount.WorkPosition = profileWorkingDetails?.FirstOrDefault()?.SelectToken("position.name")?.ToString(); facebookAccount.WorkCompany = profileWorkingDetails?.FirstOrDefault()?.SelectToken("employer.name")?.ToString(); facebookAccount.LastUpdate = DateTime.UtcNow; databaseRepository.Update(facebookAccount); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static List <Domain.Socioboard.Models.FacebookGroup> GetAllFacebookGroups(string accessToken, string client_id, string redirect_uri, string client_secret) { var facebookGroups = FacebookApiHelper.GetFacebookGroups(accessToken); if (facebookGroups == null) { return(new List <FacebookGroup>()); } return(facebookGroups); #region Old Code //List<Domain.Socioboard.Models.FacebookGroup> lstAddFacebookGroup = new List<Domain.Socioboard.Models.FacebookGroup>(); //FacebookClient fb = new FacebookClient(); //string profileId = string.Empty; //dynamic output = null; //if (accessToken != null) //{ // try // { // fb.AccessToken = accessToken; // dynamic profile = fb.Get("v2.7/me"); // output = fb.Get("v2.7/me/groups"); // foreach (var item in output["data"]) // { // try // { // Domain.Socioboard.Models.FacebookGroup objAddFacebookGroup = new Domain.Socioboard.Models.FacebookGroup(); // objAddFacebookGroup.ProfileGroupId = item["id"].ToString(); // objAddFacebookGroup.Name = item["name"].ToString(); // objAddFacebookGroup.AccessToken = accessToken.ToString(); // lstAddFacebookGroup.Add(objAddFacebookGroup); // } // catch (Exception ex) // { // Console.WriteLine(ex.StackTrace); // } // } // } // catch (Exception ex) // { // return null; // } //} //return lstAddFacebookGroup; #endregion }
public IEnumerable <MongoMessageModel> UpdatePageNotifications(Facebookaccounts facebookAccount) { var notificationDetails = new List <MongoMessageModel>(); try { var notificationsDetails = FacebookApiHelper.GetPageNotifications(facebookAccount.AccessToken); var notifications = JObject.Parse(notificationsDetails); foreach (var item in notifications["data"]) { var inboxMessages = new MongoMessageModel { profileId = facebookAccount.FbUserId, type = MessageType.FacebookPageNotification, messageTimeStamp = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow) }; try { inboxMessages.Message = item.SelectToken("title")?.ToString(); inboxMessages.messageId = item.SelectToken("id").ToString(); inboxMessages.fromId = item.SelectToken("from.id").ToString(); inboxMessages.fromName = item.SelectToken("from.name").ToString(); inboxMessages.fromScreenName = item.SelectToken("from.name").ToString(); inboxMessages.fromProfileUrl = "http://graph.facebook.com/" + inboxMessages.fromId + "/picture?type=small"; inboxMessages.RecipientId = item.SelectToken("to.id").ToString(); inboxMessages.RecipientName = item.SelectToken("to.name").ToString(); inboxMessages.messageDate = Convert.ToDateTime(item["created_time"].ToString()).ToString(CultureInfo.InvariantCulture); notificationDetails.Add(inboxMessages); } catch (Exception ex) { Console.WriteLine(ex.Message); } } AddNotificationsToDb(notificationDetails); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(notificationDetails); }
public void UpdatePageDetails(Facebookaccounts facebookAccount, DatabaseRepository databaseRepository) { try { if (facebookAccount.FbPageSubscription == FbPageSubscription.NotSubscribed && FacebookApiHelper.MakeSubscribedWithApp(facebookAccount.AccessToken)) { facebookAccount.FbPageSubscription = FbPageSubscription.Subscribed; } var pageDetails = JObject.Parse(FacebookApiHelper.GetPageDetails(facebookAccount.AccessToken)); facebookAccount.Friends = long.Parse(pageDetails.SelectToken("fan_count")?.ToString() ?? "0"); databaseRepository.Update(facebookAccount); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public IEnumerable <FacebookPagePromotionDetails> UpdatePageTaggedDetails(Facebookaccounts facebookAccount) { var taggedDetailCollections = new List <FacebookPagePromotionDetails>(); try { var taggedDetails = FacebookApiHelper.GetPageTaggedDetails(facebookAccount.AccessToken); taggedDetailCollections = ParseTagAndPromoteDetails(facebookAccount, taggedDetails).ToList(); AddedPromotionDetailsToDb(taggedDetailCollections); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(taggedDetailCollections); }
public void UpdateFeeds(Facebookaccounts facebookAccount) { const int maximumPaginationCount = 25; var currentPage = 0; if (currentPage >= maximumPaginationCount) { return; } string feeds = FacebookApiHelper.GetOwnFeedDetails(facebookAccount.AccessToken).ToString(); var feedDetails = JObject.Parse(feeds); string nextPaginationUrl; do { nextPaginationUrl = feedDetails.SelectToken("paging.next")?.ToString(); var postDetails = FetchAccountsFeedDetails(facebookAccount, feedDetails).ToList(); if (postDetails.Count > 0) { UpdatePostsToDb(postDetails); if (!string.IsNullOrEmpty(nextPaginationUrl)) { feedDetails = JObject.Parse(FacebookApiHelper .GetResponse(nextPaginationUrl, facebookAccount.AccessToken).ToString()); } } else { nextPaginationUrl = string.Empty; } currentPage++; if (currentPage > maximumPaginationCount) { nextPaginationUrl = string.Empty; } } while (!string.IsNullOrEmpty(nextPaginationUrl)); }
public async Task <ActionResult> FacebookSendMessageSubmit(UserInfo userInfo) { // After Index method renders the View, user clicks Send Mail, which comes in here. EnsureUser(ref userInfo); SendMessageResponse sendMessageResult = new SendMessageResponse(); // Send email using the Microsoft Graph API. var token = Data.GetUserSessionTokenAny(Settings.GetUserAuthStateId(ControllerContext.HttpContext)); if (token.Provider == Settings.FacebookAuthority) { sendMessageResult = await FacebookApiHelper.PostMessageAsync(token.AccessToken, token.Username, Settings.MessageSubject); } // Reuse the Index view for messages (sent, not sent, fail) . // Redirect to tell the browser to call the app back via the Index method. return(RedirectToAction(nameof(Facebook), new RouteValueDictionary(new Dictionary <string, object> { { "Status", sendMessageResult.Status }, { "StatusMessage", sendMessageResult.StatusMessage }, { "Address", userInfo.Address }, }))); }
public async Task <int> SendPhoto(byte [] image, string caption = "") { TelegramBotClient telegram = null; FacebookApiHelper facebook = null; int IsError = 0; if (type == SocialNetworkType.Telegram) { telegram = (TelegramBotClient)Bot; } if (type == SocialNetworkType.Facebook) { facebook = (FacebookApiHelper)Bot; } if (type == SocialNetworkType.VK) { //var cont = new SenderContext("Z_Messages"); //var mes = new BotMessage { BotUserVKID = botUser.BotUserVKID, Text = caption, DateTime = DateTime.Now, IsSended = false, Photo = image }; //cont.Message.Add(mes); //cont.SaveChanges(); //TODO Убрать //#if DEBUG // System.IO.File.WriteAllBytes(@"C:\Temp\vk.png", image); //#endif Requests.Add(new VKApiRequestModel(ulong.Parse(botUser.BotUserVKID), caption, RequestType.SendMessageWithPhoto, image)); } if (type == SocialNetworkType.Telegram) { await telegram.SendPhotoAsync(botUser.BotUserTelegramID, new FileToSend("photo.jpg", new MemoryStream(image)), caption); } if (type == SocialNetworkType.Facebook) { IsError = await facebook.UrlSendPhoto(botUser.BotUserFacebookID, (Bitmap)Image.FromStream(new MemoryStream(image))); } return(IsError); }
public string FindUsers(string searchText, string socialNetwork) { try { //Process authorization if (!ProcessAuthorization(HttpContext.Current)) { AccessDenied(HttpContext.Current); return(null); } if (socialNetwork.ToLower() == "twitter") { TwitterDataProvider provider = new TwitterDataProvider(TwitterApiHelper.GetTwitterApiInfoForCurrentUser()); List <TwitterUserInfo> users = provider.FindUsers(searchText); return(GetTwitterUserListPage(users)); } if (socialNetwork.ToLower() == "facebook") { FacebookApiInfo apiInfo = FacebookApiHelper.GetFacebookApiInfoForCurrentUser(); if (apiInfo == null) { throw new SocialMediaAccountNotFound(SocialMediaResource.SocialMediaAccountNotFoundFacebook); } FacebookDataProvider facebookProvider = new FacebookDataProvider(apiInfo); List <FacebookUserInfo> users = facebookProvider.FindUsers(searchText); return(GetFacebookUserListPage(users)); } return(null); } catch (Exception ex) { throw ProcessError(ex, "FindUsers"); } }
public string SaveUserAvatarFromSocialNetwork(int contactID, SocialNetworks socialNetwork, string userIdentity) { try { //Process authorization if (!ProcessAuthorization(HttpContext.Current)) { AccessDenied(HttpContext.Current); return(null); } if (socialNetwork == SocialNetworks.Twitter) { TwitterDataProvider provider = new TwitterDataProvider(TwitterApiHelper.GetTwitterApiInfoForCurrentUser()); string imageUrl = provider.GetUrlOfUserImage(userIdentity, TwitterDataProvider.ImageSize.Original); return(SaveAvatar(contactID, imageUrl)); } if (socialNetwork == SocialNetworks.Facebook) { FacebookDataProvider provider = new FacebookDataProvider(FacebookApiHelper.GetFacebookApiInfoForCurrentUser()); string imageUrl = provider.GetUrlOfUserImage(userIdentity, FacebookDataProvider.ImageSize.Original); return(SaveAvatar(contactID, imageUrl)); } if (socialNetwork == SocialNetworks.LinkedIn) { LinkedInDataProvider provider = LinkedInApiHelper.GetLinkedInDataProviderForCurrentUser(); string imageUrl = provider.GetUrlOfUserImage(userIdentity); return(SaveAvatar(contactID, imageUrl)); } return(null); } catch (Exception ex) { throw ProcessError(ex, "SaveUserAvatarFromSocialNetwork"); } }
public static string DaywiseComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Models.DaywiseSchedule schmessage, Domain.Socioboard.Models.User _user) { string ret = ""; var dbr = new DatabaseRepository(); try { var pageAccessToken = FacebookApiHelper.GetPageAccessToken(fbUserId, accessToken, string.Empty); var response = FacebookApiHelper.PublishPostOnPage(pageAccessToken, fbUserId, message, imagePath, link); var isPublished = response.Contains("id"); if (isPublished) { var selectDayObject = JsonConvert.DeserializeObject <List <string> >(schmessage.weekdays); schmessage.scheduleTime = DateTimeHelper.GetNextScheduleDate(selectDayObject, schmessage.scheduleTime); if (schmessage.scheduleTime.Date == DateTime.Today) { schmessage.scheduleTime = schmessage.scheduleTime.AddDays(7); } dbr.Update(schmessage); var notify = new Notifications(); var notifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id); if (notifications == null) { notify.MsgId = schmessage.id; notify.MsgStatus = "Scheduled"; notify.notificationtime = schmessage.localscheduletime.ToString(); notify.NotificationType = "Schedule Successfully"; notify.ReadOrUnread = "Unread"; notify.UserId = userId; dbr.Add(notify); if (_user.scheduleSuccessUpdates) { var sucResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime.ToString(), true, AppSettings.sendGridUserName, AppSettings.sendGridPassword); } } } } catch (Exception ex) { apiHitsCount = MaxapiHitsCount; var notify = new Notifications(); var notifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id); if (notifications == null) { notify.MsgId = schmessage.id; notify.MsgStatus = "Failed"; notify.notificationtime = schmessage.localscheduletime.ToString(); notify.NotificationType = "Schedule Failed"; notify.ReadOrUnread = "Unread"; notify.UserId = userId; dbr.Add(notify); if (_user.scheduleFailureUpdates) { string falResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime.ToString(), false, AppSettings.sendGridUserName, AppSettings.sendGridPassword); } } } return(ret); }
public void ShareFeedonGroup(string fbAccesstoken, string FeedId, string pageId, string message, string fbgroupId, int time, string faceaccountId, double lastupdatetime, string Facebooknameid) { var lstPost = new List <string>(); var lstCout = 0; var feedid = FeedId.TrimEnd(',').Split(','); var grpid = Facebooknameid.TrimEnd(',').Split(','); var r = new Random(); var length = feedid.Length; var objSharethonGroupPost = new SharethonGroupPost(); var mongoRepository = new MongoRepository("SharethonGroupPost"); while (length >= lstCout) { var i = r.Next(0, length - 1); if (!lstPost.Contains(feedid[i])) { var postId = feedid[i]; lstPost.Add(feedid[i]); lstCout++; foreach (var item in grpid) { var groupData = Regex.Split(item, "<:>"); var postData = mongoRepository.Find <SharethonGroupPost>(t => t.Facebookgroupid.Equals(groupData[1]) && t.PostId.Equals(postId)); var task = Task.Run(async() => await postData); var count = task.Result.Count; var link = "https://www.facebook.com/" + pageId + "/posts/" + feedid[i]; try { if (count < 1) { // dynamic output = fb.Post("v2.7/" + grpdata[1] + "/feed", args); try { var response = FacebookApiHelper.PublishPostOnPage(fbAccesstoken, groupData[1], string.Empty, string.Empty, link); if (response.Contains("id")) { GroupapiHitsCount++; } } catch (Exception) { GroupapiHitsCount = GroupMaxapiHitsCount; } objSharethonGroupPost.Id = ObjectId.GenerateNewId(); objSharethonGroupPost.Facebookaccountid = faceaccountId; objSharethonGroupPost.Facebookgroupid = groupData[1]; objSharethonGroupPost.Facebookgroupname = groupData[0]; objSharethonGroupPost.PostId = feedid[i]; objSharethonGroupPost.PostedTime = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); mongoRepository.Add(objSharethonGroupPost); } } catch (Exception ex) { GroupapiHitsCount = GroupMaxapiHitsCount; Console.WriteLine(ex.Message); } } Thread.Sleep(1000 * 50); } Thread.Sleep(1000 * 60 * time); } }
public IActionResult AddFacebookPages(long userId, long groupId) { string data = Request.Form["profileaccesstoken"]; string[] accesstoken = data.Split(','); int addedPageCount = 0; int invalidaccessToken = 0; foreach (var item in accesstoken) { dynamic profile = Fbpages.GetFbPageData(item); FacebookApiHelper.MakeSubscribedWithApp(item); try { string x = Convert.ToString(profile); _logger.LogError(x); } catch { } if (Convert.ToString(profile) == "Invalid Access Token") { invalidaccessToken++; // return Ok("Invalid Access Token"); } else { DatabaseRepository dbr = new DatabaseRepository(_logger, _env); Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr); if (fbacc != null && fbacc.IsActive == true) { addedPageCount++; //return Ok("Facebook Page added by other user."); } else { Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault(); if (ngrp == null) { return(Ok("Wrong Group Id")); } // Adding Facebook Page int res = Api.Socioboard.Repositories.FacebookRepository.AddFacebookPage(profile, dbr, userId, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookPage, item, _redisCache, _appSettings, _logger); } } } if (addedPageCount == accesstoken.Length) { return(Ok("Facebook Pages added by other user.")); } else if (addedPageCount == accesstoken.Length) { return(Ok("Facebook Pages having Invalid Access Token.")); } else if (invalidaccessToken > 0 && addedPageCount > 0) { return(Ok("Pages added successfully and " + addedPageCount + " pages added by other user or " + invalidaccessToken + " pages having invalid access token issue")); } else if (invalidaccessToken > 0) { return(Ok("Pages added successfully" + invalidaccessToken + " pages having invalid access token issue")); } else if (addedPageCount > 0) { return(Ok("Pages added successfully and " + addedPageCount + " pages added by other user")); } return(Ok("Page added successfully")); }
public async Task <HttpResponseMessage> PostMessage(JObject Responce) { DateTime TimeToStartAnswer = DateTime.Now; FacebookResponce facebookeResponce = Responce.ToObject <FacebookResponce>(); if (facebookeResponce == null) { Logging.Logger.Error("Facebook. Empty request!"); return(new HttpResponseMessage(HttpStatusCode.OK)); } if (facebookeResponce.Object != ObjectTypes.page) { Logging.Logger.Error($"Facebook. It's not a text message!"); return(new HttpResponseMessage(HttpStatusCode.OK)); } else { var FacebookBot = new FacebookApiHelper(_token); var thisQuery = new BotUserQuery { IsError = 0 }; await FacebookBot.SendAction(facebookeResponce.entry[0].messaging[0].sender.Id, SenderActionType.typing_on, thisQuery); if (facebookeResponce.entry[0].messaging[0].message.text != null) // пришло тектовое сообщение { try { string trimmedLoweredQuery = facebookeResponce.entry[0].messaging[0].message.text.ToLower().Trim(QueryAnaliser.splitters); var mbFunctional = new MallBotFunctional(); var mbDBHelper = new MallBotDBHelper(); var mbApiFunctional = new MallBotFacebookApiFunctional(); // Кэширование #region string MainCachedItemKey = "MainDataOfBot"; string RadugaCachedItemKey = "RadugaDataOfBot"; MallBotModel MainDataOfBot = null; MallBotModel RadugaDataOfBot = null; var dbMainContext = new MallBotContext(); dbMainContext.Configuration.ProxyCreationEnabled = false; var dbRadugaContext = new MallBotContext(1); dbMainContext.Configuration.ProxyCreationEnabled = false; object MaindataFromCache = MemoryCache.Default.Get(MainCachedItemKey, null); object RadugadataFromCache = MemoryCache.Default.Get(RadugaCachedItemKey, null); if (trimmedLoweredQuery == "update") { if (MaindataFromCache != null) { MemoryCache.Default.Remove(MainCachedItemKey, null); } if (RadugadataFromCache != null) { MemoryCache.Default.Remove(RadugaCachedItemKey, null); } MaindataFromCache = null; RadugadataFromCache = null; } if (MaindataFromCache == null || RadugadataFromCache == null) { List <int?> ids = new List <int?> { 3, 5 }; MainDataOfBot = new MallBotModel(dbMainContext, ids); ids = new List <int?> { 1 }; RadugaDataOfBot = new MallBotModel(dbRadugaContext, ids); string[] TimeOfExpiration = ConfigurationManager.AppSettings["TimeOfExpiration"].ToString().Split(':'); CacheItemPolicy cip = new CacheItemPolicy() { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(int.Parse(TimeOfExpiration[0])).AddMinutes(int.Parse(TimeOfExpiration[1])).AddSeconds(int.Parse(TimeOfExpiration[2]))) }; MemoryCache.Default.Set(new CacheItem(MainCachedItemKey, (object)MainDataOfBot), cip); MemoryCache.Default.Set(new CacheItem(RadugaCachedItemKey, (object)RadugaDataOfBot), cip); } else { MainDataOfBot = (MallBotModel)MaindataFromCache; RadugaDataOfBot = (MallBotModel)RadugadataFromCache; } #endregion var botUsers = dbMainContext.BotUser.ToList(); var botUser = botUsers.FirstOrDefault(x => x.BotUserFacebookID == facebookeResponce.entry[0].messaging[0].sender.Id); QueryAnaliserResult answer = null; MallBotModel DataOfBot = null; var customers = MainDataOfBot.Customers; customers.AddRange(RadugaDataOfBot.Customers); var IsTutorial = true; // Блок для описания команд. Приоритет 1. Наивысший if ( #region botUser == null || trimmedLoweredQuery == "place" || trimmedLoweredQuery == "место" || trimmedLoweredQuery == "сменить тц" || trimmedLoweredQuery == "тц" || trimmedLoweredQuery == "mall" || botUser.CustomerName == "newuser" || trimmedLoweredQuery == "help" && (botUser.CustomerName == "newuser" || botUser.CustomerName == "empty") || trimmedLoweredQuery == "помощь" && (botUser.CustomerName == "newuser" || botUser.CustomerName == "empty") #endregion ) { string message = ""; switch (trimmedLoweredQuery) { case "help": case "помощь": message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%priorityhelp%").Text; if (botUser.Locale == "ru_RU") { message = message.Replace("%place%", "место"); } else { message = message.Replace("%place%", "place"); } await FacebookBot.SendMessage(facebookeResponce.entry[0].messaging[0].sender.Id, message, thisQuery); break; default: if (botUser == null) { FacebookUser facebookUser = await FacebookBot.GetUsersInformation(facebookeResponce.entry[0].messaging[0].sender.Id, thisQuery); byte gender = 0; if (facebookUser.gender == "male") { gender = 2; } else { gender = 1; } dbMainContext = mbDBHelper.AddBotUser(ulong.Parse(facebookeResponce.entry[0].messaging[0].sender.Id), 3, null, facebookUser.first_name, facebookUser.last_name, gender, null, facebookUser.locale, false, dbMainContext); string senderId = facebookeResponce.entry[0].messaging[0].sender.Id; botUser = dbMainContext.BotUser.FirstOrDefault(x => x.BotUserFacebookID == senderId); } message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselect%").Text; message = message.Replace("%mall1%", "1. " + customers[0].Name + " " + customers[0].City); message = message.Replace("%mall2%", "2. " + customers[1].Name + " " + customers[1].City); message = message.Replace("%mall3%", "3. " + customers[2].Name + " " + customers[2].City); string[] quickReplies = { customers[0].Name, customers[1].Name, customers[2].Name }; await FacebookBot.SendMessage(facebookeResponce.entry[0].messaging[0].sender.Id, message, thisQuery, quickReplies); botUser.CustomerName = "empty"; if (botUser.LevelTutorial != 4) { botUser.LevelTutorial = 0; } botUser.ModifiedDate = DateTime.Now; dbMainContext.SaveChanges(); break; } } else { if (botUser.CustomerName == "empty") { var qa = new QueryAnaliser(); var res = mbFunctional.SearchCustomer(qa.NormalizeQuery(facebookeResponce.entry[0].messaging[0].message.text), customers); if (res.Count != 0) { var findedCustomer = customers.FirstOrDefault(x => x.CustomerID == res[0].ID); var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselectsucces%").Text; message = message.Replace("%findedmall%", findedCustomer.Name + ", " + findedCustomer.City); if (botUser.Locale == "ru_RU") { message = message.Replace("%place%", "место"); } else { message = message.Replace("%place%", "place"); } await FacebookBot.SendMessage(facebookeResponce.entry[0].messaging[0].sender.Id, message, thisQuery); botUser.CustomerName = res[0].Name; dbMainContext.SaveChanges(); if (botUser.LevelTutorial != 4) { answer = await mbApiFunctional.doTutorial(botUser, facebookeResponce.entry[0].messaging[0].message.text, FacebookBot, facebookeResponce.entry[0].messaging[0].sender.Id, dbMainContext, MainDataOfBot, thisQuery); } } else { var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselectfail%").Text; message = message.Replace("%notfindedmall%", facebookeResponce.entry[0].messaging[0].message.text); await FacebookBot.SendMessage(facebookeResponce.entry[0].messaging[0].sender.Id, message, thisQuery); } } else { if (botUser.CustomerName == RadugaDataOfBot.Customers[0].Name) { DataOfBot = RadugaDataOfBot; DataOfBot.Texts = MainDataOfBot.Texts; } else { DataOfBot = mbDBHelper.SelectData(MainDataOfBot, botUser, customers); } if (trimmedLoweredQuery.Contains("testfunc")) // команды для разработчиков { await mbApiFunctional.doDebelopersCommands(trimmedLoweredQuery, DataOfBot, FacebookBot, facebookeResponce.entry[0].messaging[0].sender.Id, thisQuery); } else { // Блок для описания команд. Приоритет 0 // команды для пользователей await mbApiFunctional.doUsersCommands(trimmedLoweredQuery, DataOfBot, FacebookBot, facebookeResponce.entry[0].messaging[0].sender.Id, botUser, thisQuery, dbMainContext); } } } if (botUser != null) { if (DataOfBot == null) { mbDBHelper.AddBotQuery(botUser, ulong.Parse(facebookeResponce.entry[0].messaging[0].sender.Id.ToString()), 3, answer, facebookeResponce.entry[0].messaging[0].message.text, IsTutorial, TimeToStartAnswer, thisQuery); } else { mbDBHelper.AddBotQuery(botUser, ulong.Parse(facebookeResponce.entry[0].messaging[0].sender.Id.ToString()), 3, answer, facebookeResponce.entry[0].messaging[0].message.text, IsTutorial, TimeToStartAnswer, thisQuery); } } return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok"), }); } catch (Exception exc) { Logging.Logger.Error("Facebook" + exc); return(new HttpResponseMessage(HttpStatusCode.OK)); } } else { await FacebookBot.SendMessage(facebookeResponce.entry[0].messaging[0].sender.Id, "Sorry, but i didn't understand you \U0001F614", thisQuery); } } return(new HttpResponseMessage(HttpStatusCode.OK)); }
public int updateFacebookFeeds(Domain.Socioboard.Models.Facebookaccounts fbAcc) { apiHitsCount = 0; var databaseRepository = new DatabaseRepository(); if (fbAcc.LastUpdate.AddHours(1) <= DateTime.UtcNow) { if (fbAcc.IsAccessTokenActive) { var feeds = FacebookApiHelper.GetOwnFeedDetails(fbAcc.AccessToken); dynamic profile = FacebookApiHelper.GetUserDetails(fbAcc.AccessToken); apiHitsCount++; if (Convert.ToString(profile) != "Invalid Access Token") { fbAcc.Friends = FacebookApiHelper.GetFriendCounts(fbAcc.AccessToken); apiHitsCount++; try { fbAcc.EmailId = Convert.ToString(profile["email"]); } catch { fbAcc.EmailId = fbAcc.EmailId; } try { fbAcc.ProfileUrl = (Convert.ToString(profile["link"])); } catch { fbAcc.ProfileUrl = (Convert.ToString(profile["picture"]["data"]["url"])); } try { fbAcc.Gender = (Convert.ToString(profile["gender"])); } catch { fbAcc.Gender = fbAcc.Gender; } try { fbAcc.Bio = (Convert.ToString(profile["bio"])); } catch { fbAcc.Bio = fbAcc.Bio; } try { fbAcc.About = (Convert.ToString(profile["about"])); } catch { fbAcc.About = fbAcc.About; } try { fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch { fbAcc.CoverPic = fbAcc.CoverPic; } try { fbAcc.Birthday = (Convert.ToString(profile["birthday"])); } catch { fbAcc.Birthday = fbAcc.Birthday; } try { JArray arry = JArray.Parse(profile["education"]); if (arry.Count > 0) { fbAcc.College = Convert.ToString(arry[arry.Count - 1]["school"]["name"]); fbAcc.Education = Convert.ToString(arry[arry.Count - 1]["concentration"]["name"]); } } catch { fbAcc.College = fbAcc.College; fbAcc.Education = fbAcc.Education; } try { JArray arry = JArray.Parse(profile["work"]); if (arry.Count > 0) { fbAcc.WorkPosition = Convert.ToString(arry[0]["position"]["name"]); fbAcc.WorkCompany = Convert.ToString(arry[0]["employer"]["name"]); } } catch { fbAcc.WorkPosition = fbAcc.WorkPosition; fbAcc.WorkCompany = fbAcc.WorkCompany; } try { databaseRepository.Update(fbAcc); } catch { } if (apiHitsCount < MaxapiHitsCount && feeds != null && feeds["data"] != null) { apiHitsCount++; if (feeds["data"] != null) { Console.WriteLine(feeds["data"]); foreach (var result in feeds["data"]) { MongoFacebookFeed objFacebookFeed = new MongoFacebookFeed(); objFacebookFeed.Type = "fb_feed"; objFacebookFeed.ProfileId = fbAcc.FbUserId; objFacebookFeed.Id = MongoDB.Bson.ObjectId.GenerateNewId(); try { objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + result["from"]["id"] + "/picture?type=small"; } catch (Exception) { objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + fbAcc.FbUserId + "/picture?type=small"; } try { objFacebookFeed.FromName = result["from"]["name"].ToString(); } catch (Exception) { objFacebookFeed.FromName = fbAcc.FbUserName; } try { objFacebookFeed.FromId = result["from"]["id"].ToString(); } catch (Exception) { objFacebookFeed.FromId = fbAcc.FbUserId; } objFacebookFeed.FeedId = result["id"].ToString(); try { objFacebookFeed.FeedDateToshow = DateTime.Parse(result["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); objFacebookFeed.FeedDate = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(Convert.ToDateTime(objFacebookFeed.FeedDateToshow)).ToString(); objFacebookFeed.FeedDateToshow = Domain.Socioboard.Helpers.SBHelper.ConvertFromUnixTimestamp(Convert.ToDouble(objFacebookFeed.FeedDate)).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { } try { objFacebookFeed.FbComment = "http://graph.facebook.com/" + result["id"] + "/comments"; objFacebookFeed.FbLike = "http://graph.facebook.com/" + result["id"] + "/likes"; } catch (Exception) { } try { objFacebookFeed.Likecount = result["likes"]["summary"]["total_count"].ToString(); } catch (Exception ex) { } try { objFacebookFeed.Commentcount = result["comments"]["summary"]["total_count"].ToString(); } catch (Exception ex) { } try { objFacebookFeed.postType = result["type"].ToString(); } catch { objFacebookFeed.postType = "status"; } try { objFacebookFeed.postingFrom = result["application"]["name"].ToString(); } catch { objFacebookFeed.postingFrom = "Facebook"; } try { objFacebookFeed.Picture = result["picture"].ToString(); } catch (Exception ex) { objFacebookFeed.Picture = ""; } string message = string.Empty; try { if (result["message"] != null) { message = result["message"]; } } catch (Exception ex) { try { if (result["description"] != null) { message = result["description"]; } } catch (Exception exx) { try { if (result["story"] != null) { message = result["story"]; } } catch (Exception exxx) { message = string.Empty; } } } if (message == null) { message = ""; } dynamic comment; try { comment = result["comments"]; } catch (Exception) { comment = null; } objFacebookFeed.FeedDescription = message; objFacebookFeed.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); //objFacebookFeed._facebookComment = FbPostComments(objFacebookFeed.FeedId, fbAcc.AccessToken); objFacebookFeed._facebookComment = FbPostComments(objFacebookFeed.FeedId, comment); try { MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed"); var ret = mongorepo.Find <MongoFacebookFeed>(t => t.FeedId == objFacebookFeed.FeedId && t.ProfileId == objFacebookFeed.ProfileId); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { mongorepo.Add <MongoFacebookFeed>(objFacebookFeed); } else { try { FilterDefinition <BsonDocument> filter = new BsonDocument("FeedId", objFacebookFeed.FeedId); var update = Builders <BsonDocument> .Update.Set("postType", objFacebookFeed.postType).Set("postingFrom", objFacebookFeed.postingFrom).Set("Likecount", objFacebookFeed.Likecount).Set("Commentcount", objFacebookFeed.Commentcount).Set("_facebookComment", objFacebookFeed._facebookComment); mongorepo.Update <MongoFacebookFeed>(update, filter); } catch { } } } catch (Exception ex) { //_logger.LogInformation(ex.Message); //_logger.LogError(ex.StackTrace); } if (apiHitsCount < MaxapiHitsCount) { //AddFbPostComments(objFacebookFeed.FeedId, fbAcc.AccessToken); } } } else { apiHitsCount = MaxapiHitsCount; } try { feeds = Socioboard.Facebook.Data.FbUser.FbGet(fbAcc.AccessToken, feeds["paging"]["next"]); } catch { apiHitsCount = MaxapiHitsCount; } } fbAcc.LastUpdate = DateTime.UtcNow; databaseRepository.Update(fbAcc); } } } else { apiHitsCount = 0; } return(0); }
/// <summary> /// Добавление пользователя в базу /// </summary> /// <param name="type"></param> /// <param name="Bot"></param> /// <param name="recepientID"></param> /// <param name="first_name"></param> /// <param name="last_name"></param> /// <returns></returns> public MallBotContext AddBotUser(SocialNetworkType type, object Bot, string recepientID, string first_name = "", string last_name = "") { try { var btusr = new BotUser(); byte sex = 0; string bdate = ""; string locale = "ru_RU"; VK vk = null; FacebookApiHelper facebook = null; if (type == SocialNetworkType.VK) { //Запрашиваем данные о юзере в vk vk = (VK)Bot; var obj = AsyncHelper.RunSync(() => vk.GetUsersInformation(ulong.Parse(recepientID))); if (obj.ToString()[0] == '¡') { Logging.Logger.Error("VK. GetUsersInformation", obj.ToString()); } else { var VKuser = (VKResponceUser)obj; sex = VKuser.response[0].sex; first_name = VKuser.response[0].first_name; last_name = VKuser.response[0].last_name; bdate = VKuser.response[0].bdate; } btusr.BotUserVKID = recepientID; } if (type == SocialNetworkType.Telegram) { btusr.BotUserTelegramID = recepientID; } if (type == SocialNetworkType.Facebook) { facebook = (FacebookApiHelper)Bot; object obj = AsyncHelper.RunSync(() => facebook.GetUsersInformation(recepientID.ToString())); if (obj.ToString()[0] == '¡') { Logging.Logger.Error("Facebook. GetUsersInformation", obj.ToString()); } else { var facebookUser = (FacebookUser)obj; if (facebookUser.gender == "male") { sex = 2; } else { sex = 1; } first_name = facebookUser.first_name; last_name = facebookUser.last_name; if (facebookUser.locale != "ru_RU") { locale = "en_EN"; } } btusr.BotUserFacebookID = recepientID; } btusr.LevelTutorial = 0; if (sex != 0) { btusr.Male = sex.ToString(); } if (!string.IsNullOrWhiteSpace(first_name) || !string.IsNullOrWhiteSpace(last_name)) { btusr.Name = first_name + " " + last_name; } if (!string.IsNullOrWhiteSpace(bdate)) { string[] data = bdate.Split('.'); if (data.Count() == 3) { btusr.DateOfBirth = new DateTime(int.Parse(data[2]), int.Parse(data[1]), int.Parse(data[0])); } else if (data.Count() == 2) { btusr.DateOfBirth = new DateTime(2096, int.Parse(data[1]), int.Parse(data[0])); } } btusr.Locale = locale; btusr.IsTestMode = 0; btusr.NowIs = MallBotWhatIsHappeningNow.SettingCustomer; btusr.CustomerCompositeID = "newuser"; btusr.LastActivityDate = DateTime.Now; BotUser.Add(btusr); SaveChanges(); return(this); } catch (Exception exc) { Logging.Logger.Error(exc); return(this); } }
public async Task <HttpResponseMessage> PostMessage(JObject Responce) { try { DateTime TimeToStartAnswer = DateTime.Now; FacebookResponce facebookeResponce = Responce.ToObject <FacebookResponce>(); Logging.Logger.Debug($"Facebook PostMessage message={Responce}"); if (facebookeResponce == null) { Logging.Logger.Error("Facebook. Empty request!"); return(result); } if (facebookeResponce.Object != ObjectTypes.page) { Logging.Logger.Error($"Facebook. It's not a message!"); return(result); } //long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; //if (unixTimestamp - facebookTimestamp > long.Parse(ConfigurationManager.AppSettings["TimeToNotice"])) //{ // Logging.Logger.Debug($"Faceboooook !!!! An old message occurred {unixTimestamp} sub = {unixTimestamp - facebookTimestamp}"); // return result; //} // создание объекта - Бота var FacebookBot = new FacebookApiHelper(_token); // создание объекта для логирования запроса var thisRequest = new BotUserRequest(); // подключаем главную базу var dbContextes = new List <MallBotContext>(); dbContextes.Add(new MallBotContext($"A{ConfigurationManager.AppSettings["dbTest"]}")); // Находим пользователя var botUsers = dbContextes[0].BotUser.ToList(); var stringID = facebookeResponce.entry[0].messaging[0].sender.Id.ToString(); var botUser = botUsers.FirstOrDefault(x => x.BotUserFacebookID == stringID); if (botUser == null) { dbContextes[0] = dbContextes[0].AddBotUser(SocialNetworkType.Facebook, FacebookBot, stringID); botUser = dbContextes[0].BotUser.FirstOrDefault(x => x.BotUserFacebookID == stringID); botUser.IsNewUser = true; } else { if (botUser.NowIs == MallBotWhatIsHappeningNow.SettingCustomer && TimeHelper.GetMinutes((DateTime)botUser.LastActivityDate) > 240) { botUser.IsNewUser = true; } else { botUser.IsNewUser = false; } // если пользователь не завершил диалог с ботом и вернулся больше, чем через пол часа, то данные сбросятся к поиску организации. // кэш почистится в MainAnswerHelper if ((botUser.NowIs == MallBotWhatIsHappeningNow.SearchingWay || botUser.NowIs == MallBotWhatIsHappeningNow.GettingAllOrganizations) && TimeHelper.GetMinutes((DateTime)botUser.LastActivityDate) > 30) { botUser.NowIs = MallBotWhatIsHappeningNow.SearchingOrganization; } } //проверка на актуальность сообщения long facebookTimestamp = (long)facebookeResponce.entry[0].messaging[0].timestamp / 1000; if (ConfigurationManager.AppSettings["IgnoreOldEvents"] == "Enabled" && !TimeHelper.IsNewEvent((int)facebookTimestamp, botUser.BotUserID)) { return(result); } // помечаем сообщение как прочитанное. thisRequest.IsSendingError = await FacebookBot.SendAction(facebookeResponce.entry[0].messaging[0].sender.Id, SenderActionType.typing_on); //проверяем, что сообщение не пусто var trimmedLoweredQuery = ""; if (!string.IsNullOrWhiteSpace(facebookeResponce.entry[0].messaging[0].message?.text)) { trimmedLoweredQuery = facebookeResponce.entry[0].messaging[0].message.text.ToLower().Trim(AnalyseHelper.splitters); } else { if (facebookeResponce.entry[0].messaging[0].postback != null) { trimmedLoweredQuery = facebookeResponce.entry[0].messaging[0].postback.payload; facebookeResponce.entry[0].messaging[0].message = new FacebookMessage { text = trimmedLoweredQuery }; } } if (string.IsNullOrWhiteSpace(trimmedLoweredQuery) || (facebookeResponce.entry[0].messaging[0].message?.attachments != null && facebookeResponce.entry[0].messaging[0].message?.attachments[0].type != AttachmentType.location)) //что-то непонятное пришло { var simpleAnaliser = new AnalyseHelper(); thisRequest.IsSendingError = await simpleAnaliser.AnalyseBadRequest(botUser, SocialNetworkType.Facebook, FacebookBot, dbContextes[0].BotText.ToList()); dbContextes[0].AddBotQuery(botUser, null, TimeToStartAnswer, thisRequest); return(result); } var analyser = new MainAnswerHelper(thisRequest, FacebookBot, SocialNetworkType.Facebook, botUser, dbContextes); FindedInformation answer; // если была прислана геолокация, то ищем по ней. Иначе по тексту if (facebookeResponce.entry[0].messaging[0].message?.attachments != null && facebookeResponce.entry[0].messaging[0].message?.attachments[0].type == AttachmentType.location) { botUser.InputDataType = InputDataType.GeoLocation; botUser.NowIs = MallBotWhatIsHappeningNow.SettingCustomer; var temp = $"POINT({facebookeResponce.entry[0].messaging[0].message.attachments[0].payload.coordinates.Long} {facebookeResponce.entry[0].messaging[0].message.attachments[0].payload.coordinates.lat})"; temp = temp.Replace(',', '.'); thisRequest.Text = temp; answer = await analyser.Main(DbGeography.FromText(temp)); } else { botUser.InputDataType = InputDataType.Text; thisRequest.Text = facebookeResponce.entry[0].messaging[0].message.text; answer = await analyser.Main(trimmedLoweredQuery); } //сохраняем полезные данные по юзеру botUser.LastActivityDate = DateTime.Now; dbContextes[0].SaveChanges(); //пишем в базу запрос dbContextes[0].AddBotQuery(botUser, answer, TimeToStartAnswer, thisRequest); return(result); } catch (Exception ex) { Logging.Logger.Error(ex, "Facebook"); return(result); } }