diff --git a/src/Api.Socioboard/Controllers/FacebookController.cs b/src/Api.Socioboard/Controllers/FacebookController.cs index ac7647ab0..21bdf0d3b 100644 --- a/src/Api.Socioboard/Controllers/FacebookController.cs +++ b/src/Api.Socioboard/Controllers/FacebookController.cs @@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Cors; using Domain.Socioboard.Models.Mongo; using MongoDB.Bson; +using Newtonsoft.Json.Linq; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 @@ -52,7 +53,7 @@ public IActionResult AddFacebookAccount(string accessToken, long groupId, long u dynamic profile = FbUser.getFbUser(accessToken); try { - string x = Convert.ToString(profile); + string x = Convert.ToString(profile); _logger.LogError(x); } catch { } @@ -63,7 +64,7 @@ public IActionResult AddFacebookAccount(string accessToken, long groupId, long u DatabaseRepository dbr = new DatabaseRepository(_logger, _env); Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr); List grpProfiles = Api.Socioboard.Repositories.GroupProfilesRepository.getAllGroupProfiles(groupId, _redisCache, dbr); - + //if (grpProfiles.First().profileId == fbacc.FbUserId) @@ -118,7 +119,7 @@ public IActionResult ReconnectFbAccount(string accessToken, long groupId, long u Domain.Socioboard.Models.Facebookaccounts fbaccw = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr); //fbacc = fbacc.Where(t => t.FbUserId.Contains("127471161024815")).ToList(); - try + try { if (fbacc.FbUserId == profileId) { @@ -134,11 +135,11 @@ public IActionResult ReconnectFbAccount(string accessToken, long groupId, long u int res = Api.Socioboard.Repositories.FacebookRepository.ReFacebookAccount(profile, FbUser.getFbFriends(accessToken), dbr, userId, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookProfile, accessToken, reconnect, _redisCache, _appSettings, _logger); if (res == 1) { - + MongoRepository repofb = new MongoRepository("FacebookPasswordChangeUserDetail", _appSettings); try { - var result = repofb.Find(t => t.profileId == fbacc.FbUserId ); + var result = repofb.Find(t => t.profileId == fbacc.FbUserId); var task = Task.Run(async () => { return await result; @@ -146,9 +147,9 @@ public IActionResult ReconnectFbAccount(string accessToken, long groupId, long u int count = task.Result.Count; IList lstFbFeeds = task.Result; - if(count>0) + if (count > 0) { - FilterDefinition filter = new BsonDocument("profileId", lstFbFeeds.FirstOrDefault().profileId); + FilterDefinition filter = new BsonDocument("profileId", lstFbFeeds.FirstOrDefault().profileId); var update = Builders.Update.Set("status", true); repofb.Update(update, filter); @@ -180,8 +181,8 @@ public IActionResult ReconnectFbAccount(string accessToken, long groupId, long u { return Ok("Oops! login information is wrong , login the profile which has to be reconnected"); } - - + + return Ok(); @@ -316,7 +317,7 @@ public IActionResult GetTopFeeds(string profileId, long userId, int skip, int co List lstfacebookfeed = new List(); MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed", _appSettings); var builder = Builders.Sort; - var sort = builder.Descending(t => t.EntryDate); + var sort = builder.Descending(t => t.EntryDate); var result = mongorepo.FindWithRange(t => t.ProfileId.Equals(profileId), sort, skip, count); var task = Task.Run(async () => { @@ -348,32 +349,32 @@ public IActionResult GetTopFeeds(string profileId, long userId, int skip, int co } [HttpGet("GetLatestFeeds")] - public IActionResult GetLatestFeeds(string profileId, long userId, int skip, int count,string date) + public IActionResult GetLatestFeeds(string profileId, long userId, int skip, int count, string date) { - DateTime lastfeeddate =Convert.ToDateTime(date); - DateTime currentdate = DateTime.UtcNow; - //Int32 unixTimestamp= Convert.ToInt32(date); - List lstfacebookfeed = new List(); - MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed", _appSettings); - var builder = Builders.Sort; - var sort = builder.Descending(t => t.EntryDate); - var result = mongorepo.FindWithRange(t => t.ProfileId.Equals(profileId), sort, skip, count); - var task = Task.Run(async () => - { - return await result; - }); - IList lstFbFeeds = task.Result; - List lstlatestfeed = new List(); - lstlatestfeed = lstFbFeeds.Select(x => new LatestFacebookFeed() { EntryDate = Convert.ToDateTime(x.EntryDate), FeedDescription = x.FeedDescription, FeedDate=x.FeedDate, ProfileId=x.ProfileId, FromId=x.FromId, FromName=x.FromName, FromProfileUrl=x.FromProfileUrl, Type=x.Type, FbComment=x.FbComment, FbLike=x.FbLike, FeedId=x.FeedId, ReadStatus=x.ReadStatus, Picture=x.Picture, Positive=x.Positive, Negative=x.Negative, Commentcount=x.Commentcount, Likecount=x.Likecount, postType=x.postType, postingFrom=x.postingFrom, _facebookComment=x._facebookComment }).ToList(); - lstlatestfeed=lstlatestfeed.FindAll(t => t.EntryDate > lastfeeddate && t.EntryDate <= currentdate).ToList(); - return Ok(lstlatestfeed.ToList()); - + DateTime lastfeeddate = Convert.ToDateTime(date); + DateTime currentdate = DateTime.UtcNow; + //Int32 unixTimestamp= Convert.ToInt32(date); + List lstfacebookfeed = new List(); + MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed", _appSettings); + var builder = Builders.Sort; + var sort = builder.Descending(t => t.EntryDate); + var result = mongorepo.FindWithRange(t => t.ProfileId.Equals(profileId), sort, skip, count); + var task = Task.Run(async () => + { + return await result; + }); + IList lstFbFeeds = task.Result; + List lstlatestfeed = new List(); + lstlatestfeed = lstFbFeeds.Select(x => new LatestFacebookFeed() { EntryDate = Convert.ToDateTime(x.EntryDate), FeedDescription = x.FeedDescription, FeedDate = x.FeedDate, ProfileId = x.ProfileId, FromId = x.FromId, FromName = x.FromName, FromProfileUrl = x.FromProfileUrl, Type = x.Type, FbComment = x.FbComment, FbLike = x.FbLike, FeedId = x.FeedId, ReadStatus = x.ReadStatus, Picture = x.Picture, Positive = x.Positive, Negative = x.Negative, Commentcount = x.Commentcount, Likecount = x.Likecount, postType = x.postType, postingFrom = x.postingFrom, _facebookComment = x._facebookComment }).ToList(); + lstlatestfeed = lstlatestfeed.FindAll(t => t.EntryDate > lastfeeddate && t.EntryDate <= currentdate).ToList(); + return Ok(lstlatestfeed.ToList()); + } [HttpGet("GetTopFilterFeeds")] public IActionResult GetTopFilterFeeds(string profileId, long userId, int skip, int count, string typeFilter) { - return Ok(Repositories.FacebookRepository.GetTopFacebookFilterFeed(profileId, userId, _redisCache, _appSettings, skip, count, typeFilter)); + return Ok(Repositories.FacebookRepository.GetTopFacebookFilterFeed(profileId, userId, _redisCache, _appSettings, skip, count, typeFilter)); } @@ -501,8 +502,8 @@ public IActionResult AddFacebookPages(long userId, long groupId) int invalidaccessToken = 0; foreach (var item in accesstoken) { - dynamic profile = Fbpages.getFbPageData(item); - string subscribed_apps = Fbpages.subscribed_apps(item, Convert.ToString(profile["id"])); + dynamic profile = Fbpages.GetFbPageData(item); + FacebookApiHelper.MakeSubscribedWithApp(item); try { string x = Convert.ToString(profile); @@ -514,10 +515,10 @@ public IActionResult AddFacebookPages(long userId, long groupId) invalidaccessToken++; // return Ok("Invalid Access Token"); } - else + else { DatabaseRepository dbr = new DatabaseRepository(_logger, _env); - Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr); + Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr); if (fbacc != null && fbacc.IsActive == true) { addedPageCount++; @@ -533,18 +534,18 @@ public IActionResult AddFacebookPages(long userId, long groupId) // 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) + else if (addedPageCount == accesstoken.Length) { return Ok("Facebook Pages having Invalid Access Token."); } - else if (invalidaccessToken > 0 && addedPageCount>0) + 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"); } @@ -591,7 +592,7 @@ public IActionResult ReconnFacebookPages(long userId, long groupId, string acces int invalidaccessToken = 0; - dynamic profile = Fbpages.getFbPageData(accessToken); + dynamic profile = Fbpages.GetFbPageData(accessToken); string subscribed_apps = Fbpages.subscribed_apps(accessToken, Convert.ToString(profile["id"])); try { @@ -607,8 +608,8 @@ public IActionResult ReconnFacebookPages(long userId, long groupId, string acces { DatabaseRepository dbr = new DatabaseRepository(_logger, _env); Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr); - - int isSaved = 0; + + int isSaved = 0; if (fbacc != null) { fbacc.IsActive = true; @@ -624,7 +625,7 @@ public IActionResult ReconnFacebookPages(long userId, long groupId, string acces } try { - fbacc.coverPic = (Convert.ToString(profile["cover"]["source"])); + fbacc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch (Exception) { @@ -632,7 +633,7 @@ public IActionResult ReconnFacebookPages(long userId, long groupId, string acces } fbacc.AccessToken = accessToken; isSaved = dbr.Update(fbacc); - if (isSaved>0) + if (isSaved > 0) { return Ok("Page Reconnected Successfully"); } @@ -653,7 +654,7 @@ public IActionResult GetFacebookPostComment(string postId) } [HttpPost("PostFacebookComment")] - public IActionResult PostFacebookComment(string postId, string profileId, string message,string timezoneOffset) + public IActionResult PostFacebookComment(string postId, string profileId, string message, string timezoneOffset) { DatabaseRepository dbr = new DatabaseRepository(_logger, _env); string postcomment = Repositories.FacebookRepository.PostFacebookComment(dbr, message, profileId, postId, timezoneOffset, _redisCache, _appSettings, _logger); diff --git a/src/Api.Socioboard/Controllers/GoogleController.cs b/src/Api.Socioboard/Controllers/GoogleController.cs index fb1d6b564..6452ad318 100644 --- a/src/Api.Socioboard/Controllers/GoogleController.cs +++ b/src/Api.Socioboard/Controllers/GoogleController.cs @@ -50,7 +50,8 @@ public GoogleController(ILogger logger, IEmailSender emailSender /// /// /// - /// + /// [HttpPost("GoogleLogin")] public IActionResult GoogleLogin(string code,Domain.Socioboard.Enum.SBAccountType accType) { @@ -251,19 +252,19 @@ public IActionResult GoogleLogin(string code,Domain.Socioboard.Enum.SBAccountTyp catch { } user.RegistrationType = Domain.Socioboard.Enum.SBRegistrationType.Google; - int SavedStatus = dbr.Add(user); + var savedStatus = dbr.Add(user); User nuser = dbr.Single(t => t.EmailId.Equals(user.EmailId)); - if (SavedStatus == 1 && nuser != null) + if (savedStatus == 1 && nuser != null) { Groups group = new Groups(); group.adminId = nuser.Id; group.createdDate = DateTime.UtcNow; group.groupName = Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName; - SavedStatus = dbr.Add(group); - if (SavedStatus == 1) + savedStatus = dbr.Add(group); + if (savedStatus == 1) { Groups ngrp = dbr.Find(t => t.adminId == nuser.Id && t.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName)).FirstOrDefault(); - GroupMembersRepository.createGroupMember(ngrp.id, nuser, _redisCache, dbr); + GroupMembersRepository.CreateGroupMember(ngrp.id, nuser, _redisCache, dbr); // Adding GPlus Profile Api.Socioboard.Repositories.GplusRepository.AddGplusAccount(userinfo, dbr, nuser.Id, ngrp.id, access_token, refreshToken, _redisCache, _appSettings, _logger); } @@ -276,6 +277,13 @@ public IActionResult GoogleLogin(string code,Domain.Socioboard.Enum.SBAccountTyp } + /// + /// + /// + /// + /// + /// + /// [HttpPost("EnableDisableGoogleSignIn")] public IActionResult EnableDisableGoogleSignIn(long userId,string GplusId, bool checkEnable) { @@ -350,6 +358,13 @@ public IActionResult GetGplusProfilesOnly(long groupId) return Ok(lstGplusAcc); } + /// + /// + /// + /// + /// + /// Pass a enum of + /// [HttpPost("GoogleLoginPhone")] public IActionResult GoogleLoginPhone(string refreshToken,string accessToken, Domain.Socioboard.Enum.SBAccountType accType) { @@ -493,7 +508,7 @@ public IActionResult GoogleLoginPhone(string refreshToken,string accessToken, Do if (SavedStatus == 1) { Groups ngrp = dbr.Find(t => t.adminId == nuser.Id && t.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName)).FirstOrDefault(); - GroupMembersRepository.createGroupMember(ngrp.id, nuser, _redisCache, dbr); + GroupMembersRepository.CreateGroupMember(ngrp.id, nuser, _redisCache, dbr); // Adding GPlus Profile Api.Socioboard.Repositories.GplusRepository.AddGplusAccount(userinfo, dbr, nuser.Id, ngrp.id, accessToken, refreshToken, _redisCache, _appSettings, _logger); } diff --git a/src/Api.Socioboard/Controllers/GroupsController.cs b/src/Api.Socioboard/Controllers/GroupsController.cs index c8db0240c..a7a74f194 100644 --- a/src/Api.Socioboard/Controllers/GroupsController.cs +++ b/src/Api.Socioboard/Controllers/GroupsController.cs @@ -54,7 +54,7 @@ public IActionResult CreateGroup(Domain.Socioboard.Models.Groups group) { Domain.Socioboard.Models.User user = dbr.FindSingle(t => t.Id == group.adminId); long GroupId = dbr.FindSingle(t => t.adminId == group.adminId && t.groupName.Equals(group.groupName)).id; - GroupMembersRepository.createGroupMember(GroupId, user, _redisCache, dbr); + GroupMembersRepository.CreateGroupMember(GroupId, user, _redisCache, dbr); _redisCache.Delete(Domain.Socioboard.Consatants.SocioboardConsts.CacheUserGroups + group.adminId); return Ok("Team Added Successfully "); } diff --git a/src/Api.Socioboard/Controllers/InstagramController.cs b/src/Api.Socioboard/Controllers/InstagramController.cs index 8e1a1fb6d..7d0edd8dc 100644 --- a/src/Api.Socioboard/Controllers/InstagramController.cs +++ b/src/Api.Socioboard/Controllers/InstagramController.cs @@ -262,49 +262,49 @@ public IActionResult GetInstaAccSingle(string accId) // DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); // List alldata = new List(); // List lstGrpProfiles = Repositories.GroupProfilesRepository.getAllGroupProfiles(groupId, _redisCache, dbr); - // List lstTwtMessages = new List(); - // List TwtMessages = new List(); + // List lstTwtMessages = new List(); + // List TwtMessages = new List(); // foreach (var item in lstGrpProfiles.Where(t => t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)) // { - // MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - // var builder = Builders.Sort; + // MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + // var builder = Builders.Sort; // var sort = builder.Descending(t => t.messageDate); - // var result = mongorepo.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterUsertweet), sort, skip, count); + // var result = mongorepo.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterMention || t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.MessageType.TwitterFollower || t.type == Domain.Socioboard.Enum.MessageType.TwitterUsertweet), sort, skip, count); // var task = Task.Run(async () => // { // return await result; // }); - // IList lstTwitterTweets = task.Result; - // TwtMessages = lstTwitterTweets.Where(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterUsertweet).ToList(); + // IList lstTwitterTweets = task.Result; + // TwtMessages = lstTwitterTweets.Where(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterUsertweet).ToList(); // if (lstTwitterTweets != null) // { // lstTwtMessages.AddRange(lstTwitterTweets); // } // var d = lstTwitterTweets.Count; // } - // int posttext = TwtMessages.FindAll(t => t.twitterMsg!= null && t.mediaUrl== null && !t.twitterMsg.Contains("http") || !t.twitterMsg.Contains("https") || !t.twitterMsg.Contains("www.") || !t.twitterMsg.Contains("http://") || !t.twitterMsg.Contains("https://") || !t.twitterMsg.Contains("www.")).Count; + // int posttext = TwtMessages.FindAll(t => t.Message!= null && t.mediaUrl== null && !t.Message.Contains("http") || !t.Message.Contains("https") || !t.Message.Contains("www.") || !t.Message.Contains("http://") || !t.Message.Contains("https://") || !t.Message.Contains("www.")).Count; // int mediapost = TwtMessages.FindAll(t => t.mediaUrl != null).Count; - // int linkpost= TwtMessages.FindAll(t => t.twitterMsg.Contains("http") || t.twitterMsg.Contains("https") || t.twitterMsg.Contains("www.") || t.twitterMsg.Contains("http://") || t.twitterMsg.Contains("https://") || t.twitterMsg.Contains("www.")).Count; - // int mentions = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention).Count; - // int retweet = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet).Count; + // int linkpost= TwtMessages.FindAll(t => t.Message.Contains("http") || t.Message.Contains("https") || t.Message.Contains("www.") || t.Message.Contains("http://") || t.Message.Contains("https://") || t.Message.Contains("www.")).Count; + // int mentions = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterMention).Count; + // int retweet = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet).Count; - //// || t.twitterMsg.Contains("https") || t.twitterMsg.Contains("www.") || t.twitterMsg.Contains("http://") || t.twitterMsg.Contains("https://") || t.twitterMsg.Contains("www.") + //// || t.Message.Contains("https") || t.Message.Contains("www.") || t.Message.Contains("http://") || t.Message.Contains("https://") || t.Message.Contains("www.") // alldata.Add(mentions); // alldata.Add(retweet); - // List lstTwtMessagess = new List(); + // List lstTwtMessagess = new List(); // foreach (var item in lstGrpProfiles.Where(t => t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)) // { - // MongoRepository mongorepoDm = new MongoRepository("MongoTwitterDirectMessages", _appSettings); + // MongoRepository mongorepoDm = new MongoRepository("MongoDirectMessages", _appSettings); - // var builder = Builders.Sort; + // var builder = Builders.Sort; // var sort = builder.Descending(t => t.entryDate); - // var result = mongorepoDm.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent), sort, skip, count); + // var result = mongorepoDm.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived || t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent), sort, skip, count); // var task = Task.Run(async () => // { // return await result; // }); - // IList lstTwitterdm = task.Result; + // IList lstTwitterdm = task.Result; // if (lstTwitterdm != null) // { // lstTwtMessagess.AddRange(lstTwitterdm); @@ -312,8 +312,8 @@ public IActionResult GetInstaAccSingle(string accId) // } - // int dmrecived = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived).Count; - // int dmsend = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent).Count; + // int dmrecived = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived).Count; + // int dmsend = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent).Count; // alldata.Add(dmrecived); // alldata.Add(dmsend); // alldata.Add(posttext); diff --git a/src/Api.Socioboard/Controllers/PaymentTransactionController.cs b/src/Api.Socioboard/Controllers/PaymentTransactionController.cs index 860dd33b0..cae2a502b 100644 --- a/src/Api.Socioboard/Controllers/PaymentTransactionController.cs +++ b/src/Api.Socioboard/Controllers/PaymentTransactionController.cs @@ -449,6 +449,89 @@ public IActionResult GetBlueSnapPlan(string planId) return Ok(responseFromServer); } - + /// + /// Get bluesnap subscription ipn + /// + /// + /// + [HttpPost("GetBlueSnapSubscription")] + public IActionResult GetBlueSnapSubscription(string subscriptionId) + { + string responseFromServer = string.Empty; + try + { + // Create a request using a URL that can receive a post. + HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://sandbox.bluesnap.com/services/2/recurring/subscriptions/" + subscriptionId); + // Set the Method property of the request to POST. + request.Method = "GET"; + request.Headers["Authorization"] = "Basic " + _appSettings.bluesnapBase64; + request.UserAgent = ".NET Framework Test Client"; + request.ContentType = "application/json"; + ServicePointManager.Expect100Continue = true; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + + // Get the response. + HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse(); + Console.WriteLine((myHttpWebResponse.StatusDescription)); + Stream dataStream = myHttpWebResponse.GetResponseStream(); + StreamReader reader = new StreamReader(dataStream); + responseFromServer = reader.ReadToEnd(); + Console.WriteLine(responseFromServer); + reader.Close(); + dataStream.Close(); + myHttpWebResponse.Close(); + } + catch (WebException wex) + { + var pageContent = new StreamReader(wex.Response.GetResponseStream()) + .ReadToEnd(); + + Console.WriteLine(wex.Message); + } + + + Dictionary planValues = new Dictionary(); + //XML + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(responseFromServer); + + + + try + { + string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); + + JObject responseJson = JObject.Parse(jsonText); + + + string temp = responseJson["recurring-subscription"]["plan-id"].ToString(); + + DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); + + try + { + PaymentTransaction objPaymentTransaction = dbr.Single(t => t.trasactionId == subscriptionId); + if (objPaymentTransaction.paymentdate.Date != DateTime.Now.Date && objPaymentTransaction != null) + { + objPaymentTransaction.amount = responseJson["recurring-subscription"]["recurring-charge-amount"].ToString(); + objPaymentTransaction.paymentdate = DateTime.UtcNow; + objPaymentTransaction.bluesnapSubscriptions++; + dbr.Update(objPaymentTransaction); + } + } + catch + { + + } + } + catch + { + + } + + return Ok(); + } + + } } diff --git a/src/Api.Socioboard/Controllers/SocialMessagesController.cs b/src/Api.Socioboard/Controllers/SocialMessagesController.cs index 6935330b6..4cc677ea2 100644 --- a/src/Api.Socioboard/Controllers/SocialMessagesController.cs +++ b/src/Api.Socioboard/Controllers/SocialMessagesController.cs @@ -22,6 +22,8 @@ using Imgur.API.Authentication.Impl; using Imgur.API.Endpoints.Impl; using Imgur.API.Models; +using Newtonsoft.Json; +using Socioboard.Facebook.Data; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 @@ -62,7 +64,7 @@ public async Task ComposeMessage(string message, string profileId var uploads = string.Empty; string imgPath = string.Empty; string temp = string.Empty; - string tempmsg = message.Replace("
",""); + string tempmsg = message.Replace("
", ""); if (shortnerStatus == Domain.Socioboard.Enum.UrlShortener.bitlyUri) { temp = Utility.GetConvertedUrls(ref tempmsg, shortnerStatus); @@ -119,12 +121,12 @@ public async Task ComposeMessage(string message, string profileId //string[] updatedmessgae = Regex.Split(message, "
"); //message = postmessage; - DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); + + var dbr = new DatabaseRepository(_logger, _appEnv); string[] lstProfileIds = null; if (profileId != null) { lstProfileIds = profileId.Split(','); - profileId = lstProfileIds[0]; } else { @@ -133,26 +135,29 @@ public async Task ComposeMessage(string message, string profileId foreach (var item in lstProfileIds) { - string temp_item_profileId = ""; - string temp_item_profileName = ""; - string[] profileSingle = new string[2]; + var tempItemProfileId = string.Empty; + var tempItemProfileName = string.Empty; + if (item.Contains("`")) { - profileSingle = item.Split('`'); - temp_item_profileId = profileSingle[0]; - temp_item_profileName = profileSingle[1]; + var profileSingle = item.Split('`'); + tempItemProfileId = profileSingle[0]; + tempItemProfileName = profileSingle[1]; } else { - temp_item_profileId = item; + tempItemProfileId = item; } - string updatedtext = ""; - string postmessage = ""; - string url = ""; + + var updatedText = string.Empty; + var postmessage = string.Empty; + var url = string.Empty; + if (!string.IsNullOrEmpty(tempmsg)) { - string[] updatedmessgae = Regex.Split(tempmsg, "
"); - foreach (var items in updatedmessgae) + var updatedMessgae = Regex.Split(tempmsg, "
"); + + foreach (var items in updatedMessgae) { if (!string.IsNullOrEmpty(items)) { @@ -163,11 +168,11 @@ public async Task ComposeMessage(string message, string profileId url = items; if (items.Contains("https://")) { - string links = Utility.getBetween(url + "###", "https", "###"); + var links = Utility.getBetween(url + "###", "https", "###"); links = "https" + links; try { - url = links.Split(' ')[0].ToString(); + url = links.Split(' ')[0]; link = url; } catch (Exception) @@ -220,12 +225,12 @@ public async Task ComposeMessage(string message, string profileId { // link = url; //updatedtext = postmessage.Replace(url, ""); - updatedtext = postmessage; + updatedText = postmessage; } else { - updatedtext = postmessage; + updatedText = postmessage; } @@ -235,15 +240,15 @@ public async Task ComposeMessage(string message, string profileId } - if (temp_item_profileId.StartsWith("fb")) - { + if (tempItemProfileId.StartsWith("fb")) + { try { new Thread(delegate () { - string prId = temp_item_profileId.Substring(3, temp_item_profileId.Length - 3); + string prId = tempItemProfileId.Substring(3, tempItemProfileId.Length - 3); Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); - string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedtext, prId, userId, uploads, link, mediaType, objFacebookAccount.FbUserName, dbr, _logger); + string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedText, prId, userId, uploads, link, mediaType, objFacebookAccount.FbUserName, dbr, _logger); }).Start(); } @@ -252,17 +257,43 @@ public async Task ComposeMessage(string message, string profileId } } - else if (temp_item_profileId.StartsWith("page")) + else if (tempItemProfileId.StartsWith("page")) { try { - new Thread(delegate () + await Task.Factory.StartNew(() => { - string prId = temp_item_profileId.Substring(5, temp_item_profileId.Length - 5); - Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); - string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedtext, prId, userId, uploads, link, mediaType, objFacebookAccount.FbUserName, dbr, _logger); + try + { + var pageId = item.Replace("page_", string.Empty); - }).Start(); + var accountDetails = FacebookRepository.getFacebookAccount(pageId, _redisCache, dbr); + + var pageAccessToken = + FacebookApiHelper.GetPageAccessToken(pageId, accountDetails.AccessToken, string.Empty); + + var response = FacebookApiHelper.PublishPost(accountDetails.FbProfileType, pageAccessToken, accountDetails.FbUserId, updatedText, pageId, uploads, link); + + FacebookHelper.UpdatePublishedDetails(accountDetails.FbProfileType, accountDetails.FbUserId, + updatedText, pageId, userId, uploads, mediaType, accountDetails.FbUserName, dbr); + + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + _logger.LogError(ex.StackTrace); + } + + }); + + #region Old Methods + //new Thread(delegate () + // { + // string prId = temp_item_profileId.Substring(5, temp_item_profileId.Length - 5); + // Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); + // string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedtext, prId, userId, uploads, link, mediaType, objFacebookAccount.FbUserName, dbr, _logger); + // }).Start(); + #endregion } catch (Exception ex) { @@ -272,15 +303,15 @@ public async Task ComposeMessage(string message, string profileId - else if (temp_item_profileId.StartsWith("urlfb")) + else if (tempItemProfileId.StartsWith("urlfb")) { try { new Thread(delegate () { - string prId = temp_item_profileId.Substring(6, temp_item_profileId.Length - 6); + string prId = tempItemProfileId.Substring(6, tempItemProfileId.Length - 6); Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); - string ret = Helper.FacebookHelper.UrlComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedtext, prId, userId, uploads, link, mediaType, objFacebookAccount.FbUserName, dbr, _logger); + string ret = Helper.FacebookHelper.UrlComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedText, prId, userId, uploads, link, mediaType, objFacebookAccount.FbUserName, dbr, _logger); }).Start(); } @@ -292,15 +323,15 @@ public async Task ComposeMessage(string message, string profileId - else if (temp_item_profileId.StartsWith("tw")) + else if (tempItemProfileId.StartsWith("tw")) { try { new Thread(delegate () { - string prId = temp_item_profileId.Substring(3, temp_item_profileId.Length - 3); - string ret = Helper.TwitterHelper.PostTwitterMessage(_appSettings, _redisCache, tempmsg, prId, userId, uploads, true, mediaType, temp_item_profileName, dbr, _logger); + string prId = tempItemProfileId.Substring(3, tempItemProfileId.Length - 3); + string ret = Helper.TwitterHelper.PostTwitterMessage(_appSettings, _redisCache, tempmsg, prId, userId, uploads, true, mediaType, tempItemProfileName, dbr, _logger); }).Start(); } @@ -309,15 +340,15 @@ public async Task ComposeMessage(string message, string profileId } } - - else if (temp_item_profileId.StartsWith("lin")) + + else if (tempItemProfileId.StartsWith("lin")) { try { new Thread(delegate () { - string prId = temp_item_profileId.Substring(4, temp_item_profileId.Length - 4); - string ret = Helper.LinkedInHelper.PostLinkedInMessage(uploads, userId, tempmsg, prId, imgPath, mediaType, temp_item_profileName, _redisCache, _appSettings, dbr); + string prId = tempItemProfileId.Substring(4, tempItemProfileId.Length - 4); + string ret = Helper.LinkedInHelper.PostLinkedInMessage(uploads, userId, tempmsg, prId, imgPath, mediaType, tempItemProfileName, _redisCache, _appSettings, dbr); }).Start(); } @@ -327,15 +358,15 @@ public async Task ComposeMessage(string message, string profileId } } - - else if (temp_item_profileId.StartsWith("Cmpylinpage")) + + else if (tempItemProfileId.StartsWith("Cmpylinpage")) { try { new Thread(delegate () { - string prId = temp_item_profileId.Substring(12, temp_item_profileId.Length - 12); - string ret = Helper.LinkedInHelper.PostLinkedInCompanyPagePost(uploads, imgPath, userId, tempmsg, prId, mediaType, temp_item_profileName, _redisCache, dbr, _appSettings); + string prId = tempItemProfileId.Substring(12, tempItemProfileId.Length - 12); + string ret = Helper.LinkedInHelper.PostLinkedInCompanyPagePost(uploads, imgPath, userId, tempmsg, prId, mediaType, tempItemProfileName, _redisCache, dbr, _appSettings); }).Start(); } @@ -344,7 +375,7 @@ public async Task ComposeMessage(string message, string profileId } } - + } return Ok("Posted"); @@ -544,7 +575,7 @@ public async Task ScheduleMessage(string message, string profileId link = linkurl; string prId = item.Substring(8, item.Length - 8); Domain.Socioboard.Models.Facebookaccounts objFacebookaccounts = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr); - Helper.ScheduleMessageHelper.ScheduleMessage(prId, objFacebookaccounts.FbUserName,link, Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage, userId, link, filename, "https://graph.facebook.com/" + prId + "/picture?type=small", scheduledatetime, localscheduletime, mediaType, _appSettings, _redisCache, dbr, _logger); + Helper.ScheduleMessageHelper.ScheduleMessage(prId, objFacebookaccounts.FbUserName, link, Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage, userId, link, filename, "https://graph.facebook.com/" + prId + "/picture?type=small", scheduledatetime, localscheduletime, mediaType, _appSettings, _redisCache, dbr, _logger); } catch (System.Exception ex) { @@ -729,6 +760,8 @@ public async Task DaywiseScheduleMessage(string message, string pr } List days = new List(); List weekval = null; + List SelectedDays = new List(); + if (weekdays != null) { @@ -740,12 +773,13 @@ public async Task DaywiseScheduleMessage(string message, string pr try { days.Add(day); + var enabledDay = ((DayOfWeek) Enum.Parse(typeof(DayOfWeek), day, true)).ToString(); + SelectedDays.Add(enabledDay); } catch (Exception ex) { } - } } @@ -758,10 +792,14 @@ public async Task DaywiseScheduleMessage(string message, string pr string retunMsg = string.Empty; + var scheduleDay = new Domain.Socioboard.Helpers.ScheduleDays(); + scheduleDay.SelectedDays = SelectedDays; + var week = JsonConvert.SerializeObject(SelectedDays); + foreach (var item in lstProfileIds) { - foreach (var week in days) - { + // foreach (var week in days) + // { if (item.StartsWith("fb")) { try @@ -833,7 +871,7 @@ public async Task DaywiseScheduleMessage(string message, string pr return Ok("Issue With Linkedin Page schedulers"); } } - } + // } } @@ -1152,7 +1190,7 @@ public IActionResult SchedulePagePost(string profileId, int TimeInterVal, long U _ShareathonRepository.Add(_LinkShareathon); new Thread(delegate () { - Helper.FacebookHelper.schedulePage_Post(_Facebookaccounts.AccessToken, item.PageId, TimeInterVal); + Helper.FacebookHelper.SchedulePagePost(_Facebookaccounts.AccessToken, items, item.PageId, TimeInterVal); }).Start(); } } diff --git a/src/Api.Socioboard/Controllers/TwitterController.cs b/src/Api.Socioboard/Controllers/TwitterController.cs index 0427c86b6..e08a24579 100644 --- a/src/Api.Socioboard/Controllers/TwitterController.cs +++ b/src/Api.Socioboard/Controllers/TwitterController.cs @@ -15,6 +15,7 @@ using System.Threading; using MongoDB.Bson; using Api.Socioboard.Repositories; +using Domain.Socioboard.Models; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 @@ -24,7 +25,7 @@ namespace Api.Socioboard.Controllers [Route("api/[controller]")] public class TwitterController : Controller { - public TwitterController(ILogger logger, IEmailSender email, Microsoft.Extensions.Options.IOptions settings, IHostingEnvironment appEnv) + public TwitterController(ILogger logger, IEmailSender email, Microsoft.Extensions.Options.IOptions settings, IHostingEnvironment appEnv) { _logger = logger; _appSettings = settings.Value; @@ -49,34 +50,33 @@ public TwitterController(ILogger logger, IEmailSender email, /// /// [HttpPost("AddTwitterAccount")] - public IActionResult AddTwitterAccount(long userId, long groupId, string requestToken, string requestSecret, string requestVerifier,bool follow) + public IActionResult AddTwitterAccount(long userId, long groupId, string requestToken, string requestSecret, string requestVerifier, bool follow) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; - DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - oAuthTwitter OAuth = new oAuthTwitter(_appSettings.twitterConsumerKey, _appSettings.twitterConsumerScreatKey, _appSettings.twitterRedirectionUrl); - OAuth.AccessToken = requestToken; - OAuth.AccessTokenSecret = requestVerifier; - OAuth.AccessTokenGet(requestToken, requestVerifier); - string output = Repositories.TwitterRepository.AddTwitterAccount(userId, groupId,follow, dbr, OAuth, _logger, _redisCache, _appSettings); + var dbr = new DatabaseRepository(_logger, _appEnv); + var OAuth = new oAuthTwitter(_appSettings.twitterConsumerKey, + _appSettings.twitterConsumerScreatKey, _appSettings.twitterRedirectionUrl) + { + AccessToken = requestToken, + AccessTokenSecret = requestVerifier + }; + OAuth.GetTwitterAccessToken(requestToken, requestVerifier); + var output = TwitterRepository.AddTwitterAccount(userId, groupId, follow, dbr, OAuth, _logger, _redisCache, _appSettings); if (output.Contains("Twitter account already added by you") || output.Contains("This Account is added by other user") || output.Contains("Issue while fetching twitter userId") || output.Contains("Your Twitter profile is not Authorized to add") || output.Contains("Error while Adding Account")) - { return BadRequest(output); - } - else - { - return Ok(output); - } + + return Ok(output); } [HttpPost("ReconnectTwtAcc")] - public IActionResult ReconnectTwtAcc(long userId, string requestToken, string requestSecret, string requestVerifier, bool follow) + public IActionResult ReconnectTwtAcc(long userId, string requestToken, string requestSecret, string requestVerifier, bool follow) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); oAuthTwitter OAuth = new oAuthTwitter(_appSettings.twitterConsumerKey, _appSettings.twitterConsumerScreatKey, _appSettings.twitterRedirectionUrl); OAuth.AccessToken = requestToken; OAuth.AccessTokenSecret = requestVerifier; - OAuth.AccessTokenGet(requestToken, requestVerifier); + OAuth.GetTwitterAccessToken(requestToken, requestVerifier); string output = Repositories.TwitterRepository.ReconnecTwitter(userId, follow, dbr, OAuth, _logger, _redisCache, _appSettings); return Ok(output); @@ -127,15 +127,15 @@ public IActionResult GetUserTweets(string profileId, long userId, int skip, int } else { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.messageDate); - var result = mongorepo.FindWithRange(t => t.profileId.Equals(profileId), sort, skip, count); + var result = mongorepo.FindWithRange(t => t.profileId.Equals(profileId), sort, skip, count); var task = Task.Run(async () => { return await result; }); - IList lstTwitterTweets = task.Result; + IList lstTwitterTweets = task.Result; return Ok(lstTwitterTweets); } } @@ -153,7 +153,7 @@ public IActionResult GetTwitterProfiles(long groupId) { lstTwtAcc.Add(twtAcc); } - } + } return Ok(lstTwtAcc); } @@ -179,12 +179,12 @@ public IActionResult GetNotifications(long groupId, long userId, int skip, int c { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); List lstGrpProfiles = Repositories.GroupProfilesRepository.getAllGroupProfiles(groupId, _redisCache, dbr); - List lstTwtMessages = new List(); + List lstTwtMessages = new List(); foreach (var item in lstGrpProfiles.Where(t => t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)) { if (skip + count < 100) { - List twtMessages = Repositories.TwitterRepository.GetUserNotifications(item.profileId, userId, _redisCache, _appSettings); + List twtMessages = Repositories.TwitterRepository.GetUserNotifications(item.profileId, userId, _redisCache, _appSettings); if (twtMessages != null) { lstTwtMessages.AddRange(twtMessages.OrderByDescending(t => t.messageDate).Skip(skip).Take(count)); @@ -192,15 +192,15 @@ public IActionResult GetNotifications(long groupId, long userId, int skip, int c } else { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.messageDate); - var result = mongorepo.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower), sort, skip, count); + var result = mongorepo.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterMention || t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.MessageType.TwitterFollower), sort, skip, count); var task = Task.Run(async () => { return await result; }); - IList lstTwitterTweets = task.Result; + IList lstTwitterTweets = task.Result; if (lstTwitterTweets != null) { lstTwtMessages.AddRange(lstTwitterTweets); @@ -216,23 +216,23 @@ public IActionResult GetTwitterDirectMessage(long groupId, long userId, int skip DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); List lstGrpProfiles = Repositories.GroupProfilesRepository.getAllGroupProfiles(groupId, _redisCache, dbr); string[] arrProfile = lstGrpProfiles.Select(t => t.profileId).ToArray(); - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", _appSettings); - var result = mongorepo.Find(t => arrProfile.Contains(t.senderId) || arrProfile.Contains(t.recipientId)); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + var result = mongorepo.Find(t => arrProfile.Contains(t.senderId) || arrProfile.Contains(t.recipientId)); var task = Task.Run(async () => { return await result; }); - IList lstTwitterTweets = task.Result; - lstTwitterTweets = lstTwitterTweets.GroupBy(y => y.senderId, (key, g) => g.OrderByDescending(t => t.createdDate).First()).OrderByDescending(p => p.createdDate).ToList(); + IList lstTwitterTweets = task.Result; + lstTwitterTweets = lstTwitterTweets.GroupBy(y => y.senderId, (key, g) => g.OrderByDescending(t => t.createdDate).First()).OrderByDescending(p => p.createdDate).ToList(); lstTwitterTweets = lstTwitterTweets.Where(t => t.profileId != null).ToList(); return Ok(lstTwitterTweets); } [HttpPost("TwitterReplyUpdate")] - public IActionResult TwitterReplyUpdate(long groupId, long userId, string profileId, string messageId, string message,string screenName) + public IActionResult TwitterReplyUpdate(long groupId, long userId, string profileId, string messageId, string message, string screenName) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - string TwitterReplyUpdate = Repositories.TwitterRepository.Post_ReplyStatusesUpdate(profileId, message, messageId, userId, groupId, dbr, _logger, _redisCache, _appSettings,screenName); + string TwitterReplyUpdate = Repositories.TwitterRepository.Post_ReplyStatusesUpdate(profileId, message, messageId, userId, groupId, dbr, _logger, _redisCache, _appSettings, screenName); return Ok(TwitterReplyUpdate); } @@ -256,14 +256,14 @@ public IActionResult TwitterFavorite_post(long groupId, long userId, string prof public IActionResult TwitterRecentFollower(long groupId) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - List lstTwitterRecentFollower = Helper.TwitterHelper.TwitterRecentFollower(groupId, dbr,_appSettings); + List lstTwitterRecentFollower = Helper.TwitterHelper.TwitterRecentFollower(groupId, dbr, _appSettings); return Ok(lstTwitterRecentFollower); } [HttpGet("TwitterFollowerCount")] public IActionResult TwitterFollowerCount(long groupId, long userId) { - DatabaseRepository dbr = new DatabaseRepository(_logger,_appEnv); + DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); string TwitterFollowerCount = Repositories.TwitterRepository.TwitterFollowerCount(userId, groupId, dbr, _redisCache); return Ok(TwitterFollowerCount); } @@ -272,26 +272,26 @@ public IActionResult TwitterFollowerCount(long groupId, long userId) public IActionResult GetIncommingMessage(long groupId, long userId) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - return Ok(Repositories.TwitterRepository.GetIncommingMessage(userId,groupId,dbr,_redisCache,_appSettings)); + return Ok(Repositories.TwitterRepository.GetIncommingMessage(userId, groupId, dbr, _redisCache, _appSettings)); } [HttpGet("GetConversation")] public IActionResult GetConversation(string SenderId, string RecipientId) { - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", _appSettings); - var result = mongorepo.Find((U=>(U.senderId == SenderId && U.recipientId == RecipientId) || (U.senderId == RecipientId && U.recipientId == SenderId))); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + var result = mongorepo.Find((U => (U.senderId == SenderId && U.recipientId == RecipientId) || (U.senderId == RecipientId && U.recipientId == SenderId))); var task = Task.Run(async () => { return await result; }); - IList lstTwitterTweetsConversation = task.Result; + IList lstTwitterTweetsConversation = task.Result; lstTwitterTweetsConversation = lstTwitterTweetsConversation.OrderBy(x => x.createdDate).ToList(); return Ok(lstTwitterTweetsConversation); } [HttpPost("PostTwitterDirectmessage")] - public IActionResult PostTwitterDirectmessage(string profileId, string SenderId, string RecipientId,string message,long UserId) + public IActionResult PostTwitterDirectmessage(string profileId, string SenderId, string RecipientId, string message, long UserId) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); string postmessage = ""; @@ -319,9 +319,9 @@ public IActionResult PostTwitterDirectmessage(string profileId, string SenderId, } message = postmessage; - if (SenderId==profileId) + if (SenderId == profileId) { - Helper.TwitterHelper.PostTwitterDirectmessage(RecipientId, message,profileId, UserId, dbr, _appSettings, _redisCache); + Helper.TwitterHelper.PostTwitterDirectmessage(RecipientId, message, profileId, UserId, dbr, _appSettings, _redisCache); return Ok(); } else @@ -332,6 +332,49 @@ public IActionResult PostTwitterDirectmessage(string profileId, string SenderId, } + + [HttpPost("PostTwtDirectmessage")] + public IActionResult PostTwtDirectmessage(string profileId, string SenderId, string RecipientId, string message, long UserId,string recipientScreenName,string recipientImageUrl,string senderScreenName,string senderImageUrl) + { + DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); + string postmessage = ""; + string[] updatedmessgae = Regex.Split(message, "
"); + foreach (var item in updatedmessgae) + { + if (!string.IsNullOrEmpty(item)) + { + //if (item.Contains("https://") || item.Contains("http://")) + //{ + // link = item; + //} + if (item.Contains("hhh") || item.Contains("nnn")) + { + if (item.Contains("hhh")) + { + postmessage = postmessage + "\n\r" + item.Replace("hhh", "#"); + } + } + else + { + postmessage = postmessage + "\n\r" + item; + } + } + } + message = postmessage; + + if (SenderId == profileId) + { + Helper.TwitterHelper.PostTwitterDirectmessage(RecipientId, message, profileId, UserId, dbr, _appSettings, _redisCache, recipientScreenName, recipientImageUrl, senderScreenName, senderImageUrl); + return Ok(); + } + else + { + Helper.TwitterHelper.PostTwitterDirectmessage(SenderId, message, profileId, UserId, dbr, _appSettings, _redisCache, recipientScreenName, recipientImageUrl, senderScreenName, senderImageUrl); + return Ok(); + } + } + + [HttpGet("TwitterMutual")] public IActionResult TwitterMutual(long groupId) { @@ -353,9 +396,9 @@ public IActionResult Twitterfans(long groupId) [HttpGet("TwitterUserFollowers")] public IActionResult TwitterUserFollowers(string profileId) { - DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - List lstfollowerlist = Helper.TwitterHelper.twitterfollowerslist(profileId, dbr, _appSettings); - return Ok(lstfollowerlist); + var dbr = new DatabaseRepository(_logger, _appEnv); + var followers = Helper.TwitterHelper.twitterfollowerslist(profileId, dbr, _appSettings); + return Ok(followers); } [HttpPost("BlocksUser")] @@ -418,17 +461,17 @@ public IActionResult EmailMessage(string profileIdFrom, string socioTwitterId, l public IActionResult UserMentions(string profileId, int skip, int count) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - List lstTwtMessages = new List(); + List lstTwtMessages = new List(); - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.messageDate); - var result = mongorepo.FindWithRange(t => t.profileId == profileId && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention), sort, skip, count); + var result = mongorepo.FindWithRange(t => t.profileId == profileId && (t.type == Domain.Socioboard.Enum.MessageType.TwitterMention), sort, skip, count); var task = Task.Run(async () => { return await result; }); - IList lstTwitterTweets = task.Result; + IList lstTwitterTweets = task.Result; if (lstTwitterTweets != null) { lstTwtMessages.AddRange(lstTwitterTweets); @@ -437,10 +480,10 @@ public IActionResult UserMentions(string profileId, int skip, int count) } [HttpGet("TwitterContactSearch")] - public IActionResult TwitterContactSearch(string profileId,string contact) + public IActionResult TwitterContactSearch(string profileId, string contact) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - List lstfollowerlist = Helper.TwitterHelper.twitterConstactSearchlist(profileId,contact, dbr, _appSettings); + List lstfollowerlist = Helper.TwitterHelper.twitterConstactSearchlist(profileId, contact, dbr, _appSettings); return Ok(lstfollowerlist); } @@ -469,7 +512,7 @@ public IActionResult TwitterConversation(string profileId) [HttpGet("DeleteTwtFeed")] - public IActionResult deleteTwtFeed(string profileId ,string messageId) + public IActionResult deleteTwtFeed(string profileId, string messageId) { MongoRepository _DeleteTwtFeeds = new MongoRepository("MongoTwitterFeed", _appSettings); var builders = Builders.Filter; @@ -521,14 +564,14 @@ public IActionResult GettwitterSingle(string profileId) } - [HttpPost("publish")] - public IActionResult publish(string profileId,string twitterText, long userId , string imgUrl ,string strid) + [HttpPost("publish")] + public IActionResult publish(string profileId, string twitterText, long userId, string imgUrl, string strid) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); string ret = Helper.TwitterHelper.PostTwitterMessage(_appSettings, _redisCache, twitterText, profileId, userId, imgUrl, true, 0, "", dbr, _logger); - if (ret =="") + if (ret == "") { - string responce = SavedFeedsManagementRepository.publish( profileId, strid, _appSettings); + string responce = SavedFeedsManagementRepository.publish(profileId, strid, _appSettings); return Ok(responce); } @@ -536,9 +579,9 @@ public IActionResult publish(string profileId,string twitterText, long userId , { return Ok("failed"); } - - } + + } [HttpGet("Notifications")] public IActionResult Notifications(long groupId, long userId, int skip, int count) @@ -547,51 +590,51 @@ public IActionResult Notifications(long groupId, long userId, int skip, int coun DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); List alldata = new List(); List lstGrpProfiles = Repositories.GroupProfilesRepository.getAllGroupProfiles(groupId, _redisCache, dbr); - List lstTwtMessages = new List(); - List TwtMessages = new List(); + List lstTwtMessages = new List(); + List TwtMessages = new List(); foreach (var item in lstGrpProfiles.Where(t => t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)) { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.messageDate); - var result = mongorepo.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterUsertweet), sort, skip, count); - var task = Task.Run(async () => + var result = mongorepo.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterMention || t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.MessageType.TwitterFollower || t.type == Domain.Socioboard.Enum.MessageType.TwitterUsertweet), sort, skip, count); + var task = Task.Run(async () => { return await result; }); - - IList lstTwitterTweets = task.Result; - TwtMessages = lstTwitterTweets.Where(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterUsertweet).ToList(); + IList lstTwitterTweets = task.Result; + + TwtMessages = lstTwitterTweets.Where(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterUsertweet).ToList(); if (lstTwitterTweets != null) { lstTwtMessages.AddRange(lstTwitterTweets); } var d = lstTwitterTweets.Count; } - int posttext = TwtMessages.FindAll(t => t.twitterMsg != null && t.mediaUrl == null && !t.twitterMsg.Contains("http") || !t.twitterMsg.Contains("https") || !t.twitterMsg.Contains("www.") || !t.twitterMsg.Contains("http://") || !t.twitterMsg.Contains("https://") || !t.twitterMsg.Contains("www.")).Count; + int posttext = TwtMessages.FindAll(t => t.Message != null && t.mediaUrl == null && !t.Message.Contains("http") || !t.Message.Contains("https") || !t.Message.Contains("www.") || !t.Message.Contains("http://") || !t.Message.Contains("https://") || !t.Message.Contains("www.")).Count; int mediapost = TwtMessages.FindAll(t => t.mediaUrl != null).Count; - int linkpost = TwtMessages.FindAll(t => t.twitterMsg.Contains("http") || t.twitterMsg.Contains("https") || t.twitterMsg.Contains("www.") || t.twitterMsg.Contains("http://") || t.twitterMsg.Contains("https://") || t.twitterMsg.Contains("www.")).Count; - int mentions = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention).Count; - int retweet = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet).Count; + int linkpost = TwtMessages.FindAll(t => t.Message.Contains("http") || t.Message.Contains("https") || t.Message.Contains("www.") || t.Message.Contains("http://") || t.Message.Contains("https://") || t.Message.Contains("www.")).Count; + int mentions = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterMention).Count; + int retweet = lstTwtMessages.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet).Count; - // || t.twitterMsg.Contains("https") || t.twitterMsg.Contains("www.") || t.twitterMsg.Contains("http://") || t.twitterMsg.Contains("https://") || t.twitterMsg.Contains("www.") + // || t.Message.Contains("https") || t.Message.Contains("www.") || t.Message.Contains("http://") || t.Message.Contains("https://") || t.Message.Contains("www.") alldata.Add(mentions); alldata.Add(retweet); - List lstTwtMessagess = new List(); + List lstTwtMessagess = new List(); foreach (var item in lstGrpProfiles.Where(t => t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)) { - MongoRepository mongorepoDm = new MongoRepository("MongoTwitterDirectMessages", _appSettings); + MongoRepository mongorepoDm = new MongoRepository("MongoDirectMessages", _appSettings); - var builder = Builders.Sort; + var builder = Builders.Sort; var sort = builder.Descending(t => t.entryDate); - var result = mongorepoDm.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent), sort, skip, count); + var result = mongorepoDm.FindWithRange(t => t.profileId.Equals(item.profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived || t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent), sort, skip, count); var task = Task.Run(async () => { return await result; }); - IList lstTwitterdm = task.Result; + IList lstTwitterdm = task.Result; if (lstTwitterdm != null) { lstTwtMessagess.AddRange(lstTwitterdm); @@ -599,8 +642,8 @@ public IActionResult Notifications(long groupId, long userId, int skip, int coun } - int dmrecived = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived).Count; - int dmsend = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent).Count; + int dmrecived = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived).Count; + int dmsend = lstTwtMessagess.FindAll(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent).Count; alldata.Add(dmrecived); alldata.Add(dmsend); alldata.Add(posttext); diff --git a/src/Api.Socioboard/Controllers/UserController.cs b/src/Api.Socioboard/Controllers/UserController.cs index 5ecc6cc37..a1f1194e6 100644 --- a/src/Api.Socioboard/Controllers/UserController.cs +++ b/src/Api.Socioboard/Controllers/UserController.cs @@ -51,12 +51,14 @@ public UserController(ILogger logger, IEmailSender emailSender, [HttpPost("Register")] public IActionResult Register(User user) { + #region Assign Initial Values + user.CreateDate = DateTime.UtcNow; user.ExpiryDate = DateTime.UtcNow.AddDays(1); user.EmailValidateToken = SBHelper.RandomString(20); user.ValidateTokenExpireDate = DateTime.UtcNow.AddDays(1); user.ActivationStatus = Domain.Socioboard.Enum.SBUserActivationStatus.MailSent; - user.Password = SBHelper.MD5Hash(user.Password); + user.Password = SBHelper.Md5Hash(user.Password); user.UserName = "Socioboard"; user.UserType = "User"; user.ReferralStatus = "InActive"; @@ -66,53 +68,68 @@ public IActionResult Register(User user) if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Free) { user.PaymentStatus = Domain.Socioboard.Enum.SBPaymentStatus.UnPaid; - } + } + + #endregion + if (!ModelState.IsValid) { return BadRequest(ModelState); } - DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - IList lstUser = dbr.Find(t => t.EmailId.Equals(user.EmailId)); - if (lstUser != null && lstUser.Count() > 0) + // get the sql database respository + var mysqlDbRespository = new DatabaseRepository(_logger, _appEnv); + + //validate the email is already register or not + var matchedUserList = mysqlDbRespository.Find(t => t.EmailId.Equals(user.EmailId)); + + if (matchedUserList != null && matchedUserList.Count > 0) { return BadRequest("This Email is already registered please login to continue"); } - IList lstUser1 = dbr.Find(a => a.PhoneNumber.Equals(user.PhoneNumber)); - //if (lstUser1 != null && lstUser1.Count() > 0) - //{ - // return BadRequest("Phone Number Exist"); - //} - int SavedStatus = dbr.Add(user); - User nuser = dbr.Single(t => t.EmailId.Equals(user.EmailId)); - if (SavedStatus == 1 && nuser != null) + + // add to database + var savedStatus = mysqlDbRespository.Add(user); + + // Fetch the full details, because some additional seed data's are present + var fetchFullUserDetails = mysqlDbRespository.Single(t => t.EmailId.Equals(user.EmailId)); + + if (savedStatus == 1 && fetchFullUserDetails != null) { - nuser.RefrralCode = "SOCIOBOARD_" + nuser.Id; - int SavedRefrral = dbr.Update(nuser); - Groups group = new Groups(); - group.adminId = nuser.Id; + fetchFullUserDetails.RefrralCode = "SOCIOBOARD_" + fetchFullUserDetails.Id; + + mysqlDbRespository.Update(fetchFullUserDetails); + + #region Add to default group and add a member to group member respository + var group = new Groups(); + group.adminId = fetchFullUserDetails.Id; // group.id = nuser.Id; group.createdDate = DateTime.UtcNow; group.groupName = Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName; - SavedStatus = dbr.Add(group); - if (SavedStatus == 1) + savedStatus = mysqlDbRespository.Add(group); + + if (savedStatus == 1) { - long GroupId = dbr.FindSingle(t => t.adminId == group.adminId && t.groupName.Equals(group.groupName)).id; - GroupMembersRepository.createGroupMember(GroupId, nuser, _redisCache, dbr); - } + var groupId = mysqlDbRespository.FindSingle(t => t.adminId == group.adminId && t.groupName.Equals(group.groupName)).id; + GroupMembersRepository.CreateGroupMember(groupId, fetchFullUserDetails, _redisCache, mysqlDbRespository); + } + #endregion + + #region Sending Email Activation Email to resgister user try { - string path = _appEnv.WebRootPath + "\\views\\mailtemplates\\registrationmail.html"; - string html = System.IO.File.ReadAllText(path); - html = html.Replace("[FirstName]", nuser.FirstName); - html = html.Replace("[AccountType]", nuser.AccountType.ToString()); - html = html.Replace("[ActivationLink]", _appSettings.Domain + "/Home/Active?Token=" + nuser.EmailValidateToken + "&id=" + nuser.Id); - _emailSender.SendMailSendGrid(_appSettings.frommail, "", nuser.EmailId, "", "", "Socioboard Email confirmation Link", html, _appSettings.SendgridUserName, _appSettings.SendGridPassword); + var path = _appEnv.WebRootPath + "\\views\\mailtemplates\\registrationmail.html"; + var html = System.IO.File.ReadAllText(path); + html = html.Replace("[FirstName]", fetchFullUserDetails.FirstName); + html = html.Replace("[AccountType]", fetchFullUserDetails.AccountType.ToString()); + html = html.Replace("[ActivationLink]", _appSettings.Domain + "/Home/Active?Token=" + fetchFullUserDetails.EmailValidateToken + "&id=" + fetchFullUserDetails.Id); + _emailSender.SendMailSendGrid(_appSettings.frommail, "", fetchFullUserDetails.EmailId, "", "", "Socioboard Email confirmation Link", html, _appSettings.SendgridUserName, _appSettings.SendGridPassword); } catch { return Ok(); - } + } + #endregion } else { @@ -130,7 +147,7 @@ public IActionResult PhoneSignUp(User user) user.EmailValidateToken = SBHelper.RandomString(20); user.ValidateTokenExpireDate = DateTime.UtcNow.AddDays(1); user.ActivationStatus = Domain.Socioboard.Enum.SBUserActivationStatus.MailSent; - user.Password = SBHelper.MD5Hash(user.Password); + user.Password = SBHelper.Md5Hash(user.Password); user.UserName = "Socioboard"; user.UserType = "User"; user.PayPalAccountStatus = Domain.Socioboard.Enum.PayPalAccountStatus.notadded; @@ -166,7 +183,7 @@ public IActionResult PhoneSignUp(User user) if (SavedStatus == 1) { long GroupId = dbr.FindSingle(t => t.adminId == group.adminId && t.groupName.Equals(group.groupName)).id; - GroupMembersRepository.createGroupMember(GroupId, nuser, _redisCache, dbr); + GroupMembersRepository.CreateGroupMember(GroupId, nuser, _redisCache, dbr); } try { @@ -198,7 +215,7 @@ public IActionResult SocioboardAccountCreation(User user) user.ValidateTokenExpireDate = DateTime.UtcNow.AddDays(1); user.ActivationStatus = Domain.Socioboard.Enum.SBUserActivationStatus.Active; user.dailyGrpReportsSummery = true; - user.Password = SBHelper.MD5Hash(user.Password); + user.Password = SBHelper.Md5Hash(user.Password); user.UserName = "Socioboard"; user.UserType = "User"; user.PayPalAccountStatus = Domain.Socioboard.Enum.PayPalAccountStatus.notadded; @@ -236,7 +253,7 @@ public IActionResult SocioboardAccountCreation(User user) if (SavedStatus == 1) { long GroupId = dbr.FindSingle(t => t.adminId == group.adminId && t.groupName.Equals(group.groupName)).id; - GroupMembersRepository.createGroupMember(GroupId, nuser, _redisCache, dbr); + GroupMembersRepository.CreateGroupMember(GroupId, nuser, _redisCache, dbr); } return Ok("Register Successfully."); } @@ -261,7 +278,7 @@ public IActionResult Login(UserLoginViewModel user) // User inMemUser = (User)_memoryCache.Get(user.UserName); if (inMemUser != null) { - if (inMemUser.Password.Equals(SBHelper.MD5Hash(user.Password))) + if (inMemUser.Password.Equals(SBHelper.Md5Hash(user.Password))) { return Ok(inMemUser); } @@ -277,45 +294,41 @@ public IActionResult Login(UserLoginViewModel user) _logger.LogError(ex.StackTrace); } - - - DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - IList lstUser = dbr.Find(t => t.EmailId.Equals(user.UserName)); - if (lstUser != null && lstUser.Count() > 0) + var dbr = new DatabaseRepository(_logger, _appEnv); + var lstUser = dbr.Find(t => t.EmailId.Equals(user.UserName)); + if (lstUser != null && lstUser.Count > 0) { - if (lstUser.First().Password != null && lstUser.First().Password.Equals(SBHelper.MD5Hash(user.Password))) + var matchedUser = lstUser.First(); + + if (matchedUser.Password != null && matchedUser.Password.Equals(SBHelper.Md5Hash(user.Password))) { //if (lstUser.First().UserType == "SuperAdmin") //{ // return Ok(lstUser.First()); //} - if (lstUser.First().RefrralCode == null) + if (matchedUser.RefrralCode == null) { - lstUser.First().RefrralCode = "SOCIOBOARD_" + lstUser.First().Id; + matchedUser.RefrralCode = "SOCIOBOARD_" + matchedUser.Id; } DateTime d1 = DateTime.UtcNow; //User userTable = dbr.Single < User>(t => t.EmailId == user.UserName); - lstUser.First().LastLoginTime = d1; + matchedUser.LastLoginTime = d1; //userTable.LastLoginTime = d1; - dbr.Update(lstUser.First()); + dbr.Update(matchedUser); // _memoryCache.Set(lstUser.First().EmailId, lstUser.First()); - _redisCache.Set(lstUser.First().EmailId, lstUser.First()); - if (lstUser.First().ActivationStatus == Domain.Socioboard.Enum.SBUserActivationStatus.Active) - { - return Ok(lstUser.First()); - } - else if (lstUser.First().ActivationStatus == Domain.Socioboard.Enum.SBUserActivationStatus.MailSent) - { - return Ok("Activate your account through email"); - } - else if (lstUser.First().ActivationStatus == Domain.Socioboard.Enum.SBUserActivationStatus.Disable) - { - return Ok("Your account is disabled. Please contact socioboard support for more assistance"); - } - else + _redisCache.Set(matchedUser.EmailId, matchedUser); + + switch (matchedUser.ActivationStatus) { - return Ok("Something went wrong please try after sometime"); + case Domain.Socioboard.Enum.SBUserActivationStatus.Active: + return Ok(matchedUser); + case Domain.Socioboard.Enum.SBUserActivationStatus.MailSent: + return Ok("Activate your account through email"); + case Domain.Socioboard.Enum.SBUserActivationStatus.Disable: + return Ok("Your account is disabled. Please contact socioboard support for more assistance"); + default: + return Ok("Something went wrong please try after sometime"); } } else @@ -360,7 +373,7 @@ public IActionResult CheckUserLogin(UserLoginViewModel user) { return Ok(lstUser.First()); } - else if (lstUser.First().Password.Equals(SBHelper.MD5Hash(user.Password))) + else if (lstUser.First().Password.Equals(SBHelper.Md5Hash(user.Password))) { return Ok(lstUser.First()); } @@ -1630,7 +1643,7 @@ public IActionResult FacebookLogin(string AccessToken, Domain.Socioboard.Enum.SB if (SavedStatus == 1) { Groups ngrp = dbr.Find(t => t.adminId == nuser.Id && t.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName)).FirstOrDefault(); - GroupMembersRepository.createGroupMember(ngrp.id, nuser, _redisCache, dbr); + GroupMembersRepository.CreateGroupMember(ngrp.id, nuser, _redisCache, dbr); // Adding Facebook Profile Api.Socioboard.Repositories.FacebookRepository.AddFacebookAccount(profile, FbUser.getFbFriends(AccessToken), dbr, nuser.Id, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookProfile, AccessToken, _redisCache, _appSettings, _logger); } @@ -1820,15 +1833,15 @@ public IActionResult ChangePassword(long userId) User user = dbr.Single(t => t.Id == userId); if (user != null && user.Password != null) { - if (user.Password.Equals(SBHelper.MD5Hash(currentPassword))) + if (user.Password.Equals(SBHelper.Md5Hash(currentPassword))) { - if (user.Password.Equals(SBHelper.MD5Hash(newPassword))) + if (user.Password.Equals(SBHelper.Md5Hash(newPassword))) { return BadRequest("Current Password and New Password are same.Try with New Password"); } if (newPassword.Equals(conformPassword)) { - user.Password = SBHelper.MD5Hash(newPassword); + user.Password = SBHelper.Md5Hash(newPassword); int res = dbr.Update(user); if (res == 1) { @@ -2053,7 +2066,7 @@ public IActionResult ResetPasswordMail(string emailId, string changePassword, st { if (user.forgotPasswordKeyToken.Equals(token)) { - user.Password = SBHelper.MD5Hash(changePassword); + user.Password = SBHelper.Md5Hash(changePassword); user.forgotPasswordKeyToken = SBHelper.RandomString(20); user.forgotPasswordExpireDate = DateTime.UtcNow.AddDays(1); int res = dbr.Update(user); @@ -2096,7 +2109,7 @@ public IActionResult EnableTwoStepLogin(long userId, string currentPassword) User user = dbr.Single(t => t.Id == userId); if (user.SocialLoginEnableFb == false && user.SocialLoginEnableGo == false) { - if (user.Password.Equals(SBHelper.MD5Hash(currentPassword))) + if (user.Password.Equals(SBHelper.Md5Hash(currentPassword))) { user.TwostepEnable = true; int res = dbr.Update(user); @@ -2109,7 +2122,7 @@ public IActionResult EnableTwoStepLogin(long userId, string currentPassword) return BadRequest("Error while enabling two step login, pls try after some time."); } } - else if (!user.Password.Equals(SBHelper.MD5Hash(currentPassword))) + else if (!user.Password.Equals(SBHelper.Md5Hash(currentPassword))) { return BadRequest("Wrong password"); } @@ -2141,7 +2154,7 @@ public IActionResult DisablebleTwoStepLogin(long userId, string currentPassword) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); User user = dbr.Single(t => t.Id == userId); - if (user.Password.Equals(SBHelper.MD5Hash(currentPassword))) + if (user.Password.Equals(SBHelper.Md5Hash(currentPassword))) { user.TwostepEnable = false; int res = dbr.Update(user); @@ -2154,7 +2167,7 @@ public IActionResult DisablebleTwoStepLogin(long userId, string currentPassword) return BadRequest("Error while disabling two step login, pls try after some time."); } } - else if (!user.Password.Equals(SBHelper.MD5Hash(currentPassword))) + else if (!user.Password.Equals(SBHelper.Md5Hash(currentPassword))) { return BadRequest("Wrong password"); } @@ -2183,7 +2196,7 @@ public IActionResult VerificationPassword(long userId, string currentPassword) { return BadRequest("EmailId reset is not permitted as you registered in Socioboard with Google."); } - if (user.Password.Equals(SBHelper.MD5Hash(currentPassword))) + if (user.Password.Equals(SBHelper.Md5Hash(currentPassword))) { return Ok("Now you can change your EmailID"); } @@ -2586,7 +2599,7 @@ public IActionResult AuthLogin(AuthUser authUser) if (authUser.AuthCode.Contains("1974224400.2310fd1.699477d40ff64cd6babfb0b3a6cf60fa")) { DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); - User _User = dbr.Single(t => t.EmailId.Equals(authUser.email) && t.Password.Equals(SBHelper.MD5Hash(authUser.password))); + User _User = dbr.Single(t => t.EmailId.Equals(authUser.email) && t.Password.Equals(SBHelper.Md5Hash(authUser.password))); if (_User == null) { authUser.AuthMessage = "Invalid EmailId and password"; diff --git a/src/Api.Socioboard/Helper/FacebookHelper.cs b/src/Api.Socioboard/Helper/FacebookHelper.cs index 446f9bec2..dd2de83bd 100644 --- a/src/Api.Socioboard/Helper/FacebookHelper.cs +++ b/src/Api.Socioboard/Helper/FacebookHelper.cs @@ -6,6 +6,7 @@ using MongoDB.Driver; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -14,15 +15,17 @@ using Newtonsoft.Json.Linq; using Socioboard.Facebook.Data; using Api.Socioboard.Controllers; +using Domain.Socioboard.Enum; +using Domain.Socioboard.Interfaces.Repositories; namespace Api.Socioboard.Helper { public static class FacebookHelper { - + 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.Enum.MediaType mediaType, string profileName, DatabaseRepository dbr, ILogger _logger) { - + string ret = ""; FacebookClient fb = new FacebookClient(); fb.AccessToken = accessToken; @@ -43,7 +46,7 @@ public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profile { if (!string.IsNullOrEmpty(imagePath)) { - if(!imagePath.Contains("mp4") && !imagePath.Contains("mov") && !imagePath.Contains("mpeg") && !imagePath.Contains("wmv") && !imagePath.Contains("avi") && !imagePath.Contains("flv") && !imagePath.Contains("3gp")) + if (!imagePath.Contains("mp4") && !imagePath.Contains("mov") && !imagePath.Contains("mpeg") && !imagePath.Contains("wmv") && !imagePath.Contains("avi") && !imagePath.Contains("flv") && !imagePath.Contains("3gp")) { Uri u = new Uri(imagePath); string filename = string.Empty; @@ -104,26 +107,7 @@ public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profile ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();//v2.1 } - ScheduledMessage scheduledMessage = new ScheduledMessage(); - scheduledMessage.createTime = DateTime.UtcNow; - scheduledMessage.picUrl = "https://graph.facebook.com/" + fbUserId + "/picture?type=small";//imagePath; - scheduledMessage.profileId = profileId; - if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile) - { - scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.Facebook; - } - else - { - scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage; - } - scheduledMessage.scheduleTime = DateTime.UtcNow; - scheduledMessage.shareMessage = message; - scheduledMessage.userId = userId; - scheduledMessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated; - scheduledMessage.url = imagePath;//"https://graph.facebook.com/"+ fbUserId + "/picture?type=small"; - scheduledMessage.mediaType = mediaType; - scheduledMessage.socialprofileName = profileName; - dbr.Add(scheduledMessage); + UpdatePublishedDetails(profiletype, fbUserId, message, profileId, userId, imagePath, mediaType, profileName, dbr); } catch (Exception ex) @@ -134,6 +118,28 @@ public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profile return ret; } + public static void UpdatePublishedDetails(FbProfileType profileType, string fbUserId, string message, string profileId, long userId, string imagePath, MediaType mediaType, string profileName, IDatabaseRepository dbr) + { + var scheduledMessage = new ScheduledMessage + { + createTime = DateTime.UtcNow, + picUrl = "https://graph.facebook.com/" + fbUserId + "/picture?type=small", + profileId = profileId, + profileType = profileType == Domain.Socioboard.Enum.FbProfileType.FacebookProfile + ? Domain.Socioboard.Enum.SocialProfileType.Facebook + : Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage, + scheduleTime = DateTime.UtcNow, + shareMessage = message, + userId = userId, + status = Domain.Socioboard.Enum.ScheduleStatus.Compleated, + url = imagePath, + mediaType = mediaType, + socialprofileName = profileName + }; + + + dbr.Add(scheduledMessage); + } public static string UrlComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Enum.MediaType mediaType, string profileName, DatabaseRepository dbr, ILogger _logger) { @@ -194,16 +200,16 @@ public static string UrlComposeMessage(Domain.Socioboard.Enum.FbProfileType prof var webClient = new WebClient(); byte[] img = webClient.DownloadData(imagePath); media.SetValue(img); - // args["title"] = message; - // args["description"] = message; + // args["title"] = message; + // args["description"] = message; args["source"] = media; ret = fb.Post("v2.7/" + fbUserId + "/videos", args).ToString();//v2.1 } } else { - // args["message"] = message; - // ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString(); + // args["message"] = message; + // ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString(); } } else @@ -220,11 +226,11 @@ public static string UrlComposeMessage(Domain.Socioboard.Enum.FbProfileType prof { ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();//v2.1 } - catch(Exception ex) + catch (Exception ex) { } - + } ScheduledMessage scheduledMessage = new ScheduledMessage(); @@ -240,7 +246,7 @@ public static string UrlComposeMessage(Domain.Socioboard.Enum.FbProfileType prof scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage; } scheduledMessage.scheduleTime = DateTime.UtcNow; - scheduledMessage.shareMessage =link; + scheduledMessage.shareMessage = link; scheduledMessage.userId = userId; scheduledMessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated; scheduledMessage.url = imagePath;//"https://graph.facebook.com/"+ fbUserId + "/picture?type=small"; @@ -403,7 +409,7 @@ public static Domain.Socioboard.Models.Facebookpage GetFbPageDetails(string url, { pageinfo = fb.Get(url); } - catch(Exception ex) + catch (Exception ex) { try { @@ -447,7 +453,7 @@ public static Domain.Socioboard.Models.Facebookpage GetFbPageDetails(string url, dynamic friends = fb.Get("v2.7/" + _facebookpage.ProfilePageId);//v2.1 fancountPage = Convert.ToInt32(friends["likes"].ToString()); } - catch + catch { fancountPage = 0; } @@ -483,54 +489,69 @@ public static string getFacebookRecentPost(string fbAccesstoken, string pageId) return output; } - public static void schedulePage_Post(string accessToken, string id,int TimeInterVal) + /// + /// + /// + /// + /// + /// + public static void SchedulePagePost(string accessToken,string destinationPageId, string sourcePageId, int timeInterVal) { try { - int i = 1; - string curser_next = string.Empty; + var timeIncrementer = 1; + + var cursorNext = string.Empty; do { - string feeds = Fbpages.getFacebookPageRecentPost(accessToken, id, curser_next); - string feedId = string.Empty; - - if (!string.IsNullOrEmpty(feeds) && !feeds.Equals("[]")) + 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())) { - JObject fbpageNotes = JObject.Parse(feeds); try { - curser_next = fbpageNotes["paging"]["next"].ToString(); + 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) { - curser_next = "0"; - } - foreach (JObject obj in JArray.Parse(fbpageNotes["data"].ToString())) - { - try - { - string feedid = obj["id"].ToString(); - feedid = feedid.Split('_')[1]; - double timestamp = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow.AddMinutes(TimeInterVal * i)); - string link = "https://www.facebook.com/" + id + "/posts/" + feedid; - string ret = Fbpages.schedulePage_Post(accessToken, link, timestamp.ToString()); - if (!string.IsNullOrEmpty(ret)) - { - i++; - } - } - catch { } - + Console.WriteLine(ex.Message); } } - } while (curser_next != "0"); + } while (cursorNext != "0"); } catch (Exception ex) { + Console.WriteLine(ex.Message); } } - + } } diff --git a/src/Api.Socioboard/Helper/ScheduleMessageHelper.cs b/src/Api.Socioboard/Helper/ScheduleMessageHelper.cs index 73fe07709..5046cef18 100644 --- a/src/Api.Socioboard/Helper/ScheduleMessageHelper.cs +++ b/src/Api.Socioboard/Helper/ScheduleMessageHelper.cs @@ -6,6 +6,9 @@ using Microsoft.Extensions.Logging; using Domain.Socioboard.Models; using System.Globalization; +using Domain.Socioboard.Helpers; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace Api.Socioboard.Helper { @@ -72,8 +75,6 @@ public static string ScheduleMessage(string profileId, string socialprofileName, public static string DaywiseScheduleMessage(string profileId, string socialprofileName, string weekdays, string shareMessage, Domain.Socioboard.Enum.SocialProfileType profiletype, long userId, string link, string url, string picUrl, string localscheduletime, AppSettings _AppSettings, Cache _redisCache, DatabaseRepository dbr, ILogger _logger) { - - DaywiseSchedule scheduledMessage = new DaywiseSchedule(); scheduledMessage.shareMessage = shareMessage; //scheduledMessage.calendertime = Convert.ToDateTime(localscheduletime); @@ -109,14 +110,18 @@ public static string DaywiseScheduleMessage(string profileId, string socialprofi scheduledMessage.profileType = profiletype; scheduledMessage.profileId = profileId; scheduledMessage.weekdays = weekdays; + + scheduledMessage.url = url; scheduledMessage.link = link; scheduledMessage.picUrl = picUrl; scheduledMessage.createTime = DateTime.UtcNow; - scheduledMessage.clientTime = DateTime.Now; - scheduledMessage.scheduleTime = Convert.ToDateTime(userlocalscheduletime); - scheduledMessage.localscheduletime = userlocalscheduletime; + scheduledMessage.clientTime = DateTime.Now; + scheduledMessage.localscheduletime = Convert.ToDateTime(userlocalscheduletime); + + var selectDayObject = JsonConvert.DeserializeObject>(scheduledMessage.weekdays); + scheduledMessage.scheduleTime = DateTimeHelper.GetNextScheduleDate(selectDayObject, scheduledMessage.localscheduletime); // scheduledMessage.localscheduletime = userlocalscheduletime; scheduledMessage.socialprofileName = socialprofileName; diff --git a/src/Api.Socioboard/Helper/TwitterHelper.cs b/src/Api.Socioboard/Helper/TwitterHelper.cs index 7bd2b7bd5..40c453796 100644 --- a/src/Api.Socioboard/Helper/TwitterHelper.cs +++ b/src/Api.Socioboard/Helper/TwitterHelper.cs @@ -19,6 +19,8 @@ using Socioboard.Twitter.Twitter.Core.FollowersMethods; using Socioboard.Twitter.Twitter.Core.TimeLineMethods; using Socioboard.Twitter.Twitter.Core.DirectMessageMethods; +using Socioboard.Twitter.Twitter.Core; +using Socioboard.Twitter.TwitterUtilites; namespace Api.Socioboard.Helper { @@ -44,12 +46,12 @@ public static string PostTwitterMessage(AppSettings _AppSettings, Cache _redisCa { PhotoUpload ph = new PhotoUpload(); string res = string.Empty; - // rt = ph.Tweet(url, message, OAuthTwt); + // rt = ph.Tweet(url, message, OAuthTwt); if (url.Contains("mp4")) { var webClient = new WebClient(); byte[] img = webClient.DownloadData(url); - rt = videoUploading(img,message,objTwitterAccount.oAuthToken,objTwitterAccount.oAuthSecret,_AppSettings); + rt = videoUploading(img, message, objTwitterAccount.oAuthToken, objTwitterAccount.oAuthSecret, _AppSettings); } else { @@ -104,11 +106,11 @@ public static string PostTwitterMessage(AppSettings _AppSettings, Cache _redisCa return str; } - public static bool videoUploading(byte[] binary,string tweetmessage,string accesstoken,string tokensecret,Helper.AppSettings _appsetting) + public static bool videoUploading(byte[] binary, string tweetmessage, string accesstoken, string tokensecret, Helper.AppSettings _appsetting) { try { - Tweetinvi.Auth.SetUserCredentials(_appsetting.twitterConsumerKey,_appsetting.twitterConsumerScreatKey,accesstoken, tokensecret); + Tweetinvi.Auth.SetUserCredentials(_appsetting.twitterConsumerKey, _appsetting.twitterConsumerScreatKey, accesstoken, tokensecret); string mediaType = "video/mp4"; var uploader = Tweetinvi.Upload.CreateChunkedUploader(); var half = (binary.Length / 2); @@ -121,7 +123,7 @@ public static bool videoUploading(byte[] binary,string tweetmessage,string acces if (uploader.Append(second, "media")) { var media = uploader.Complete(); - var tweet =Tweetinvi.Tweet.PublishTweet(tweetmessage, new Tweetinvi.Parameters.PublishTweetOptionalParameters + var tweet = Tweetinvi.Tweet.PublishTweet(tweetmessage, new Tweetinvi.Parameters.PublishTweetOptionalParameters { Medias = { media } }); @@ -324,9 +326,107 @@ public static string TwitterComposeMessageRss(string message, string OAuthToken, return lstTwitterRecentFollower; } + public static void PostTwitterDirectmessage(string toId, string message, string profileId, long UserId, Model.DatabaseRepository dbr, + Helper.AppSettings _appSettings, Helper.Cache _redisCache,string recipientScreenName, string recipientImageUrl, string senderScreenName, string senderImageUrl) + { + Domain.Socioboard.Models.Mongo.MongoDirectMessages objDirectMessages = new Domain.Socioboard.Models.Mongo.MongoDirectMessages(); + // Domain.Socioboard.Models.TwitterAccount objTwitterAccount = Repositories.TwitterRepository.getTwitterAccount(profileId, _redisCache,dbr); + Domain.Socioboard.Models.TwitterAccount objTwitterAccount = new TwitterAccount(); + objTwitterAccount = dbr.Single(t => t.userId == UserId && t.twitterUserId.Contains(profileId)); + if (objTwitterAccount == null) + { + objTwitterAccount = dbr.Single(t => t.userId == UserId && t.twitterUserId.Contains(toId)); + toId = profileId; + } + oAuthTwitter OAuthTwt = new oAuthTwitter(_appSettings.twitterConsumerKey, _appSettings.twitterConsumerScreatKey, _appSettings.twitterRedirectionUrl); + OAuthTwt.AccessToken = objTwitterAccount.oAuthToken; + OAuthTwt.AccessTokenSecret = objTwitterAccount.oAuthSecret; + OAuthTwt.TwitterScreenName = objTwitterAccount.twitterScreenName; + OAuthTwt.TwitterUserId = objTwitterAccount.twitterUserId; + const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; + TwitterUser twtuser = new TwitterUser(); + JArray ret = new JArray(); + try + { + var objTwitterDirectMessages = new TwitterApiHelper(_appSettings.twitterConsumerKey, _appSettings.twitterConsumerScreatKey, OAuthTwt.AccessToken, OAuthTwt.AccessTokenSecret); + var task = new Task(async () => + { + var response = await objTwitterDirectMessages.DirectMessage(message, toId); + + if (!string.IsNullOrEmpty(response)) + { + + try + { + var jobject = JObject.Parse(response); + + objDirectMessages.messageId = jobject.SelectToken("event.id")?.ToString() ?? string.Empty; + objDirectMessages.message = jobject.SelectToken("event.message_create.message_data.text")?.ToString() ?? string.Empty; + objDirectMessages.profileId = objTwitterAccount.twitterUserId; + + var timestamp = jobject.SelectToken("event.created_timestamp")?.ToString() ?? string.Empty; + objDirectMessages.timeStamp = Math.Floor(double.Parse(timestamp) / 1000); + + try + { + var dateTime = + Domain.Socioboard.Helpers.SBHelper + .ConvertUnixTimeStamp(timestamp); + + objDirectMessages.createdDate = dateTime.ToString("yyyy/MM/dd HH:mm:ss"); + } + catch (Exception ex) + { + objDirectMessages.createdDate = DateTime.Now.ToString(); + } + + objDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.recipientId = jobject.SelectToken("event.message_create.target.recipient_id")?.ToString() ?? string.Empty; + objDirectMessages.senderId = jobject.SelectToken("event.message_create.sender_id")?.ToString() ?? string.Empty; + + + /* Previous Response + * objDirectMessages.messageId = ret[0]["id_str"].ToString(); + objDirectMessages.message = ret[0]["text"].ToString(); + objDirectMessages.profileId = objTwitterAccount.twitterUserId; + objDirectMessages.createdDate = DateTime.ParseExact(ret[0]["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(ret[0]["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.recipientId = ret[0]["recipient"]["id_str"].ToString(); + objDirectMessages.recipientProfileUrl = ret[0]["recipient"]["profile_image_url_https"].ToString(); + objDirectMessages.recipientScreenName = ret[0]["recipient"]["screen_name"].ToString(); + objDirectMessages.senderId = ret[0]["sender"]["id_str"].ToString(); + objDirectMessages.senderProfileUrl = ret[0]["sender"]["profile_image_url_https"].ToString(); + objDirectMessages.senderScreenName = ret[0]["sender"]["screen_name"].ToString(); + */ + + objDirectMessages.recipientProfileUrl = recipientImageUrl; + objDirectMessages.recipientScreenName = recipientScreenName; + + objDirectMessages.senderProfileUrl = senderImageUrl; + objDirectMessages.senderScreenName = senderScreenName; + + objDirectMessages.type = Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent; + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + mongorepo.Add(objDirectMessages); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + }); + task.Start(); + } + catch (Exception ex) + { + + } + } + public static void PostTwitterDirectmessage(string toId, string message, string profileId, long UserId, Model.DatabaseRepository dbr, Helper.AppSettings _appSettings, Helper.Cache _redisCache) { - Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages _TwitterDirectMessages = new Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages(); + Domain.Socioboard.Models.Mongo.MongoDirectMessages objDirectMessages = new Domain.Socioboard.Models.Mongo.MongoDirectMessages(); // Domain.Socioboard.Models.TwitterAccount objTwitterAccount = Repositories.TwitterRepository.getTwitterAccount(profileId, _redisCache,dbr); Domain.Socioboard.Models.TwitterAccount objTwitterAccount = new TwitterAccount(); objTwitterAccount = dbr.Single(t => t.userId == UserId && t.twitterUserId.Contains(profileId)); @@ -345,23 +445,71 @@ public static void PostTwitterDirectmessage(string toId, string message, string JArray ret = new JArray(); try { - ret = twtuser.PostDirect_Messages_New(OAuthTwt, message, toId); - _TwitterDirectMessages.messageId = ret[0]["id_str"].ToString(); - _TwitterDirectMessages.message = ret[0]["text"].ToString(); - _TwitterDirectMessages.profileId = objTwitterAccount.twitterUserId; - _TwitterDirectMessages.createdDate = DateTime.ParseExact(ret[0]["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); - _TwitterDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(ret[0]["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); - _TwitterDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); - _TwitterDirectMessages.recipientId = ret[0]["recipient"]["id_str"].ToString(); - _TwitterDirectMessages.recipientProfileUrl = ret[0]["recipient"]["profile_image_url_https"].ToString(); - _TwitterDirectMessages.recipientScreenName = ret[0]["recipient"]["screen_name"].ToString(); - _TwitterDirectMessages.senderId = ret[0]["sender"]["id_str"].ToString(); - _TwitterDirectMessages.senderProfileUrl = ret[0]["sender"]["profile_image_url_https"].ToString(); - _TwitterDirectMessages.senderScreenName = ret[0]["sender"]["screen_name"].ToString(); - _TwitterDirectMessages.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent; - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", _appSettings); - mongorepo.Add(_TwitterDirectMessages); + var objTwitterDirectMessages = new TwitterApiHelper(_appSettings.twitterConsumerKey, _appSettings.twitterConsumerScreatKey, OAuthTwt.AccessToken, OAuthTwt.AccessTokenSecret); + var task = new Task(async () => + { + var response = await objTwitterDirectMessages.DirectMessage(message, toId); + + if (!string.IsNullOrEmpty(response)) + { + + try + { + var jobject = JObject.Parse(response); + + objDirectMessages.messageId = jobject.SelectToken("event.id")?.ToString() ?? string.Empty; + objDirectMessages.message = jobject.SelectToken("event.message_create.message_data.text")?.ToString() ?? string.Empty; + objDirectMessages.profileId = objTwitterAccount.twitterUserId; + + var timestamp = jobject.SelectToken("event.created_timestamp")?.ToString() ?? string.Empty; + objDirectMessages.timeStamp = double.Parse(timestamp); + + try + { + objDirectMessages.createdDate = Domain.Socioboard.Helpers.SBHelper.ConvertFromUnixTimestamp(double.Parse(timestamp)).ToString(); + } + catch (Exception) + { + objDirectMessages.createdDate = DateTime.Now.ToString(); + } + + objDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.recipientId = jobject.SelectToken("event.message_create.target.recipient_id")?.ToString() ?? string.Empty; + objDirectMessages.senderId = jobject.SelectToken("event.message_create.sender_id")?.ToString() ?? string.Empty; + + + /* Previous Response + * objDirectMessages.messageId = ret[0]["id_str"].ToString(); + objDirectMessages.message = ret[0]["text"].ToString(); + objDirectMessages.profileId = objTwitterAccount.twitterUserId; + objDirectMessages.createdDate = DateTime.ParseExact(ret[0]["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(ret[0]["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.recipientId = ret[0]["recipient"]["id_str"].ToString(); + objDirectMessages.recipientProfileUrl = ret[0]["recipient"]["profile_image_url_https"].ToString(); + objDirectMessages.recipientScreenName = ret[0]["recipient"]["screen_name"].ToString(); + objDirectMessages.senderId = ret[0]["sender"]["id_str"].ToString(); + objDirectMessages.senderProfileUrl = ret[0]["sender"]["profile_image_url_https"].ToString(); + objDirectMessages.senderScreenName = ret[0]["sender"]["screen_name"].ToString(); + */ + objDirectMessages.recipientProfileUrl = string.Empty; + objDirectMessages.recipientScreenName = string.Empty; + + objDirectMessages.senderProfileUrl = string.Empty; + objDirectMessages.senderScreenName = string.Empty; + + objDirectMessages.type = Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent; + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + mongorepo.Add(objDirectMessages); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + }); + task.Start(); } catch (Exception ex) { @@ -390,7 +538,7 @@ public static bool FollowAccount(oAuthTwitter OAuth, string Screen_name, string return false; } strdic.Add("follow", "true"); - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!string.IsNullOrEmpty(response)) { IsFollowed = true; @@ -491,47 +639,52 @@ public static bool FollowAccount(oAuthTwitter OAuth, string Screen_name, string } - public static List twitterfollowerslist(string profileId, Model.DatabaseRepository dbr, Helper.AppSettings _appSettings) + public static IEnumerable twitterfollowerslist(string profileId, Model.DatabaseRepository dbr, Helper.AppSettings _appSettings) { - string profileids = profileId; - List lstfollowerlist = new List(); + var profileids = profileId; + var lstfollowerlist = new List(); //List lstGroupprofiles = dbr.Find(t => t.groupId == groupId && t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter).ToList(); //profileids = lstGroupprofiles.Select(t => t.profileId).ToArray(); - List lstAccRepo = dbr.Find(t => profileids.Contains(t.twitterUserId) && t.isActive).ToList(); + var lstAccRepo = dbr.Find(t => profileids.Contains(t.twitterUserId) && t.isActive).ToList(); oAuthTwitter oaut = null; - Users twtUser = new Users(); - foreach (Domain.Socioboard.Models.TwitterAccount itemTwt in lstAccRepo) + var twtUser = new Users(); + foreach (var itemTwt in lstAccRepo) { - oaut = new oAuthTwitter(); - oaut.AccessToken = itemTwt.oAuthToken; - oaut.AccessTokenSecret = itemTwt.oAuthSecret; - oaut.TwitterScreenName = itemTwt.twitterScreenName; - oaut.TwitterUserId = itemTwt.twitterUserId; - oaut.ConsumerKey = _appSettings.twitterConsumerKey; - oaut.ConsumerKeySecret = _appSettings.twitterConsumerScreatKey; - JArray jarresponse = twtUser.Get_Followers_ById(oaut, itemTwt.twitterUserId); - JArray user_data = JArray.Parse(jarresponse[0]["ids"].ToString()); - foreach (var items in user_data) + oaut = new oAuthTwitter { - string userid = items.ToString(); - JArray userprofile = twtUser.Get_Users_LookUp(oaut, userid); + AccessToken = itemTwt.oAuthToken, + AccessTokenSecret = itemTwt.oAuthSecret, + TwitterScreenName = itemTwt.twitterScreenName, + TwitterUserId = itemTwt.twitterUserId, + ConsumerKey = _appSettings.twitterConsumerKey, + ConsumerKeySecret = _appSettings.twitterConsumerScreatKey + }; + var jarresponse = twtUser.Get_Followers_ById(oaut, itemTwt.twitterUserId); + var userData = JArray.Parse(jarresponse[0]["ids"].ToString()); + foreach (var items in userData) + { + var userid = items.ToString(); + var userprofile = twtUser.Get_Users_LookUp(oaut, userid); foreach (var item in userprofile) { - Domain.Socioboard.Models.TwitterMutualFans objTwitterFollowers = new Domain.Socioboard.Models.TwitterMutualFans(); - objTwitterFollowers.screen_name = item["screen_name"].ToString(); - objTwitterFollowers.name = item["name"].ToString(); - objTwitterFollowers.description = item["description"].ToString(); - objTwitterFollowers.followers = item["followers_count"].ToString(); - objTwitterFollowers.following= item["friends_count"].ToString(); - objTwitterFollowers.location = item["location"].ToString(); - objTwitterFollowers.profile_image_url = item["profile_image_url"].ToString(); + var objTwitterFollowers = new TwitterMutualFans + { + screen_name = item["screen_name"].ToString(), + name = item["name"].ToString(), + description = item["description"].ToString(), + followers = item["followers_count"].ToString(), + following = item["friends_count"].ToString(), + location = item["location"].ToString(), + profile_image_url = item["profile_image_url"].ToString() + }; lstfollowerlist.Add(objTwitterFollowers); + yield return objTwitterFollowers; } } } - return lstfollowerlist; + } public static string TwitterBlockUsers(string profileId, string toTwitterUserId, Model.DatabaseRepository dbr, ILogger _logger, Helper.Cache _redisCache, Helper.AppSettings _appSettings) { @@ -725,41 +878,41 @@ public static Domain.Socioboard.Models.TwitterFriendRelation TwitterFrindsRelati } } - public static List twitterConstactSearchlist(string profileId,string contact, Model.DatabaseRepository dbr, Helper.AppSettings _appSettings) + public static List twitterConstactSearchlist(string profileId, string contact, Model.DatabaseRepository dbr, Helper.AppSettings _appSettings) { string profileids = profileId; List lstContact = new List(); Domain.Socioboard.Models.TwitterAccount itemTwt = dbr.Single(t => profileids.Contains(t.twitterUserId)); oAuthTwitter oaut = null; Users twtUser = new Users(); - oaut = new oAuthTwitter(); - oaut.AccessToken = itemTwt.oAuthToken; - oaut.AccessTokenSecret = itemTwt.oAuthSecret; - oaut.TwitterScreenName = itemTwt.twitterScreenName; - oaut.TwitterUserId = itemTwt.twitterUserId; - oaut.ConsumerKey = _appSettings.twitterConsumerKey; - oaut.ConsumerKeySecret = _appSettings.twitterConsumerScreatKey; - JArray jarresponse = twtUser.Get_Users_Search(oaut, contact,"20"); - JArray user_data = JArray.Parse(jarresponse[0]["ids"].ToString()); - foreach (var items in user_data) + oaut = new oAuthTwitter(); + oaut.AccessToken = itemTwt.oAuthToken; + oaut.AccessTokenSecret = itemTwt.oAuthSecret; + oaut.TwitterScreenName = itemTwt.twitterScreenName; + oaut.TwitterUserId = itemTwt.twitterUserId; + oaut.ConsumerKey = _appSettings.twitterConsumerKey; + oaut.ConsumerKeySecret = _appSettings.twitterConsumerScreatKey; + JArray jarresponse = twtUser.Get_Users_Search(oaut, contact, "20"); + JArray user_data = JArray.Parse(jarresponse[0]["ids"].ToString()); + foreach (var items in user_data) + { + string userid = items.ToString(); + JArray userprofile = twtUser.Get_Users_LookUp(oaut, userid); + foreach (var item in userprofile) { - string userid = items.ToString(); - JArray userprofile = twtUser.Get_Users_LookUp(oaut, userid); - foreach (var item in userprofile) - { - Domain.Socioboard.Models.TwitterContactSearch objTwitterContact = new Domain.Socioboard.Models.TwitterContactSearch(); - objTwitterContact.screen_name = item["screen_name"].ToString(); - objTwitterContact.name = item["name"].ToString(); - objTwitterContact.description = item["description"].ToString(); - objTwitterContact.followers = item["followers_count"].ToString(); - objTwitterContact.following = item["friends_count"].ToString(); - objTwitterContact.location = item["location"].ToString(); - objTwitterContact.profile_image_url = item["profile_image_url"].ToString(); - lstContact.Add(objTwitterContact); - } - + Domain.Socioboard.Models.TwitterContactSearch objTwitterContact = new Domain.Socioboard.Models.TwitterContactSearch(); + objTwitterContact.screen_name = item["screen_name"].ToString(); + objTwitterContact.name = item["name"].ToString(); + objTwitterContact.description = item["description"].ToString(); + objTwitterContact.followers = item["followers_count"].ToString(); + objTwitterContact.following = item["friends_count"].ToString(); + objTwitterContact.location = item["location"].ToString(); + objTwitterContact.profile_image_url = item["profile_image_url"].ToString(); + lstContact.Add(objTwitterContact); } - + + } + return lstContact; } @@ -767,8 +920,8 @@ public static Domain.Socioboard.Models.TwitterFriendRelation TwitterFrindsRelati { string profileids = profileId; List UnfollowBackID = new List(); - // List lstGroupprofiles = dbr.Find(t => t.groupId == groupId && t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter).ToList(); - //profileids = lstGroupprofiles.Select(t => t.profileId).ToArray(); + // List lstGroupprofiles = dbr.Find(t => t.groupId == groupId && t.profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter).ToList(); + //profileids = lstGroupprofiles.Select(t => t.profileId).ToArray(); List lstAccRepo = dbr.Find(t => profileids.Contains(t.twitterUserId) && t.isActive).ToList(); oAuthTwitter oaut = null; Users twtUser = new Users(); @@ -792,7 +945,7 @@ public static Domain.Socioboard.Models.TwitterFriendRelation TwitterFrindsRelati var items = user_data.Intersect(user_data_2).ToArray(); var hgh = user_data_2.Intersect(items).ToArray(); // Array itema = user_data.Intersect(items); - Array UnfollowBack_id= user_data_2.Union(items).Except(hgh).ToArray(); + Array UnfollowBack_id = user_data_2.Union(items).Except(hgh).ToArray(); foreach (var ite in UnfollowBack_id) { string userid = ite.ToString(); @@ -856,7 +1009,7 @@ public static Domain.Socioboard.Models.TwitterFriendRelation TwitterFrindsRelati _objLstData.fromName = items["user"]["name"].ToString(); _objLstData.fromScreenName = items["user"]["screen_name"].ToString(); _objLstData.fromLocation = items["user"]["location"].ToString(); - if(_objLstData.fromLocation=="") + if (_objLstData.fromLocation == "") { _objLstData.fromLocation = "NA"; } diff --git a/src/Api.Socioboard/Model/MongoRepository.cs b/src/Api.Socioboard/Model/MongoRepository.cs index 7304c2fa6..f5856ac08 100644 --- a/src/Api.Socioboard/Model/MongoRepository.cs +++ b/src/Api.Socioboard/Model/MongoRepository.cs @@ -136,15 +136,22 @@ public void Delete(System.Linq.Expressions.Expression> expressi var output = await collection.ToListAsync().ConfigureAwait(false); return output; } + public async Task> FindWithRange(Expression> query, SortDefinition sort, int skip, int take) where T : class, new() { var collection = _db.GetCollection(collecionName, settings).Find(query).Sort(sort).Limit(take).Skip(skip); var output = await collection.ToListAsync().ConfigureAwait(false); - return output; - + return output; } + public async Task> FindWithRange(Expression> query, int skip, int take) where T : class, new() + { + var collection = _db.GetCollection(collecionName, settings).Find(query).Limit(take).Skip(skip); + + var output = await collection.ToListAsync().ConfigureAwait(false); + return output; + } public T Single(System.Linq.Expressions.Expression> expression) where T : class, new() @@ -181,9 +188,9 @@ public T Single(System.Linq.Expressions.Expression> expression) } - public void Add(IEnumerable items) where T : class, new() + public void AddRange(IEnumerable collections) where T : class, new() { - foreach (T item in items) + foreach (T item in collections) { Add(item); } diff --git a/src/Api.Socioboard/Repositories/ContentStudioRepository.cs b/src/Api.Socioboard/Repositories/ContentStudioRepository.cs index dfc5c6c58..47c270758 100644 --- a/src/Api.Socioboard/Repositories/ContentStudioRepository.cs +++ b/src/Api.Socioboard/Repositories/ContentStudioRepository.cs @@ -239,9 +239,7 @@ public class ContentStudioRepository } else { - var builder = Builders.Sort; - var sort = builder.Ascending(t => t.title.Contains(keywords)); - var result = mongorepo.Find(t => t.title.Contains(keywords)); + var result = mongorepo.FindWithRange(t => t.title.Contains(keywords) || t.postdescription.Contains(keywords), 0,100); var task = Task.Run(async () => { return await result; diff --git a/src/Api.Socioboard/Repositories/FacebookRepository.cs b/src/Api.Socioboard/Repositories/FacebookRepository.cs index 1925b7462..cbd0f84a2 100644 --- a/src/Api.Socioboard/Repositories/FacebookRepository.cs +++ b/src/Api.Socioboard/Repositories/FacebookRepository.cs @@ -38,27 +38,27 @@ public static int AddFacebookAccount(dynamic profile, Int64 friends, Model.Datab catch { } try { - fbAcc.gender = (Convert.ToString(profile["gender"])); + fbAcc.Gender = (Convert.ToString(profile["gender"])); } catch { } try { - fbAcc.bio = (Convert.ToString(profile["bio"])); + fbAcc.Bio = (Convert.ToString(profile["bio"])); } catch { } try { - fbAcc.about = (Convert.ToString(profile["about"])); + fbAcc.About = (Convert.ToString(profile["about"])); } catch { } try { - fbAcc.coverPic = (Convert.ToString(profile["cover"]["source"])); + fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch { } try { - fbAcc.birthday = (Convert.ToString(profile["birthday"])); + fbAcc.Birthday = (Convert.ToString(profile["birthday"])); } catch { } try @@ -66,8 +66,8 @@ public static int AddFacebookAccount(dynamic profile, Int64 friends, Model.Datab 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"]); + fbAcc.College = Convert.ToString(arry[arry.Count() - 1]["school"]["name"]); + fbAcc.Education = Convert.ToString(arry[arry.Count() - 1]["concentration"]["name"]); } } catch { } @@ -76,8 +76,8 @@ public static int AddFacebookAccount(dynamic profile, Int64 friends, Model.Datab 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"]); + fbAcc.WorkPosition = Convert.ToString(arry[0]["position"]["name"]); + fbAcc.WorkCompany = Convert.ToString(arry[0]["employer"]["name"]); } } catch { } @@ -106,27 +106,27 @@ public static int AddFacebookAccount(dynamic profile, Int64 friends, Model.Datab catch { } try { - fbAcc.gender = (Convert.ToString(profile["gender"])); + fbAcc.Gender = (Convert.ToString(profile["gender"])); } catch { } try { - fbAcc.bio = (Convert.ToString(profile["bio"])); + fbAcc.Bio = (Convert.ToString(profile["bio"])); } catch { } try { - fbAcc.about = (Convert.ToString(profile["about"])); + fbAcc.About = (Convert.ToString(profile["about"])); } catch { } try { - fbAcc.coverPic = (Convert.ToString(profile["cover"]["source"])); + fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch { } try { - fbAcc.birthday = (Convert.ToString(profile["birthday"])); + fbAcc.Birthday = (Convert.ToString(profile["birthday"])); } catch { } try @@ -134,12 +134,12 @@ public static int AddFacebookAccount(dynamic profile, Int64 friends, Model.Datab try { - fbAcc.college = Convert.ToString(profile["education"][0]["school"]["name"]); + fbAcc.College = Convert.ToString(profile["education"][0]["school"]["name"]); } catch { } try { - fbAcc.education = Convert.ToString(profile["education"][0]["concentration"]["name"]); + fbAcc.Education = Convert.ToString(profile["education"][0]["concentration"]["name"]); } catch { } @@ -150,12 +150,12 @@ public static int AddFacebookAccount(dynamic profile, Int64 friends, Model.Datab try { - fbAcc.workPosition = Convert.ToString(profile["work"][0]["position"]["name"]); + fbAcc.WorkPosition = Convert.ToString(profile["work"][0]["position"]["name"]); } catch { } try { - fbAcc.workCompany = Convert.ToString(profile["work"][0]["employer"]["name"]); + fbAcc.WorkCompany = Convert.ToString(profile["work"][0]["employer"]["name"]); } catch { } @@ -218,27 +218,27 @@ public static int ReFacebookAccount(dynamic profile, Int64 friends, Model.Databa catch { } try { - fbAcc.gender = (Convert.ToString(profile["gender"])); + fbAcc.Gender = (Convert.ToString(profile["gender"])); } catch { } try { - fbAcc.bio = (Convert.ToString(profile["bio"])); + fbAcc.Bio = (Convert.ToString(profile["bio"])); } catch { } try { - fbAcc.about = (Convert.ToString(profile["about"])); + fbAcc.About = (Convert.ToString(profile["about"])); } catch { } try { - fbAcc.coverPic = (Convert.ToString(profile["cover"]["source"])); + fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch { } try { - fbAcc.birthday = (Convert.ToString(profile["birthday"])); + fbAcc.Birthday = (Convert.ToString(profile["birthday"])); } catch { } try @@ -246,8 +246,8 @@ public static int ReFacebookAccount(dynamic profile, Int64 friends, Model.Databa 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"]); + fbAcc.College = Convert.ToString(arry[arry.Count() - 1]["school"]["name"]); + fbAcc.Education = Convert.ToString(arry[arry.Count() - 1]["concentration"]["name"]); } } catch { } @@ -256,8 +256,8 @@ public static int ReFacebookAccount(dynamic profile, Int64 friends, Model.Databa 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"]); + fbAcc.WorkPosition = Convert.ToString(arry[0]["position"]["name"]); + fbAcc.WorkCompany = Convert.ToString(arry[0]["employer"]["name"]); } } catch { } @@ -295,7 +295,7 @@ public static int AddFacebookPage(dynamic profile, Model.DatabaseRepository dbr, } try { - fbAcc.coverPic = (Convert.ToString(profile["cover"]["source"])); + fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch (Exception) { @@ -324,7 +324,7 @@ public static int AddFacebookPage(dynamic profile, Model.DatabaseRepository dbr, fbAcc.FbUserName = (Convert.ToString(profile["name"])); try { - fbAcc.coverPic = (Convert.ToString(profile["cover"]["source"])); + fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch (Exception) { @@ -761,17 +761,17 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H try { - Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages _TwitterDirectMessages; + Domain.Socioboard.Models.Mongo.MongoDirectMessages objDirectMessages; dynamic data = FbUser.conversations(AccessToken); foreach (var item in data["data"]) { foreach (var msg_item in item["messages"]["data"]) { - _TwitterDirectMessages = new Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages(); + objDirectMessages = new Domain.Socioboard.Models.Mongo.MongoDirectMessages(); try { - _TwitterDirectMessages.messageId = msg_item["id"].ToString(); + objDirectMessages.messageId = msg_item["id"].ToString(); } catch (Exception ex) { @@ -779,7 +779,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.createdDate = Convert.ToDateTime(msg_item["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.createdDate = Convert.ToDateTime(msg_item["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { @@ -787,7 +787,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.senderId = msg_item["from"]["id"].ToString(); + objDirectMessages.senderId = msg_item["from"]["id"].ToString(); } catch (Exception ex) { @@ -795,7 +795,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.senderScreenName = msg_item["from"]["name"].ToString(); + objDirectMessages.senderScreenName = msg_item["from"]["name"].ToString(); } catch (Exception ex) { @@ -803,7 +803,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.senderProfileUrl = "http://graph.facebook.com/" + _TwitterDirectMessages.senderId + "/picture?type=small"; + objDirectMessages.senderProfileUrl = "http://graph.facebook.com/" + objDirectMessages.senderId + "/picture?type=small"; } catch (Exception ex) { @@ -811,7 +811,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.recipientId = msg_item["to"]["data"][0]["id"].ToString(); + objDirectMessages.recipientId = msg_item["to"]["data"][0]["id"].ToString(); } catch (Exception ex) { @@ -819,7 +819,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.recipientScreenName = msg_item["to"]["data"][0]["name"].ToString(); + objDirectMessages.recipientScreenName = msg_item["to"]["data"][0]["name"].ToString(); } catch (Exception ex) { @@ -827,7 +827,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.recipientProfileUrl = "http://graph.facebook.com/" + _TwitterDirectMessages.recipientId + "/picture?type=small"; + objDirectMessages.recipientProfileUrl = "http://graph.facebook.com/" + objDirectMessages.recipientId + "/picture?type=small"; } catch (Exception ex) { @@ -835,16 +835,16 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.message = msg_item["message"].ToString(); - if (string.IsNullOrEmpty(_TwitterDirectMessages.message)) + objDirectMessages.message = msg_item["message"].ToString(); + if (string.IsNullOrEmpty(objDirectMessages.message)) { if ((msg_item["attachments"]["data"][0]["mime_type"].ToString()).Contains("image")) { - _TwitterDirectMessages.image = msg_item["attachments"]["data"][0]["image_data"]["url"].ToString(); + objDirectMessages.image = msg_item["attachments"]["data"][0]["image_data"]["url"].ToString(); } else { - _TwitterDirectMessages.message = msg_item["attachments"]["data"][0]["name"].ToString(); + objDirectMessages.message = msg_item["attachments"]["data"][0]["name"].ToString(); } } } @@ -854,24 +854,24 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } try { - _TwitterDirectMessages.image = msg_item["shares"]["data"][0]["link"].ToString(); + objDirectMessages.image = msg_item["shares"]["data"][0]["link"].ToString(); } catch (Exception ex) { _logger.LogError("getPageConversations = > getPageConversations = > " + ex.Message); } - if (_TwitterDirectMessages.senderId == ProfileId) + if (objDirectMessages.senderId == ProfileId) { - _TwitterDirectMessages.type = Domain.Socioboard.Enum.TwitterMessageType.FacebookPageDirectMessageSent; + objDirectMessages.type = Domain.Socioboard.Enum.MessageType.FacebookPageDirectMessageSent; } else { - _TwitterDirectMessages.type = Domain.Socioboard.Enum.TwitterMessageType.FacebookPagDirectMessageReceived; + objDirectMessages.type = Domain.Socioboard.Enum.MessageType.FacebookPagDirectMessageReceived; } //code to add facebook page conversations - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", settings); - var ret = mongorepo.Find(t => t.messageId == _TwitterDirectMessages.messageId); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", settings); + var ret = mongorepo.Find(t => t.messageId == objDirectMessages.messageId); var task = Task.Run(async () => { return await ret; @@ -883,7 +883,7 @@ public static void SavePageConversations(string AccessToken, string ProfileId, H } else { - mongorepo.Add(_TwitterDirectMessages); + mongorepo.Add(objDirectMessages); } } } @@ -900,18 +900,18 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He try { dynamic data = FbUser.notifications(AccessToken); - Domain.Socioboard.Models.Mongo.MongoTwitterMessage _InboxMessages; + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel; foreach (var item in data["data"]) { - _InboxMessages = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); + objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); - _InboxMessages.profileId = ProfileId; - _InboxMessages.type = Domain.Socioboard.Enum.TwitterMessageType.FacebookPageNotification; - _InboxMessages.messageTimeStamp = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow); + objMessageModel.profileId = ProfileId; + objMessageModel.type = Domain.Socioboard.Enum.MessageType.FacebookPageNotification; + objMessageModel.messageTimeStamp = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow); try { - _InboxMessages.twitterMsg = item["title"].ToString(); + objMessageModel.Message = item["title"].ToString(); } catch (Exception ex) { @@ -919,7 +919,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } try { - _InboxMessages.messageId = item["id"].ToString(); + objMessageModel.messageId = item["id"].ToString(); } catch (Exception ex) { @@ -927,7 +927,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } try { - _InboxMessages.fromId = item["from"]["id"].ToString(); + objMessageModel.fromId = item["from"]["id"].ToString(); } catch (Exception ex) { @@ -935,8 +935,8 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } try { - _InboxMessages.fromName = item["from"]["name"].ToString(); - _InboxMessages.fromScreenName = item["from"]["name"].ToString(); + objMessageModel.fromName = item["from"]["name"].ToString(); + objMessageModel.fromScreenName = item["from"]["name"].ToString(); } catch (Exception ex) { @@ -944,7 +944,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } try { - _InboxMessages.fromProfileUrl = "http://graph.facebook.com/" + _InboxMessages.fromId + "/picture?type=small"; + objMessageModel.fromProfileUrl = "http://graph.facebook.com/" + objMessageModel.fromId + "/picture?type=small"; } catch (Exception ex) { @@ -952,7 +952,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } try { - _InboxMessages.RecipientId = item["to"]["id"].ToString(); + objMessageModel.RecipientId = item["to"]["id"].ToString(); } catch (Exception ex) { @@ -960,7 +960,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } try { - _InboxMessages.RecipientName = item["to"]["name"].ToString(); + objMessageModel.RecipientName = item["to"]["name"].ToString(); } catch (Exception ex) { @@ -968,7 +968,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He } //try //{ - // _InboxMessages.r = "http://graph.facebook.com/" + _InboxMessages.RecipientId + "/picture?type=small"; + // objMessageModel.r = "http://graph.facebook.com/" + objMessageModel.RecipientId + "/picture?type=small"; //} //catch (Exception ex) //{ @@ -976,14 +976,14 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He //} try { - _InboxMessages.messageDate = Convert.ToDateTime(item["created_time"].ToString()); + objMessageModel.messageDate = Convert.ToDateTime(item["created_time"].ToString()); } catch (Exception ex) { _logger.LogError("Facebook.asmx = > getUserNotifications = > " + ex.Message); } - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", settings); - var ret = mongorepo.Find(t => t.profileId == _InboxMessages.profileId && t.messageId == _InboxMessages.messageId); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", settings); + var ret = mongorepo.Find(t => t.profileId == objMessageModel.profileId && t.messageId == objMessageModel.messageId); var task = Task.Run(async () => { return await ret; @@ -991,7 +991,7 @@ public static void SavePageNotification(string AccessToken, string ProfileId, He int count = task.Result.Count; if (count < 1) { - mongorepo.Add(_InboxMessages); + mongorepo.Add(objMessageModel); } } } @@ -1221,7 +1221,7 @@ public static void SaveFacebookPageTaggedDetails(string accesstoken, string face _InboxMessages = new Domain.Socioboard.Models.Mongo.FacebookPagePromotionDetails(); _InboxMessages.ProfileId = facebookid; - _InboxMessages.type = Domain.Socioboard.Enum.FacebookPagePromotion.tagged; + _InboxMessages.type = Domain.Socioboard.Enum.FacebookPagePromotion.Tagged; _InboxMessages.EntryDate = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow); try { @@ -1326,7 +1326,7 @@ public static void SaveFacebookPagePromotionalDetails(string accesstoken, string _InboxMessages = new Domain.Socioboard.Models.Mongo.FacebookPagePromotionDetails(); _InboxMessages.ProfileId = facebookid; - _InboxMessages.type = Domain.Socioboard.Enum.FacebookPagePromotion.promotable_posts; + _InboxMessages.type = Domain.Socioboard.Enum.FacebookPagePromotion.PromotablePosts; _InboxMessages.EntryDate = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow); try { @@ -1428,7 +1428,7 @@ public static string AddFbPostComments(string postid, string AccessToken, Helper { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; - dynamic post = FbUser.getPostComments(AccessToken, postid); + dynamic post = FbUser.GetPostComments(AccessToken, postid); foreach (var item in post["data"]) { @@ -1685,27 +1685,24 @@ public static List FbPostComments(string postid, dynamic pos public static List GetTopFacebookFeed(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings, int skip, int count) { - List lstfacebookfeed = new List(); - MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed", settings); - var builder = Builders.Sort; - - + var lstfacebookfeed = new List(); + var mongorepo = new MongoRepository("MongoFacebookFeed", settings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.FeedDate); - - var result = mongorepo.FindWithRange(t => t.ProfileId.Equals(profileId), sort, skip, 20); - var task = Task.Run(async () => - { - return await result; - }); - IList lstFbFeeds = null; + var result =mongorepo.FindWithRange(t => t.ProfileId.Equals(profileId), sort, skip, 20); + var task = Task.Run(async () => await result); + + IList lstFbFeeds; try { lstFbFeeds = task.Result.ToList(); } catch (Exception ex) { - + lstFbFeeds = new List(); } + + // lstFbFeeds = lstFbFeeds.OrderByDescending(t => t.EntryDate).ToList(); // foreach (var item in lstFbFeeds)//sortt.ToList()) foreach (var item in lstFbFeeds) @@ -2011,7 +2008,7 @@ public static string PostFacebookComment(Model.DatabaseRepository dbr, string me { lstFbAcc = inMemFbAcc; } - string commentId = FbUser.postComments(lstFbAcc.AccessToken, postId, message); + string commentId = FbUser.PostComments(lstFbAcc.AccessToken, postId, message); JObject tempCommentId = JObject.Parse(commentId); if (commentId.Contains("Invalid Access Token")) { @@ -2107,6 +2104,10 @@ public static void UpdatePageShareathon(Domain.Socioboard.Models.Facebookaccount { return await ret; }); + + if (task.Result == null) + return; + int count = task.Result.Count; if (count > 0) { @@ -2127,6 +2128,10 @@ public static void UpdateGroupShareathon(Domain.Socioboard.Models.Facebookaccoun { return await ret1; }); + + if (task1.Result == null) + return; + int count1 = task1.Result.Count; if (count1 > 0) { @@ -2147,6 +2152,10 @@ public static void UpdatePageshareathonPage(Domain.Socioboard.Models.Facebookacc { return await ret; }); + + if (task.Result == null) + return; + int count = task.Result.Count; if (count > 0) { @@ -2167,6 +2176,10 @@ public static void UpdateGroupShareathonPage(Domain.Socioboard.Models.Facebookac { return await ret1; }); + + if (task1.Result == null) + return; + int count1 = task1.Result.Count; if (count1 > 0) { @@ -2188,6 +2201,10 @@ public static void UpdateDeletesPagehreathon(string profileId, Helper.AppSetting { return await ret; }); + + if (task.Result == null) + return; + int count = task.Result.Count; if (count > 0) { @@ -2204,6 +2221,10 @@ public static void UpadteDeletesGroupShareathon(string profileId, Helper.AppSett { return await ret; }); + + if (task1.Result == null) + return; + int count1 = task1.Result.Count; if (count1 > 0) { @@ -2248,6 +2269,10 @@ public static void UpdateDeleteLinkShareathon(string Facebookpageid, long userId return await ret; }); + + if (task.Result == null) + return; + LinkShareathon _linkshareathon = task.Result.ToList().First(); //var builders = Builders.Filter; //FilterDefinition filter = builders.Eq("strId", _linkshareathon.strId); @@ -2270,6 +2295,10 @@ public static void DeleteFacebookPassChange(string profileId, long userId, Help { return await ret; }); + + if (task.Result == null) + return; + int count = task.Result.Count; if (count > 0) { diff --git a/src/Api.Socioboard/Repositories/GroupMembersRepository.cs b/src/Api.Socioboard/Repositories/GroupMembersRepository.cs index 724f50925..38f949f2a 100644 --- a/src/Api.Socioboard/Repositories/GroupMembersRepository.cs +++ b/src/Api.Socioboard/Repositories/GroupMembersRepository.cs @@ -19,6 +19,7 @@ public static class GroupMembersRepository } } catch { } + List groupMembers = dbr.Find(t => t.groupid == groupId).ToList(); _redisCache.Set(Domain.Socioboard.Consatants.SocioboardConsts.CacheGroupMembers + groupId, groupMembers); return groupMembers; @@ -56,19 +57,29 @@ public static class GroupMembersRepository return groupMembers; } - public static int createGroupMember(long groupId, User user, Helper.Cache _redisCache, Model.DatabaseRepository dbr) + /// + /// To add the member to the specified group + /// + /// group Id + /// user details + /// + /// Database respository object + /// + public static int CreateGroupMember(long groupId, User user, Helper.Cache redisCache, Model.DatabaseRepository dbr) { - Domain.Socioboard.Models.Groupmembers grpMember = new Domain.Socioboard.Models.Groupmembers(); - grpMember.groupid = groupId; - grpMember.email = user.EmailId; - grpMember.firstName = user.FirstName; - grpMember.lastName = user.LastName; - grpMember.memberStatus = Domain.Socioboard.Enum.GroupMemberStatus.Accepted; - grpMember.profileImg = user.ProfilePicUrl; - grpMember.userId = user.Id; - grpMember.memberCode = "Admin"; - grpMember.isAdmin = true; - return dbr.Add(grpMember); + var grpMember = new Groupmembers + { + groupid = groupId, + email = user.EmailId, + firstName = user.FirstName, + lastName = user.LastName, + memberStatus = Domain.Socioboard.Enum.GroupMemberStatus.Accepted, + profileImg = user.ProfilePicUrl, + userId = user.Id, + memberCode = "Admin", + isAdmin = true + }; + return dbr.Add(grpMember); } public static List getGroupadmin(long groupId, Helper.Cache _redisCache, Model.DatabaseRepository dbr) diff --git a/src/Api.Socioboard/Repositories/InstagramRepository.cs b/src/Api.Socioboard/Repositories/InstagramRepository.cs index b1b79f4ce..7160fec68 100644 --- a/src/Api.Socioboard/Repositories/InstagramRepository.cs +++ b/src/Api.Socioboard/Repositories/InstagramRepository.cs @@ -409,7 +409,7 @@ public static void GetInstagramSelfFeeds(string instagramId, string accessToken, public static void GetInstagramFollowing(string profile_id, string access_token, int status,Helper.AppSettings _appSettings) { - Domain.Socioboard.Models.Mongo.MongoTwitterMessage _MongoTwitterMessage = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); JObject post_data = new JObject(); string url = "https://api.instagram.com/v1/users/self/follows?access_token=" + access_token + "&count=100"; bool hasData = true; @@ -442,24 +442,24 @@ public static void GetInstagramFollowing(string profile_id, string access_token, string full_name = item["full_name"].ToString(); DateTime CreatedTime = DateTime.Now; - _MongoTwitterMessage.id = ObjectId.GenerateNewId(); - _MongoTwitterMessage.messageId = ""; - _MongoTwitterMessage.profileId = profile_id; - _MongoTwitterMessage.fromId = id; - _MongoTwitterMessage.fromName = ""; - _MongoTwitterMessage.RecipientId = profile_id; - _MongoTwitterMessage.messageId = id; - _MongoTwitterMessage.RecipientName = full_name; - _MongoTwitterMessage.twitterMsg = ""; - _MongoTwitterMessage.fromProfileUrl = ""; - _MongoTwitterMessage.RecipientName = ""; - _MongoTwitterMessage.type = Domain.Socioboard.Enum.TwitterMessageType.InstagramFollowing; - _MongoTwitterMessage.messageDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); - _MongoTwitterMessage.FollowerCount = 0; - _MongoTwitterMessage.FollowingCount = 0; - _MongoTwitterMessage.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var ret = mongorepo.Find(t => t.RecipientId == _MongoTwitterMessage.RecipientId && t.fromId == _MongoTwitterMessage.fromId && t.type == Domain.Socioboard.Enum.TwitterMessageType.InstagramFollowing); + objMessageModel.id = ObjectId.GenerateNewId(); + objMessageModel.messageId = ""; + objMessageModel.profileId = profile_id; + objMessageModel.fromId = id; + objMessageModel.fromName = ""; + objMessageModel.RecipientId = profile_id; + objMessageModel.messageId = id; + objMessageModel.RecipientName = full_name; + objMessageModel.Message = ""; + objMessageModel.fromProfileUrl = ""; + objMessageModel.RecipientName = ""; + objMessageModel.type = Domain.Socioboard.Enum.MessageType.InstagramFollowing; + objMessageModel.messageDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objMessageModel.FollowerCount = 0; + objMessageModel.FollowingCount = 0; + objMessageModel.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var ret = mongorepo.Find(t => t.RecipientId == objMessageModel.RecipientId && t.fromId == objMessageModel.fromId && t.type == Domain.Socioboard.Enum.MessageType.InstagramFollowing); var task = Task.Run(async () => { return await ret; }); @@ -468,7 +468,7 @@ public static void GetInstagramFollowing(string profile_id, string access_token, int count = task.Result.Count; if (count < 1) { - mongorepo.Add(_MongoTwitterMessage); + mongorepo.Add(objMessageModel); } } } @@ -492,7 +492,7 @@ public static void GetInstagramFollowing(string profile_id, string access_token, public static void GetInstagramFollower(string profile_id, string access_token, int status, Helper.AppSettings _appSettings) { - Domain.Socioboard.Models.Mongo.MongoTwitterMessage _MongoTwitterMessage = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); JObject post_data = new JObject(); string url = "https://api.instagram.com/v1/users/self/followed-by?access_token=" + access_token + "&cout=100"; bool hasData = true; @@ -523,21 +523,21 @@ public static void GetInstagramFollower(string profile_id, string access_token, string full_name = item["full_name"].ToString(); string image_url = item["profile_picture"].ToString(); DateTime CreatedTime = DateTime.UtcNow; - _MongoTwitterMessage.id = ObjectId.GenerateNewId(); - _MongoTwitterMessage.profileId = profile_id; - _MongoTwitterMessage.messageId = id; - _MongoTwitterMessage.fromId = id; - _MongoTwitterMessage.fromName = user_name; - _MongoTwitterMessage.RecipientId = profile_id; - _MongoTwitterMessage.RecipientName = ""; - _MongoTwitterMessage.fromProfileUrl = image_url; - _MongoTwitterMessage.type = Domain.Socioboard.Enum.TwitterMessageType.InstagramFollower; - _MongoTwitterMessage.FollowerCount = 0; - _MongoTwitterMessage.FollowingCount = 0; - _MongoTwitterMessage.readStatus = status; - _MongoTwitterMessage.messageTimeStamp = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow); - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var ret = mongorepo.Find(t => t.RecipientId == _MongoTwitterMessage.RecipientId && t.fromId == _MongoTwitterMessage.fromId && t.type == Domain.Socioboard.Enum.TwitterMessageType.InstagramFollower); + objMessageModel.id = ObjectId.GenerateNewId(); + objMessageModel.profileId = profile_id; + objMessageModel.messageId = id; + objMessageModel.fromId = id; + objMessageModel.fromName = user_name; + objMessageModel.RecipientId = profile_id; + objMessageModel.RecipientName = ""; + objMessageModel.fromProfileUrl = image_url; + objMessageModel.type = Domain.Socioboard.Enum.MessageType.InstagramFollower; + objMessageModel.FollowerCount = 0; + objMessageModel.FollowingCount = 0; + objMessageModel.readStatus = status; + objMessageModel.messageTimeStamp = Helper.DateExtension.ConvertToUnixTimestamp(DateTime.UtcNow); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var ret = mongorepo.Find(t => t.RecipientId == objMessageModel.RecipientId && t.fromId == objMessageModel.fromId && t.type == Domain.Socioboard.Enum.MessageType.InstagramFollower); var task = Task.Run(async () => { return await ret; }); @@ -546,7 +546,7 @@ public static void GetInstagramFollower(string profile_id, string access_token, int count = task.Result.Count; if (count < 1) { - mongorepo.Add(_MongoTwitterMessage); + mongorepo.Add(objMessageModel); } } } diff --git a/src/Api.Socioboard/Repositories/TwitterReportsRepository.cs b/src/Api.Socioboard/Repositories/TwitterReportsRepository.cs index 27551106f..189f8c764 100644 --- a/src/Api.Socioboard/Repositories/TwitterReportsRepository.cs +++ b/src/Api.Socioboard/Repositories/TwitterReportsRepository.cs @@ -18,18 +18,18 @@ public class TwitterReportsRepository { public static void CreateTodayReports(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) { - List lstTwitterMessages = TwitterReportsRepository.GetTodayMessages(profileId, userId, _redisCache, settings); - List lstTwitterDirectMessages = TwitterReportsRepository.GetTodayDirectMessages(profileId, userId, _redisCache, settings); + List lstTwitterMessages = TwitterReportsRepository.GetTodayMessages(profileId, userId, _redisCache, settings); + List lstTwitterDirectMessages = TwitterReportsRepository.GetTodayDirectMessages(profileId, userId, _redisCache, settings); MongoRepository mongorepo = new MongoRepository("MongoTwitterDailyReports", settings); MongoTwitterDailyReports todayReports = new MongoTwitterDailyReports(); - todayReports.mentions = lstTwitterMessages.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention); - todayReports.newFollowers = lstTwitterMessages.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower); - todayReports.retweets = lstTwitterMessages.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet); + todayReports.mentions = lstTwitterMessages.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterMention); + todayReports.newFollowers = lstTwitterMessages.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterFollower); + todayReports.retweets = lstTwitterMessages.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet); todayReports.timeStamp = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); - //todayReports.newFollowing = lstTwitterMessages.Count(t=>t.type == Domain.Socioboard.Enum.TwitterMessageType.) - todayReports.directMessagesReceived = lstTwitterDirectMessages.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived); - todayReports.directMessagesSent = lstTwitterDirectMessages.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent); + //todayReports.newFollowing = lstTwitterMessages.Count(t=>t.type == Domain.Socioboard.Enum.MessageType.) + todayReports.directMessagesReceived = lstTwitterDirectMessages.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived); + todayReports.directMessagesSent = lstTwitterDirectMessages.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent); todayReports.profileId = profileId; todayReports.id = ObjectId.GenerateNewId(); DateTime dayStart = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0, DateTimeKind.Utc); @@ -57,31 +57,31 @@ public static void CreateTodayReports(string profileId, long userId, Helper.Cach } } - private static List GetTodayMessages(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) + private static List GetTodayMessages(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", settings); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", settings); DateTime dayStart = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0, DateTimeKind.Utc); DateTime dayEnd = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59, DateTimeKind.Utc); - var result = mongorepo.Find(t => (t.messageTimeStamp > SBHelper.ConvertToUnixTimestamp(dayStart)) && (t.messageTimeStamp < SBHelper.ConvertToUnixTimestamp(dayEnd))); + var result = mongorepo.Find(t => (t.messageTimeStamp > SBHelper.ConvertToUnixTimestamp(dayStart)) && (t.messageTimeStamp < SBHelper.ConvertToUnixTimestamp(dayEnd))); var task = Task.Run(async () => { return await result; }); - IList lstTwtMessages = task.Result; + IList lstTwtMessages = task.Result; return lstTwtMessages.ToList(); } - private static List GetTodayDirectMessages(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) + private static List GetTodayDirectMessages(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) { - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", settings); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", settings); DateTime dayStart = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0, DateTimeKind.Utc); DateTime dayEnd = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59, DateTimeKind.Utc); - var result = mongorepo.Find(t => (t.timeStamp > SBHelper.ConvertToUnixTimestamp(dayStart)) && (t.timeStamp < SBHelper.ConvertToUnixTimestamp(dayEnd))); + var result = mongorepo.Find(t => (t.timeStamp > SBHelper.ConvertToUnixTimestamp(dayStart)) && (t.timeStamp < SBHelper.ConvertToUnixTimestamp(dayEnd))); var task = Task.Run(async () => { return await result; }); - IList lstTwtMessages = task.Result; + IList lstTwtMessages = task.Result; return lstTwtMessages.ToList(); } @@ -112,15 +112,15 @@ public static List GetTwitterMessageReports(string pro public static List GetTopFiveFans(string profileId, int daysCount, Helper.Cache _redisCache, Helper.AppSettings settings) { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", settings); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", settings); DateTime dayStart = new DateTime(DateTime.UtcNow.AddDays(-1 * daysCount).Year, DateTime.UtcNow.AddDays(-1 * daysCount).Month, DateTime.UtcNow.AddDays(-1 * daysCount).Day, 0, 0, 0, DateTimeKind.Utc); DateTime dayEnd = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59, DateTimeKind.Utc); - var result = mongorepo.Find(t => (t.messageTimeStamp > SBHelper.ConvertToUnixTimestamp(dayStart)) && (t.messageTimeStamp < SBHelper.ConvertToUnixTimestamp(dayEnd)) && t.profileId==profileId && (t.type==Domain.Socioboard.Enum.TwitterMessageType.TwitterMention|| t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet)); + var result = mongorepo.Find(t => (t.messageTimeStamp > SBHelper.ConvertToUnixTimestamp(dayStart)) && (t.messageTimeStamp < SBHelper.ConvertToUnixTimestamp(dayEnd)) && t.profileId==profileId && (t.type==Domain.Socioboard.Enum.MessageType.TwitterMention|| t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet)); var task = Task.Run(async () => { return await result; }); - IList lstTwtMessages = task.Result; + IList lstTwtMessages = task.Result; List lstTwtTopFans = lstTwtMessages.GroupBy(t => t.fromId).Select(g => new TwitterFan(g.ToList())).OrderBy(x=>x.totalCount).Take(5).ToList(); return lstTwtTopFans; diff --git a/src/Api.Socioboard/Repositories/TwitterRepository.cs b/src/Api.Socioboard/Repositories/TwitterRepository.cs index 701c675b1..fb8781298 100644 --- a/src/Api.Socioboard/Repositories/TwitterRepository.cs +++ b/src/Api.Socioboard/Repositories/TwitterRepository.cs @@ -577,25 +577,25 @@ public static string DeleteProfile(Model.DatabaseRepository dbr, string profileI return lstFbFeeds.ToList(); } - public static List GetUserTweets(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) + public static List GetUserTweets(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) { - List inMemFeeds = _redisCache.Get>(Domain.Socioboard.Consatants.SocioboardConsts.CacheTwitterUser100Tweets + profileId); + List inMemFeeds = _redisCache.Get>(Domain.Socioboard.Consatants.SocioboardConsts.CacheTwitterUser100Tweets + profileId); if (inMemFeeds != null) { return inMemFeeds; } else { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", settings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", settings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.messageDate); - var result = mongorepo.FindWithRange(t => t.profileId.Equals(profileId), sort, 0, 100); + var result = mongorepo.FindWithRange(t => t.profileId.Equals(profileId), sort, 0, 100); var task = Task.Run(async () => { return await result; }); - IList TwtTweets = task.Result; - IList lstTwtTweets = TwtTweets.Where(t=>t.type==TwitterMessageType.TwitterUsertweet).ToList(); + IList TwtTweets = task.Result; + IList lstTwtTweets = TwtTweets.Where(t=>t.type==MessageType.TwitterUsertweet).ToList(); if (lstTwtTweets != null) { @@ -608,24 +608,24 @@ public static string DeleteProfile(Model.DatabaseRepository dbr, string profileI } } - public static List GetUserNotifications(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) + public static List GetUserNotifications(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) { - List inMemFeeds = _redisCache.Get>(Domain.Socioboard.Consatants.SocioboardConsts.CacheTwitterUser100Notifications + profileId); + List inMemFeeds = _redisCache.Get>(Domain.Socioboard.Consatants.SocioboardConsts.CacheTwitterUser100Notifications + profileId); if (inMemFeeds != null) { return inMemFeeds; } else { - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", settings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", settings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.messageDate); - var result = mongorepo.FindWithRange(t => t.profileId.Equals(profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower), sort, 0, 100); + var result = mongorepo.FindWithRange(t => t.profileId.Equals(profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterMention || t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet || t.type == Domain.Socioboard.Enum.MessageType.TwitterFollower), sort, 0, 100); var task = Task.Run(async () => { return await result; }); - IList lstTwtTweets = task.Result; + IList lstTwtTweets = task.Result; if (lstTwtTweets != null) { @@ -638,24 +638,24 @@ public static string DeleteProfile(Model.DatabaseRepository dbr, string profileI } } - public static List GetTwitterDirectMessages(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) + public static List GetTwitterDirectMessages(string profileId, long userId, Helper.Cache _redisCache, Helper.AppSettings settings) { - List inMemFeeds = _redisCache.Get>(Domain.Socioboard.Consatants.SocioboardConsts.CacheTwitterUser100DirectMessage + profileId); + List inMemFeeds = _redisCache.Get>(Domain.Socioboard.Consatants.SocioboardConsts.CacheTwitterUser100DirectMessage + profileId); if (inMemFeeds != null) { return inMemFeeds; } else { - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", settings); - var builder = Builders.Sort; + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", settings); + var builder = Builders.Sort; var sort = builder.Descending(t => t.createdDate); - var result = mongorepo.FindWithRange(t => t.senderId.Equals(profileId) && (t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent || t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived), sort, 0, 100); + var result = mongorepo.FindWithRange(t => t.senderId.Equals(profileId) && (t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent || t.type == Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived), sort, 0, 100); var task = Task.Run(async () => { return await result; }); - IList lstTwtTweets = task.Result; + IList lstTwtTweets = task.Result; if (lstTwtTweets != null) { @@ -725,14 +725,14 @@ public static string GetIncommingMessage(long userId, long groupId, Model.Databa } profileids = lstGroupprofiles.Select(t => t.profileId).ToArray(); - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", _appSettings); - //var ret = mongorepo.Find(t => profileids.Contains(t.recipientId)); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + //var ret = mongorepo.Find(t => profileids.Contains(t.recipientId)); //var task = Task.Run(async () => //{ // return await ret; //}); //long TwitterFollowerCount = task.Result.Count; - long TwitterFollowerCount = mongorepo.Counts(t => profileids.Contains(t.recipientId)); + long TwitterFollowerCount = mongorepo.Counts(t => profileids.Contains(t.recipientId)); if (TwitterFollowerCount > 1000000) { long r = TwitterFollowerCount % 1000000; @@ -770,16 +770,16 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu _logger.LogError("tl.Get_Statuses_Mentions_Timeline ex.StackTrace >> " + ex.StackTrace); _logger.LogError("tl.Get_Statuses_Mentions_Timeline ex.Message >> " + ex.Message); } - Domain.Socioboard.Models.Mongo.MongoTwitterMessage objTwitterMessage = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); foreach (var item in data) { - //objTwitterMessage.UserId = Guid.Parse(UserId); - objTwitterMessage.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterMention; - objTwitterMessage.id = MongoDB.Bson.ObjectId.GenerateNewId(); + //objMessageModel.UserId = Guid.Parse(UserId); + objMessageModel.type = Domain.Socioboard.Enum.MessageType.TwitterMention; + objMessageModel.id = MongoDB.Bson.ObjectId.GenerateNewId(); try { - objTwitterMessage.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -788,8 +788,8 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu try { const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; - objTwitterMessage.messageDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); - objTwitterMessage.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objMessageModel.messageDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objMessageModel.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); } catch (Exception ex) { @@ -797,7 +797,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu } try { - objTwitterMessage.twitterMsg = item["text"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.Message = item["text"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -806,7 +806,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu try { - objTwitterMessage.fromId = item["user"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromId = item["user"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -815,7 +815,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu try { - objTwitterMessage.fromScreenName = item["user"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromScreenName = item["user"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -824,7 +824,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu try { - objTwitterMessage.fromProfileUrl = item["user"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromProfileUrl = item["user"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -833,7 +833,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu try { - objTwitterMessage.inReplyToStatusUserId = item["in_reply_to_status_id_str"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.inReplyToStatusUserId = item["in_reply_to_status_id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) @@ -843,7 +843,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu try { - objTwitterMessage.sourceUrl = item["source"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.sourceUrl = item["source"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -851,7 +851,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu } try { - objTwitterMessage.profileId = profileId; + objMessageModel.profileId = profileId; } catch (Exception ex) { @@ -859,7 +859,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu } try { - objTwitterMessage.screenName = item["user"]["screen_name"].ToString(); + objMessageModel.screenName = item["user"]["screen_name"].ToString(); } catch (Exception ex) { @@ -867,7 +867,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu } try { - objTwitterMessage.RecipientId = profileId; + objMessageModel.RecipientId = profileId; } catch (Exception ex) { @@ -875,7 +875,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu } try { - objTwitterMessage.RecipientName = screenName; + objMessageModel.RecipientName = screenName; } catch (Exception ex) { @@ -883,8 +883,8 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu } - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var ret = mongorepo.Find(t => t.RecipientId == objTwitterMessage.RecipientId && t.messageId == objTwitterMessage.messageId && t.profileId == profileId); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var ret = mongorepo.Find(t => t.RecipientId == objMessageModel.RecipientId && t.messageId == objMessageModel.messageId && t.profileId == profileId); var task = Task.Run(async () => { return await ret; @@ -892,7 +892,7 @@ private static void SaveTwitterMessages(string profileId, string screenName, oAu int count = task.Result.Count; if (count < 1) { - mongorepo.Add(objTwitterMessage); + mongorepo.Add(objMessageModel); } } @@ -921,19 +921,19 @@ private static void SaveUserRetweets(string profileId, oAuthTwitter oAuth, ILogg _logger.LogError("twtuser.GetStatuses_Retweet_Of_Me ex.StackTrace >> " + ex.StackTrace); _logger.LogError("twtuser.GetStatuses_Retweet_Of_Me ex.Message >> " + ex.Message); } - Domain.Socioboard.Models.Mongo.MongoTwitterMessage objTwitterMessage = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); foreach (var item in Retweet) { try { - objTwitterMessage.profileId = profileId; - objTwitterMessage.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet; + objMessageModel.profileId = profileId; + objMessageModel.type = Domain.Socioboard.Enum.MessageType.TwitterRetweet; try { const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; - objTwitterMessage.messageDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); - objTwitterMessage.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objMessageModel.messageDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objMessageModel.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); } catch (Exception ex) { @@ -941,62 +941,62 @@ private static void SaveUserRetweets(string profileId, oAuthTwitter oAuth, ILogg } try { - objTwitterMessage.messageId = item["id_str"].ToString(); + objMessageModel.messageId = item["id_str"].ToString(); } catch (Exception ex) { - objTwitterMessage.messageId = item["id"].ToString(); + objMessageModel.messageId = item["id"].ToString(); } try { - objTwitterMessage.twitterMsg = item["text"].ToString(); + objMessageModel.Message = item["text"].ToString(); } catch (Exception ex) { } try { - objTwitterMessage.RecipientId = item["user"]["id_str"].ToString(); + objMessageModel.RecipientId = item["user"]["id_str"].ToString(); } catch (Exception ex) { } try { - objTwitterMessage.RecipientName = item["user"]["screen_name"].ToString(); + objMessageModel.RecipientName = item["user"]["screen_name"].ToString(); } catch (Exception ex) { } Tweet _tweet = new Tweet(); - JArray retweet_data = _tweet.Get_Statuses_RetweetsById(oAuth, objTwitterMessage.messageId); + JArray retweet_data = _tweet.Get_Statuses_RetweetsById(oAuth, objMessageModel.messageId); foreach (var item_retweet in retweet_data) { try { - objTwitterMessage.fromId = item_retweet["user"]["id_str"].ToString(); + objMessageModel.fromId = item_retweet["user"]["id_str"].ToString(); } catch (Exception ex) { - objTwitterMessage.fromId = item_retweet["user"]["id"].ToString(); + objMessageModel.fromId = item_retweet["user"]["id"].ToString(); } try { - objTwitterMessage.fromName = item_retweet["user"]["screen_name"].ToString(); + objMessageModel.fromName = item_retweet["user"]["screen_name"].ToString(); } catch (Exception ex) { } try { - objTwitterMessage.fromProfileUrl = item_retweet["user"]["profile_image_url"].ToString(); + objMessageModel.fromProfileUrl = item_retweet["user"]["profile_image_url"].ToString(); } catch (Exception ex) { - objTwitterMessage.fromProfileUrl = item_retweet["user"]["profile_image_url_https"].ToString(); + objMessageModel.fromProfileUrl = item_retweet["user"]["profile_image_url_https"].ToString(); } @@ -1007,8 +1007,8 @@ private static void SaveUserRetweets(string profileId, oAuthTwitter oAuth, ILogg { } - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var ret = mongorepo.Find(t => t.RecipientId == objTwitterMessage.RecipientId && t.messageId == objTwitterMessage.messageId && t.profileId == profileId); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var ret = mongorepo.Find(t => t.RecipientId == objMessageModel.RecipientId && t.messageId == objMessageModel.messageId && t.profileId == profileId); var task = Task.Run(async () => { return await ret; @@ -1016,7 +1016,7 @@ private static void SaveUserRetweets(string profileId, oAuthTwitter oAuth, ILogg int count = task.Result.Count; if (count < 1) { - mongorepo.Add(objTwitterMessage); + mongorepo.Add(objMessageModel); } } @@ -1036,12 +1036,12 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi JArray Timeline = twtuser.GetStatuses_User_Timeline(oAuth); foreach (var item in Timeline) { - Domain.Socioboard.Models.Mongo.MongoTwitterMessage objTwitterMessage = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); - objTwitterMessage.id = ObjectId.GenerateNewId(); - objTwitterMessage.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterUsertweet; + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); + objMessageModel.id = ObjectId.GenerateNewId(); + objMessageModel.type = Domain.Socioboard.Enum.MessageType.TwitterUsertweet; try { - objTwitterMessage.twitterMsg = item["text"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.Message = item["text"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1049,7 +1049,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.sourceUrl = item["source"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.sourceUrl = item["source"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1057,7 +1057,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.mediaUrl = item["extended_entities"]["media"][0]["media_url_https"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.mediaUrl = item["extended_entities"]["media"][0]["media_url_https"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1065,7 +1065,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.screenName = screenName; + objMessageModel.screenName = screenName; } catch (Exception ex) { @@ -1073,7 +1073,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.profileId = profileId; + objMessageModel.profileId = profileId; } catch (Exception ex) { @@ -1081,7 +1081,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1090,8 +1090,8 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi try { const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; - objTwitterMessage.messageDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); - objTwitterMessage.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objMessageModel.messageDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objMessageModel.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); } catch (Exception ex) { @@ -1099,7 +1099,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.inReplyToStatusUserId = item["in_reply_to_status_id_str"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.inReplyToStatusUserId = item["in_reply_to_status_id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1108,7 +1108,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi try { - objTwitterMessage.fromProfileUrl = item["user"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromProfileUrl = item["user"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1116,7 +1116,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.fromName = item["user"]["name"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromName = item["user"]["name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1124,7 +1124,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi } try { - objTwitterMessage.fromId = item["user"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromId = item["user"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1133,14 +1133,14 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi try { - objTwitterMessage.fromScreenName = item["user"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); + objMessageModel.fromScreenName = item["user"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var ret = mongorepo.Find(t => t.RecipientId == objTwitterMessage.RecipientId && t.messageId == objTwitterMessage.messageId && t.profileId == profileId); + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var ret = mongorepo.Find(t => t.RecipientId == objMessageModel.RecipientId && t.messageId == objMessageModel.messageId && t.profileId == profileId); var task = Task.Run(async () => { return await ret; @@ -1148,7 +1148,7 @@ private static void SaveUserTweets(string profileId, string screenName, oAuthTwi int count = task.Result.Count; if (count < 1) { - mongorepo.Add(objTwitterMessage); + mongorepo.Add(objMessageModel); } } } @@ -1169,7 +1169,7 @@ private static void SaveTwitterFeeds(string profileId, string screenName, oAuthT Domain.Socioboard.Models.Mongo.MongoTwitterFeed objTwitterFeed = new Domain.Socioboard.Models.Mongo.MongoTwitterFeed(); foreach (var item in Home_Timeline) { - objTwitterFeed.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterFeed; + objTwitterFeed.type = Domain.Socioboard.Enum.MessageType.TwitterFeed; try { objTwitterFeed.feed = item["text"].ToString().TrimStart('"').TrimEnd('"'); @@ -1306,16 +1306,16 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter { JArray Messages_Sent = twtuser.GetDirect_Messages_Sent(OAuth, 20); - Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages objTwitterDirectMessages = new Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages(); + Domain.Socioboard.Models.Mongo.MongoDirectMessages objDirectMessages = new Domain.Socioboard.Models.Mongo.MongoDirectMessages(); foreach (var item in Messages_Sent) { - objTwitterDirectMessages.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageSent; - objTwitterDirectMessages.id = ObjectId.GenerateNewId(); - objTwitterDirectMessages.profileId = profileId; + objDirectMessages.type = Domain.Socioboard.Enum.MessageType.TwitterDirectMessageSent; + objDirectMessages.id = ObjectId.GenerateNewId(); + objDirectMessages.profileId = profileId; try { - objTwitterDirectMessages.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1324,8 +1324,8 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter try { const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; - objTwitterDirectMessages.createdDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); - objTwitterDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objDirectMessages.createdDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); } catch (Exception ex) { @@ -1333,7 +1333,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter } try { - objTwitterDirectMessages.message = item["text"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.message = item["text"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1342,7 +1342,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter try { - objTwitterDirectMessages.recipientId = item["recipient"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.recipientId = item["recipient"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1351,7 +1351,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter try { - objTwitterDirectMessages.recipientScreenName = item["recipient"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.recipientScreenName = item["recipient"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1360,7 +1360,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter try { - objTwitterDirectMessages.recipientProfileUrl = item["recipient"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.recipientProfileUrl = item["recipient"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1369,7 +1369,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter try { - objTwitterDirectMessages.senderId = item["sender"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.senderId = item["sender"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1378,7 +1378,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter try { - objTwitterDirectMessages.senderScreenName = item["sender"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.senderScreenName = item["sender"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1386,7 +1386,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter } try { - objTwitterDirectMessages.senderProfileUrl = item["sender"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.senderProfileUrl = item["sender"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1394,14 +1394,14 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter } try { - objTwitterDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", _appSettings); - var ret = mongorepo.Find(t => t.messageId == objTwitterDirectMessages.messageId && t.profileId == profileId && t.recipientId == objTwitterDirectMessages.recipientId && t.senderId == objTwitterDirectMessages.senderId); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + var ret = mongorepo.Find(t => t.messageId == objDirectMessages.messageId && t.profileId == profileId && t.recipientId == objDirectMessages.recipientId && t.senderId == objDirectMessages.senderId); var task = Task.Run(async () => { return await ret; @@ -1409,7 +1409,7 @@ private static void SaveTwitterDirectMessageSent(string profileId, oAuthTwitter int count = task.Result.Count; if (count < 1) { - mongorepo.Add(objTwitterDirectMessages); + mongorepo.Add(objDirectMessages); } } } @@ -1429,15 +1429,15 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit { JArray Messages_Sent = twtuser.GetDirect_Messages(OAuth, 20); - Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages objTwitterDirectMessages = new Domain.Socioboard.Models.Mongo.MongoTwitterDirectMessages(); + Domain.Socioboard.Models.Mongo.MongoDirectMessages objDirectMessages = new Domain.Socioboard.Models.Mongo.MongoDirectMessages(); foreach (var item in Messages_Sent) { - objTwitterDirectMessages.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterDirectMessageReceived; - objTwitterDirectMessages.id = ObjectId.GenerateNewId(); - objTwitterDirectMessages.profileId = profileId; + objDirectMessages.type = Domain.Socioboard.Enum.MessageType.TwitterDirectMessageReceived; + objDirectMessages.id = ObjectId.GenerateNewId(); + objDirectMessages.profileId = profileId; try { - objTwitterDirectMessages.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.messageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1446,8 +1446,8 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit try { const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; - objTwitterDirectMessages.createdDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); - objTwitterDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); + objDirectMessages.createdDate = DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.timeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact(item["created_at"].ToString().TrimStart('"').TrimEnd('"'), format, System.Globalization.CultureInfo.InvariantCulture)); } catch (Exception ex) { @@ -1455,7 +1455,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit } try { - objTwitterDirectMessages.message = item["text"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.message = item["text"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1464,7 +1464,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit try { - objTwitterDirectMessages.recipientId = item["recipient"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.recipientId = item["recipient"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1473,7 +1473,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit try { - objTwitterDirectMessages.recipientScreenName = item["recipient"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.recipientScreenName = item["recipient"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1482,7 +1482,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit try { - objTwitterDirectMessages.recipientProfileUrl = item["recipient"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.recipientProfileUrl = item["recipient"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1491,7 +1491,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit try { - objTwitterDirectMessages.senderId = item["sender"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.senderId = item["sender"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1500,7 +1500,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit try { - objTwitterDirectMessages.senderScreenName = item["sender"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.senderScreenName = item["sender"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1508,7 +1508,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit } try { - objTwitterDirectMessages.senderProfileUrl = item["sender"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); + objDirectMessages.senderProfileUrl = item["sender"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { @@ -1516,14 +1516,14 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit } try { - objTwitterDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objDirectMessages.entryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } - MongoRepository mongorepo = new MongoRepository("MongoTwitterDirectMessages", _appSettings); - var ret = mongorepo.Find(t => t.messageId == objTwitterDirectMessages.messageId && t.profileId == profileId && t.recipientId == objTwitterDirectMessages.recipientId && t.senderId == objTwitterDirectMessages.senderId); + MongoRepository mongorepo = new MongoRepository("MongoDirectMessages", _appSettings); + var ret = mongorepo.Find(t => t.messageId == objDirectMessages.messageId && t.profileId == profileId && t.recipientId == objDirectMessages.recipientId && t.senderId == objDirectMessages.senderId); var task = Task.Run(async () => { return await ret; @@ -1531,7 +1531,7 @@ private static void SaveTwittwrDirectMessageRecieved(string profileId, oAuthTwit int count = task.Result.Count; if (count < 1) { - mongorepo.Add(objTwitterDirectMessages); + mongorepo.Add(objDirectMessages); } } } @@ -1563,85 +1563,85 @@ public static void SaveUserFollowers(oAuthTwitter OAuth, string screeenName, str do { curser = curser_next; - Domain.Socioboard.Models.Mongo.MongoTwitterMessage _InboxMessages; + Domain.Socioboard.Models.Mongo.MongoMessageModel objMessageModel; foreach (var item in user_data) { try { - _InboxMessages = new Domain.Socioboard.Models.Mongo.MongoTwitterMessage(); - _InboxMessages.id = ObjectId.GenerateNewId(); - _InboxMessages.profileId = TwitterUserId; - _InboxMessages.type = Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower; - _InboxMessages.messageId = ""; - _InboxMessages.readStatus = 1; + objMessageModel = new Domain.Socioboard.Models.Mongo.MongoMessageModel(); + objMessageModel.id = ObjectId.GenerateNewId(); + objMessageModel.profileId = TwitterUserId; + objMessageModel.type = Domain.Socioboard.Enum.MessageType.TwitterFollower; + objMessageModel.messageId = ""; + objMessageModel.readStatus = 1; try { - _InboxMessages.twitterMsg = item["description"].ToString(); + objMessageModel.Message = item["description"].ToString(); } catch (Exception ex) { } try { - _InboxMessages.fromId = item["id_str"].ToString(); + objMessageModel.fromId = item["id_str"].ToString(); } catch (Exception ex) { - _InboxMessages.fromId = item["id"].ToString(); + objMessageModel.fromId = item["id"].ToString(); } try { - _InboxMessages.fromName = item["screen_name"].ToString(); + objMessageModel.fromName = item["screen_name"].ToString(); } catch (Exception ex) { } try { - _InboxMessages.FollowerCount = Convert.ToInt32(item["followers_count"].ToString()); + objMessageModel.FollowerCount = Convert.ToInt32(item["followers_count"].ToString()); } catch (Exception ex) { } try { - _InboxMessages.FollowingCount = Convert.ToInt32(item["friends_count"].ToString()); + objMessageModel.FollowingCount = Convert.ToInt32(item["friends_count"].ToString()); } catch (Exception ex) { } try { - _InboxMessages.fromProfileUrl = item["profile_image_url"].ToString(); + objMessageModel.fromProfileUrl = item["profile_image_url"].ToString(); } catch (Exception ex) { - _InboxMessages.fromProfileUrl = item["profile_image_url_https"].ToString(); + objMessageModel.fromProfileUrl = item["profile_image_url_https"].ToString(); } try { - _InboxMessages.messageDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); - _InboxMessages.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); + objMessageModel.messageDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); + objMessageModel.messageTimeStamp = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); } catch (Exception ex) { } - _InboxMessages.RecipientId = TwitterUserId; - _InboxMessages.RecipientName = screeenName; - MongoRepository mongorepo = new MongoRepository("MongoTwitterMessage", _appSettings); - var result = mongorepo.Find(t => t.fromId == _InboxMessages.fromId && t.RecipientId == _InboxMessages.RecipientId && t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterFollower); + objMessageModel.RecipientId = TwitterUserId; + objMessageModel.RecipientName = screeenName; + MongoRepository mongorepo = new MongoRepository("MongoMessageModel", _appSettings); + var result = mongorepo.Find(t => t.fromId == objMessageModel.fromId && t.RecipientId == objMessageModel.RecipientId && t.type == Domain.Socioboard.Enum.MessageType.TwitterFollower); var task = Task.Run(async () => { return await result; }); - IList lstMongoTwitterMessage = task.Result; + IList lstMongoTwitterMessage = task.Result; if (lstMongoTwitterMessage.Count > 0) { - mongorepo.UpdateReplace(_InboxMessages, t => t.id == lstMongoTwitterMessage[0].id); + mongorepo.UpdateReplace(objMessageModel, t => t.id == lstMongoTwitterMessage[0].id); } else { - mongorepo.Add(_InboxMessages); + mongorepo.Add(objMessageModel); } } diff --git a/src/Api.Socioboard/project.lock.json b/src/Api.Socioboard/project.lock.json index b60efd749..afe41d36a 100644 --- a/src/Api.Socioboard/project.lock.json +++ b/src/Api.Socioboard/project.lock.json @@ -35,10 +35,10 @@ "lib/net45/Facebook.dll": {} } }, - "Google.Apis/1.24.1": { + "Google.Apis/1.25.0": { "type": "package", "dependencies": { - "Google.Apis.Core": "1.24.1", + "Google.Apis.Core": "1.25.0", "Zlib.Portable.Signed": "1.11.0" }, "compile": { @@ -63,11 +63,11 @@ "lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.Analytics.v3.dll": {} } }, - "Google.Apis.Auth/1.24.1": { + "Google.Apis.Auth/1.25.0": { "type": "package", "dependencies": { - "Google.Apis": "1.24.1", - "Google.Apis.Core": "1.24.1" + "Google.Apis": "1.25.0", + "Google.Apis.Core": "1.25.0" }, "compile": { "lib/net45/Google.Apis.Auth.PlatformServices.dll": {}, @@ -78,7 +78,7 @@ "lib/net45/Google.Apis.Auth.dll": {} } }, - "Google.Apis.Core/1.24.1": { + "Google.Apis.Core/1.25.0": { "type": "package", "dependencies": { "Newtonsoft.Json": "7.0.1" @@ -90,11 +90,11 @@ "lib/net45/Google.Apis.Core.dll": {} } }, - "Google.Apis.YouTube.v3/1.24.1.760": { + "Google.Apis.YouTube.v3/1.25.0.760": { "type": "package", "dependencies": { - "Google.Apis": "1.24.1", - "Google.Apis.Auth": "1.24.1" + "Google.Apis": "1.25.0", + "Google.Apis.Auth": "1.25.0" }, "compile": { "lib/net45/Google.Apis.YouTube.v3.dll": {} @@ -103,45 +103,6 @@ "lib/net45/Google.Apis.YouTube.v3.dll": {} } }, - "Google.GData.Client/2.2.0": { - "type": "package", - "dependencies": { - "Newtonsoft.Json": "4.0.5" - }, - "compile": { - "lib/Google.GData.Client.dll": {} - }, - "runtime": { - "lib/Google.GData.Client.dll": {} - } - }, - "Google.GData.Extensions/2.2.0": { - "type": "package", - "dependencies": { - "Google.GData.Client": "2.2.0", - "Newtonsoft.Json": "4.0.5" - }, - "compile": { - "lib/Google.GData.Extensions.dll": {} - }, - "runtime": { - "lib/Google.GData.Extensions.dll": {} - } - }, - "Google.GData.YouTube/2.2.0": { - "type": "package", - "dependencies": { - "Google.GData.Client": "2.2.0", - "Google.GData.Extensions": "2.2.0", - "Newtonsoft.Json": "4.0.5" - }, - "compile": { - "lib/Google.GData.YouTube.dll": {} - }, - "runtime": { - "lib/Google.GData.YouTube.dll": {} - } - }, "Hammock/1.2.3": { "type": "package", "compile": { @@ -2451,10 +2412,10 @@ "lib/net45/Facebook.dll": {} } }, - "Google.Apis/1.24.1": { + "Google.Apis/1.25.0": { "type": "package", "dependencies": { - "Google.Apis.Core": "1.24.1", + "Google.Apis.Core": "1.25.0", "Zlib.Portable.Signed": "1.11.0" }, "compile": { @@ -2479,11 +2440,11 @@ "lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.Analytics.v3.dll": {} } }, - "Google.Apis.Auth/1.24.1": { + "Google.Apis.Auth/1.25.0": { "type": "package", "dependencies": { - "Google.Apis": "1.24.1", - "Google.Apis.Core": "1.24.1" + "Google.Apis": "1.25.0", + "Google.Apis.Core": "1.25.0" }, "compile": { "lib/net45/Google.Apis.Auth.PlatformServices.dll": {}, @@ -2494,7 +2455,7 @@ "lib/net45/Google.Apis.Auth.dll": {} } }, - "Google.Apis.Core/1.24.1": { + "Google.Apis.Core/1.25.0": { "type": "package", "dependencies": { "Newtonsoft.Json": "7.0.1" @@ -2506,11 +2467,11 @@ "lib/net45/Google.Apis.Core.dll": {} } }, - "Google.Apis.YouTube.v3/1.24.1.760": { + "Google.Apis.YouTube.v3/1.25.0.760": { "type": "package", "dependencies": { - "Google.Apis": "1.24.1", - "Google.Apis.Auth": "1.24.1" + "Google.Apis": "1.25.0", + "Google.Apis.Auth": "1.25.0" }, "compile": { "lib/net45/Google.Apis.YouTube.v3.dll": {} @@ -2519,45 +2480,6 @@ "lib/net45/Google.Apis.YouTube.v3.dll": {} } }, - "Google.GData.Client/2.2.0": { - "type": "package", - "dependencies": { - "Newtonsoft.Json": "4.0.5" - }, - "compile": { - "lib/Google.GData.Client.dll": {} - }, - "runtime": { - "lib/Google.GData.Client.dll": {} - } - }, - "Google.GData.Extensions/2.2.0": { - "type": "package", - "dependencies": { - "Google.GData.Client": "2.2.0", - "Newtonsoft.Json": "4.0.5" - }, - "compile": { - "lib/Google.GData.Extensions.dll": {} - }, - "runtime": { - "lib/Google.GData.Extensions.dll": {} - } - }, - "Google.GData.YouTube/2.2.0": { - "type": "package", - "dependencies": { - "Google.GData.Client": "2.2.0", - "Google.GData.Extensions": "2.2.0", - "Newtonsoft.Json": "4.0.5" - }, - "compile": { - "lib/Google.GData.YouTube.dll": {} - }, - "runtime": { - "lib/Google.GData.YouTube.dll": {} - } - }, "Hammock/1.2.3": { "type": "package", "compile": { @@ -4862,12 +4784,12 @@ "serializers/JsonNetSerializer.cs" ] }, - "Google.Apis/1.24.1": { - "sha512": "IotbJlX3qTthN3Z3HdtnzV81CkWUi5iFAKlZUqM0tEz5XYfm0rsieCIn5xGgemcrJ2NAQSrDVmcu4u2AHXS1uQ==", + "Google.Apis/1.25.0": { + "sha512": "6F8TcXVYS1dGSC7m4fQsf7wk7TlVmZV6qyMN3e0HIQHOdXOHNvmvMmI7hEOxfKX7xFKakUC98zxhS9j6GLDpwQ==", "type": "package", - "path": "Google.Apis/1.24.1", + "path": "Google.Apis/1.25.0", "files": [ - "Google.Apis.1.24.1.nupkg.sha512", + "Google.Apis.1.25.0.nupkg.sha512", "Google.Apis.nuspec", "License.txt", "lib/net45/Google.Apis.PlatformServices.dll", @@ -4917,12 +4839,12 @@ "lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.Analytics.v3.xml" ] }, - "Google.Apis.Auth/1.24.1": { - "sha512": "Jlki9jQxZT2J1frKqbA7Hp2QwT14nrtrTBSb6NmT5JRfmFLDLtipJXLBSFnXpY8glchc2sQIIixMo5ul4buuhA==", + "Google.Apis.Auth/1.25.0": { + "sha512": "L2mdtqQ1VZxn5v3FLuI3EKsiNQQyaM7rr+tvn1Z1utJ1ZheD1nUyIm9Z6wCM7SL0gImYQWqzWMb6nOtxXKJV7A==", "type": "package", - "path": "Google.Apis.Auth/1.24.1", + "path": "Google.Apis.Auth/1.25.0", "files": [ - "Google.Apis.Auth.1.24.1.nupkg.sha512", + "Google.Apis.Auth.1.25.0.nupkg.sha512", "Google.Apis.Auth.nuspec", "License.txt", "lib/net45/Google.Apis.Auth.PlatformServices.dll", @@ -4960,12 +4882,12 @@ "lib/wpa81/Google.Apis.Auth.xml" ] }, - "Google.Apis.Core/1.24.1": { - "sha512": "ucJl79pUqRlD0GdsaJI0VPCcREmoYH+93Z1eHWRjOAkMQVGo2Jb9yOF6bJBQnPO+BTvGlf32a0Xc+nxCOLdvEw==", + "Google.Apis.Core/1.25.0": { + "sha512": "GD3N9s6LLv6MNcBh+uE+fq35Mi7keslkcpmdbnO8ZkQs18Oul1PAmyyflKAdKAWTexxEFknjEchI7erLizADkg==", "type": "package", - "path": "Google.Apis.Core/1.24.1", + "path": "Google.Apis.Core/1.25.0", "files": [ - "Google.Apis.Core.1.24.1.nupkg.sha512", + "Google.Apis.Core.1.25.0.nupkg.sha512", "Google.Apis.Core.nuspec", "License.txt", "lib/net45/Google.Apis.Core.dll", @@ -4979,12 +4901,12 @@ "lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Core.xml" ] }, - "Google.Apis.YouTube.v3/1.24.1.760": { - "sha512": "52hdVKEiSsut5cQc46pdgn91s6gNYH6T5ipbvjsnVHvyqps7c4OIylXvHNdCotd2S71u1+1/gLRW439BE4Whlg==", + "Google.Apis.YouTube.v3/1.25.0.760": { + "sha512": "d43Fp5+E+cAew9DyCaba9aFf0lHQzrwP+HPIdSC3baxJaGPkAvqQJFMU+SKUvtFsatd1E0jFyjxQfw2//zWHFA==", "type": "package", - "path": "Google.Apis.YouTube.v3/1.24.1.760", + "path": "Google.Apis.YouTube.v3/1.25.0.760", "files": [ - "Google.Apis.YouTube.v3.1.24.1.760.nupkg.sha512", + "Google.Apis.YouTube.v3.1.25.0.760.nupkg.sha512", "Google.Apis.YouTube.v3.nuspec", "lib/net45/Google.Apis.YouTube.v3.dll", "lib/net45/Google.Apis.YouTube.v3.pdb", @@ -5000,36 +4922,6 @@ "lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.xml" ] }, - "Google.GData.Client/2.2.0": { - "sha512": "fEzWX+zWCJLj2pHcaY22hz4bbhCYzk01OodW2lqovh8jA2KsMaZ+SvZJqjl2sZo83us8DAFYlnopIR6qfkBbrQ==", - "type": "package", - "path": "Google.GData.Client/2.2.0", - "files": [ - "Google.GData.Client.2.2.0.nupkg.sha512", - "Google.GData.Client.nuspec", - "lib/Google.GData.Client.dll" - ] - }, - "Google.GData.Extensions/2.2.0": { - "sha512": "Pvei3H1fhthoPbgey6QXqlYD3BCYo+E2h/J1+1PVK1rKMQ/9Ifo3nx5KDT1luyu2H/ZGFxouDaxnqKq2u/J5Qg==", - "type": "package", - "path": "Google.GData.Extensions/2.2.0", - "files": [ - "Google.GData.Extensions.2.2.0.nupkg.sha512", - "Google.GData.Extensions.nuspec", - "lib/Google.GData.Extensions.dll" - ] - }, - "Google.GData.YouTube/2.2.0": { - "sha512": "z/Ce0/mZDFs3sSqU5GdHhfilNVjnUHu8PZtfskzI3rMbxCLi9J1e1MQ097Jcl6DuSjkJl+M90JyC98wy5X7goA==", - "type": "package", - "path": "Google.GData.YouTube/2.2.0", - "files": [ - "Google.GData.YouTube.2.2.0.nupkg.sha512", - "Google.GData.YouTube.nuspec", - "lib/Google.GData.YouTube.dll" - ] - }, "Hammock/1.2.3": { "sha512": "JdYotigd2ZilatoSXL+PXFZERRHkhTN3vn/rkVLrm2FxbXJjW0lhD4qEXF/gTv1RUp4gjgBwCTxv/WxQmAessQ==", "type": "package", @@ -5144,12 +5036,12 @@ ] }, "Imgur.API/4.0.1": { - "sha512": "P5sDCdRgjJoiUksCvkEu5KdF3rLKLioC6cAya7h/GyYhFEHePCwMq33QYDl/M4Ms9ALZEvoU/+vXxfMLpDhSlg==", + "sha512": "fgg9Y0FQVw0RXeztVkbhFyIuc4SbxEDu7uTRPmes58jNpti5p3HW3dD1H4OtYB67stZbmWbiTwyx2Qm1/m8e6w==", "type": "package", "path": "Imgur.API/4.0.1", "files": [ - "Imgur.API.4.0.1.nupkg.sha512", - "Imgur.API.nuspec", + "imgur.api.4.0.1.nupkg.sha512", + "imgur.api.nuspec", "lib/net45/Imgur.API.dll", "lib/net45/Imgur.API.xml", "lib/netstandard1.1/Imgur.API.dll", @@ -5493,7 +5385,7 @@ ] }, "Microsoft.AspNetCore.JsonPatch/1.0.0": { - "sha512": "WVaSVS+dDlWCR/qerHnBxU9tIeJ9GMA3M5tg4cxH7/cJYZZLnr2zvaFHGB+cRRNCKKTJ0pFRxT7ES8knhgAAaA==", + "sha512": "TFhm3NMZTvm8JmZ3yTwSlbVBaLBcSFqVlJn8WxC6voGcTb12TOVKWAHL0K5eHoYKEvUhKUvrP1ugeFua39Xueg==", "type": "package", "path": "Microsoft.AspNetCore.JsonPatch/1.0.0", "files": [ @@ -6366,16 +6258,16 @@ ] }, "Microsoft.Extensions.PlatformAbstractions/1.0.0": { - "sha512": "zyjUzrOmuevOAJpIo3Mt5GmpALVYCVdLZ99keMbmCxxgQH7oxzU58kGHzE6hAgYEiWsdfMJLjVR7r+vSmaJmtg==", + "sha512": "+SMcyAqMVmGIP/nOLyVLOhnYVJNawYSm5ZogbZ+kA34eDuPdlunds4bLvT5wiiHm+El+aZr8OSGE6u4d245u+w==", "type": "package", "path": "Microsoft.Extensions.PlatformAbstractions/1.0.0", "files": [ - "Microsoft.Extensions.PlatformAbstractions.1.0.0.nupkg.sha512", - "Microsoft.Extensions.PlatformAbstractions.nuspec", "lib/net451/Microsoft.Extensions.PlatformAbstractions.dll", "lib/net451/Microsoft.Extensions.PlatformAbstractions.xml", "lib/netstandard1.3/Microsoft.Extensions.PlatformAbstractions.dll", - "lib/netstandard1.3/Microsoft.Extensions.PlatformAbstractions.xml" + "lib/netstandard1.3/Microsoft.Extensions.PlatformAbstractions.xml", + "microsoft.extensions.platformabstractions.1.0.0.nupkg.sha512", + "microsoft.extensions.platformabstractions.nuspec" ] }, "Microsoft.Extensions.Primitives/1.0.0": { @@ -6594,7 +6486,7 @@ ] }, "NHibernate/4.0.4.4000": { - "sha512": "jAKwpGLeGai8KWj1e3p1K882vlZUJaQeH4RTuscKTyXhsEsiQEe2uKs9S3bY91aPyygMiPXg1CyRopi1K+e5aA==", + "sha512": "Me3y8Q1NPEfiTRuisgayLs5nm7J4hoGhvXT/hD5w78WajPFfsb+qNP2ld+bNimpvW0U/BDSaZAUS0FKl5+ty/w==", "type": "package", "path": "NHibernate/4.0.4.4000", "files": [ @@ -6606,15 +6498,15 @@ "ConfigurationTemplates/SQLite.cfg.xml", "ConfigurationTemplates/SybaseASE.cfg.xml", "ConfigurationTemplates/SybaseSQLAnywhere.cfg.xml", - "NHibernate.4.0.4.4000.nupkg.sha512", "NHibernate.license.txt", - "NHibernate.nuspec", "NHibernate.readme.html", "NHibernate.releasenotes.txt", "lib/net40/NHibernate.dll", "lib/net40/NHibernate.xml", "nhibernate-configuration.xsd", - "nhibernate-mapping.xsd" + "nhibernate-mapping.xsd", + "nhibernate.4.0.4.4000.nupkg.sha512", + "nhibernate.nuspec" ] }, "NHibernate.Linq/1.0.0": { @@ -9421,8 +9313,7 @@ "": [ "Domain.Socioboard >= 1.0.0-*", "Google.Apis.Analytics.v3 >= 1.14.0.456", - "Google.Apis.YouTube.v3 >= 1.24.1.760", - "Google.GData.YouTube >= 2.2.0", + "Google.Apis.YouTube.v3 >= 1.25.0.760", "Imgur.API >= 4.0.1", "Microsoft.ApplicationInsights.AspNetCore >= 1.0.0", "Microsoft.AspNetCore.Cors >= 1.0.0", diff --git a/src/Api.Socioboard/wwwroot/Api.Socioboard.xml b/src/Api.Socioboard/wwwroot/Api.Socioboard.xml index 3f3f7a330..e85072b36 100644 --- a/src/Api.Socioboard/wwwroot/Api.Socioboard.xml +++ b/src/Api.Socioboard/wwwroot/Api.Socioboard.xml @@ -317,17 +317,17 @@ Id of the user - + To change the password when user request it. id of the user - password which is using currently - A new password given by the user - confirm password + password which is using currently + A new password given by the user + confirm password - + To send the mail to user :for reseting the password when user forgot it and request for change. @@ -348,14 +348,14 @@ Email Id does not exist: When email id does not exist in db. - + sending mail to user after reseting the password. User email id - changed password + changed password Forgot password token - Password changed successfully:if user data present in db and validate token. + smtpClientPassword changed successfully:if user data present in db and validate token. EmailId does not exist:when user emailid does not exist @@ -440,7 +440,7 @@ From Google Developer console https://console.developers.google.com From Google Developer console https://console.developers.google.com - A string used to identify a user. + A string used to identify a user. diff --git a/src/Domain.Socioboard/Enum/AdsOfferAccountStatus.cs b/src/Domain.Socioboard/Enum/AdsOfferAccountStatus.cs index 141d08188..1e8c068b8 100644 --- a/src/Domain.Socioboard/Enum/AdsOfferAccountStatus.cs +++ b/src/Domain.Socioboard/Enum/AdsOfferAccountStatus.cs @@ -1,15 +1,17 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Threading.Tasks; namespace Domain.Socioboard.Enum { public enum AdsOfferAccountStatus - { - + { + [Description("Client enables always free options")] Active = 1, - InActive = 0, + [Description("Client disable always free options")] + InActive = 0, } } diff --git a/src/Domain.Socioboard/Enum/AdsStatus.cs b/src/Domain.Socioboard/Enum/AdsStatus.cs index e108fb21b..e68aa520e 100644 --- a/src/Domain.Socioboard/Enum/AdsStatus.cs +++ b/src/Domain.Socioboard/Enum/AdsStatus.cs @@ -6,10 +6,8 @@ namespace Domain.Socioboard.Enum { public enum AdsStatus - { - + { NotVerified = 0, Verified = 1, - } } diff --git a/src/Domain.Socioboard/Enum/FacebookPagePromotion.cs b/src/Domain.Socioboard/Enum/FacebookPagePromotion.cs index b858bc8ad..d18e71c8f 100644 --- a/src/Domain.Socioboard/Enum/FacebookPagePromotion.cs +++ b/src/Domain.Socioboard/Enum/FacebookPagePromotion.cs @@ -7,7 +7,8 @@ namespace Domain.Socioboard.Enum { public enum FacebookPagePromotion { - tagged=0, - promotable_posts=1 + Tagged=0, + + PromotablePosts=1 } } diff --git a/src/Domain.Socioboard/Enum/MessageType.cs b/src/Domain.Socioboard/Enum/MessageType.cs new file mode 100644 index 000000000..b1cdb3997 --- /dev/null +++ b/src/Domain.Socioboard/Enum/MessageType.cs @@ -0,0 +1,23 @@ + + +namespace Domain.Socioboard.Enum +{ + public enum MessageType + { + TwitterMention = 0, + TwitterRetweet = 1, + TwitterUsertweet = 2, + TwitterFeed = 3, + TwitterDirectMessageSent = 4, + TwitterDirectMessageReceived = 5, + TwitterFollower = 6, + FacebookPageDirectMessageSent = 7, + FacebookPagDirectMessageReceived = 8, + InstagramFollower = 9, + InstagramFollowing = 10, + FacebookPageNotification = 11 + } + + + +} diff --git a/src/Domain.Socioboard/Enum/PayPalAccountStatus.cs b/src/Domain.Socioboard/Enum/PayPalAccountStatus.cs index 92224a194..5b3d0b6ef 100644 --- a/src/Domain.Socioboard/Enum/PayPalAccountStatus.cs +++ b/src/Domain.Socioboard/Enum/PayPalAccountStatus.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Threading.Tasks; @@ -9,9 +10,12 @@ namespace Domain.Socioboard.Enum public enum PayPalAccountStatus { + [Description("User not selected Paypal")] notadded = 0, + [Description("User selected Paypal, but still in progress")] inprogress = 1, - added=2 + [Description("User selected Paypal and added successfully")] + added =2 } } diff --git a/src/Domain.Socioboard/Enum/SBPaymentStatus.cs b/src/Domain.Socioboard/Enum/SBPaymentStatus.cs index 385a0f125..41d9b291f 100644 --- a/src/Domain.Socioboard/Enum/SBPaymentStatus.cs +++ b/src/Domain.Socioboard/Enum/SBPaymentStatus.cs @@ -1,9 +1,14 @@  +using System.ComponentModel; + namespace Domain.Socioboard.Enum { public enum SBPaymentStatus { + [Description("Paid version")] Paid = 0, + + [Description("Unpaid version")] UnPaid = 1 } } diff --git a/src/Domain.Socioboard/Enum/SBUserActivationStatus.cs b/src/Domain.Socioboard/Enum/SBUserActivationStatus.cs index fe816479b..7a609fa98 100644 --- a/src/Domain.Socioboard/Enum/SBUserActivationStatus.cs +++ b/src/Domain.Socioboard/Enum/SBUserActivationStatus.cs @@ -1,11 +1,20 @@  +using System.ComponentModel; + namespace Domain.Socioboard.Enum { public enum SBUserActivationStatus { + [Description("Account already active")] Active =0, + + [Description("Account not active,but has been sent")] MailSent =1, + + [Description("Account not active,and also hasn't been sent")] InActive =2, + + [Description("Account disable due to illlegal activity")] Disable =3 } } diff --git a/src/Domain.Socioboard/Helpers/CustomTaskFactory.cs b/src/Domain.Socioboard/Helpers/CustomTaskFactory.cs new file mode 100644 index 000000000..1d9034de1 --- /dev/null +++ b/src/Domain.Socioboard/Helpers/CustomTaskFactory.cs @@ -0,0 +1,69 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Domain.Socioboard.Helpers +{ + public class CustomTaskFactory + { + public delegate void TaskError(Task task, Exception error); + + private event TaskError Error; + + public static readonly CustomTaskFactory Instance = new CustomTaskFactory(); + + private CustomTaskFactory() + { + Error += (t, e) => { }; + } + + private void InvokeError(Task task, Exception error) + => Error?.Invoke(task, error); + + public Task Start(Action action) + { + var task = new Task(action); + Start(task); + return task; + } + + public Task Start(Action action, CancellationToken token, TaskCreationOptions options = TaskCreationOptions.LongRunning) + { + var task = new Task(action, token, options); + Start(task); + return task; + } + + private void Start(Task task) + { + task.ContinueWith(t => + { + if (t.Exception != null) + InvokeError(t, t.Exception.InnerException); + }, + TaskContinuationOptions.OnlyOnFaulted | + TaskContinuationOptions.ExecuteSynchronously); + task.Start(); + } + + public Task Start(Func action, TaskCreationOptions options) + { + + var task = new Task(action, options); + + task.ContinueWith(t => + { + if (t.Exception != null) + InvokeError(t, t.Exception.InnerException); + }, + TaskContinuationOptions.OnlyOnFaulted | + TaskContinuationOptions.ExecuteSynchronously); + + task.Start(); + + return task; + } + } + + +} \ No newline at end of file diff --git a/src/Domain.Socioboard/Helpers/DateTimeHelper.cs b/src/Domain.Socioboard/Helpers/DateTimeHelper.cs new file mode 100644 index 000000000..441a01bd2 --- /dev/null +++ b/src/Domain.Socioboard/Helpers/DateTimeHelper.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Domain.Socioboard.Helpers +{ + public class ScheduleDays + { + public ScheduleDays() + { + + } + + public List SelectedDays { get; set; } = new List(); + } + + public class DateTimeHelper + { + public static DateTime GetNextScheduleDate(DayOfWeek requiredDay, DateTime startDate) + { + for (int countIndex = 0; countIndex < 7; countIndex++) + { + var currentDate = startDate.AddDays(countIndex); + if (currentDate.DayOfWeek == requiredDay) + return currentDate; + } + return startDate; + } + + public static DateTime GetNextScheduleDate(List selectedDays,DateTime startDate) + { + + for (int countIndex = 0; countIndex < 7; countIndex++) + { + var currentDate = startDate.AddDays(countIndex); + if (selectedDays.Contains(currentDate.DayOfWeek.ToString())) + return currentDate; + } + return startDate; + } + } +} diff --git a/src/Domain.Socioboard/Helpers/SBHelper.cs b/src/Domain.Socioboard/Helpers/SBHelper.cs index d2bc01a78..318d035f0 100644 --- a/src/Domain.Socioboard/Helpers/SBHelper.cs +++ b/src/Domain.Socioboard/Helpers/SBHelper.cs @@ -1,6 +1,7 @@ using Domain.Socioboard.Enum; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; @@ -18,70 +19,61 @@ public static string RandomString(int length) .Select(s => s[random.Next(s.Length)]).ToArray()); } - - - - - public static string MD5Hash(string text) + public static string Md5Hash(string text) { - MD5 md5 = MD5.Create(); + var md5 = MD5.Create(); //compute hash from the bytes of text - byte[] result = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes(text)); + var result = md5.ComputeHash(Encoding.Unicode.GetBytes(text)); //get hash result after compute it // byte[] result = md5.ComputeHash; - - StringBuilder strBuilder = new StringBuilder(); - for (int i = 0; i < result.Length; i++) + var strBuilder = new StringBuilder(); + for (var i = 0; i < result.Length; i++) { //change it into 2 hexadecimal digits //for each byte strBuilder.Append(result[i].ToString("x2")); } - return strBuilder.ToString(); } public static int GetMaxProfileCount(SBAccountType accountType) { - int ret = 5; + int maxProfileCount; + switch (accountType) { case SBAccountType.Free: - ret = 5; + maxProfileCount = 5; break; case SBAccountType.Standard: - ret = 10; + maxProfileCount = 10; break; - case SBAccountType.Premium: - ret = 20; + maxProfileCount = 20; break; case SBAccountType.Deluxe: - ret = 50; + maxProfileCount = 50; break; case SBAccountType.Topaz: - ret = 100; + maxProfileCount = 100; break; case SBAccountType.Ruby: - ret = 200; + maxProfileCount = 200; break; case SBAccountType.Gold: - ret = 500; + maxProfileCount = 500; break; case SBAccountType.Platinum: - ret = 1000; + maxProfileCount = 1000; break; default: - ret = 5; + maxProfileCount = 5; break; - - - } - return ret; + return maxProfileCount; } public static int GetMaxGroupCount(SBAccountType accountType) @@ -130,6 +122,11 @@ public static DateTime ConvertFromUnixTimestamp(double timestamp) return origin.AddSeconds(timestamp); } + public static DateTime ConvertUnixTimeStamp(string unixTimeStamp) + { + return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp)); + } + public static double ConvertToUnixTimestamp(DateTime date) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); @@ -137,6 +134,24 @@ public static double ConvertToUnixTimestamp(DateTime date) return Math.Floor(diff.TotalSeconds); } + public static void ForEach(this IEnumerable items, Action action) + { + foreach (var item in items) + { + try + { + action(item); + } + catch (IOException io) + { + Console.WriteLine(io.Message); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + } } } diff --git a/src/Domain.Socioboard/Helpers/UrlRSSfeedsNews.cs b/src/Domain.Socioboard/Helpers/UrlRSSfeedsNews.cs index 012263f50..0547e94ef 100644 --- a/src/Domain.Socioboard/Helpers/UrlRSSfeedsNews.cs +++ b/src/Domain.Socioboard/Helpers/UrlRSSfeedsNews.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using System.Net; -using System.Threading.Tasks; namespace Domain.Socioboard.Helpers { diff --git a/src/Domain.Socioboard/Interfaces/Repositories/IMongoRepository.cs b/src/Domain.Socioboard/Interfaces/Repositories/IMongoRepository.cs index 9d0a985da..2d77f33c6 100644 --- a/src/Domain.Socioboard/Interfaces/Repositories/IMongoRepository.cs +++ b/src/Domain.Socioboard/Interfaces/Repositories/IMongoRepository.cs @@ -15,7 +15,7 @@ public interface IMongoRepository System.Linq.IQueryable All() where T : class, new(); System.Linq.IQueryable All(int page, int pageSize) where T : class, new(); Task Add(T item) where T : class, new(); - void Add(IEnumerable items) where T : class, new(); + void AddRange(IEnumerable collections) where T : class, new(); Task> Find(Expression> query) where T : class, new(); Task> FindAdvance(Expression> query) where T : class, new(); int Counts(Expression> query) where T : class, new(); diff --git a/src/Domain.Socioboard/Interfaces/Services/IEmailSender.cs b/src/Domain.Socioboard/Interfaces/Services/IEmailSender.cs index 56965206f..6b606efaa 100644 --- a/src/Domain.Socioboard/Interfaces/Services/IEmailSender.cs +++ b/src/Domain.Socioboard/Interfaces/Services/IEmailSender.cs @@ -8,7 +8,8 @@ namespace Domain.Socioboard.Interfaces.Services public interface IEmailSender { string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "", string Password = ""); - string SendMailSendGrid(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "", string Password = ""); + + string SendMailSendGrid(string from, string password, string to, string bcc, string cc, string subject, string body, string smtpClientUserName = "", string smtpClientPassword = ""); } } diff --git a/src/Domain.Socioboard/Models/DaywiseSchedule.cs b/src/Domain.Socioboard/Models/DaywiseSchedule.cs index 5c1b87c15..4d2c80a8e 100644 --- a/src/Domain.Socioboard/Models/DaywiseSchedule.cs +++ b/src/Domain.Socioboard/Models/DaywiseSchedule.cs @@ -17,7 +17,7 @@ public DaywiseSchedule() public virtual DateTime clientTime { get; set; } public virtual DateTime scheduleTime { get; set; } public virtual DateTime postedTime { get; set; } - public virtual string localscheduletime { get; set; } + public virtual DateTime localscheduletime { get; set; } public virtual Enum.ScheduleStatus status { get; set; } public virtual long userId { get; set; } public virtual Enum.SocialProfileType profileType { get; set; } diff --git a/src/Domain.Socioboard/Models/Facebookaccounts.cs b/src/Domain.Socioboard/Models/Facebookaccounts.cs index ef10a5442..488153f32 100644 --- a/src/Domain.Socioboard/Models/Facebookaccounts.cs +++ b/src/Domain.Socioboard/Models/Facebookaccounts.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Domain.Socioboard.Models { @@ -11,36 +8,63 @@ public Facebookaccounts() { IsAccessTokenActive = true; } - public virtual Int64 Id { get; set; } + public virtual long Id { get; set; } + public virtual string FbUserId { get; set; } + public virtual string FbUserName { get; set; } + public virtual string AccessToken { get; set; } - public virtual Int64 Friends { get; set; } + + public virtual long Friends { get; set; } + public virtual string EmailId { get; set; } - public virtual string coverPic { get; set; } - public virtual string birthday { get; set; } - public virtual string education { get; set; } - public virtual string college { get; set; } - public virtual string workPosition { get; set; } - public virtual string homeTown { get; set; } - public virtual string gender { get; set; } - public virtual string bio { get; set; } - public virtual string about { get; set; } - public virtual string workCompany { get; set; } - public virtual Domain.Socioboard.Enum.FbProfileType FbProfileType { get; set; } - public virtual Domain.Socioboard.Enum.FbPageSubscription FbPageSubscription { get; set; } + + public virtual string CoverPic { get; set; } + + public virtual string Birthday { get; set; } + + public virtual string Education { get; set; } + public virtual string College { get; set; } + + public virtual string WorkPosition { get; set; } + + public virtual string HomeTown { get; set; } + + public virtual string Gender { get; set; } + + public virtual string Bio { get; set; } + + public virtual string About { get; set; } + + public virtual string WorkCompany { get; set; } + + public virtual Enum.FbProfileType FbProfileType { get; set; } + + public virtual Enum.FbPageSubscription FbPageSubscription { get; set; } + public virtual string ProfileUrl { get; set; } + public virtual bool IsActive { get; set; } - public virtual Int64 UserId { get; set; } + + public virtual long UserId { get; set; } public virtual bool IsAccessTokenActive { get; set; } + public virtual DateTime LastUpdate { get; set;} + public virtual DateTime SchedulerUpdate { get; set; } + public virtual DateTime PageShareathonUpdate { get; set; } + public virtual DateTime GroupShareathonUpdate { get; set; } - public virtual DateTime lastpagereportgenerated { get; set; } + + public virtual DateTime LastPageReportGenerated { get; set; } + public virtual bool Is90DayDataUpdated { get; set; } - public virtual DateTime contenetShareathonUpdate { get; set; } + + public virtual DateTime ContentShareathonUpdate { get; set; } + public virtual bool SocailSignInEnable { get; set; } } diff --git a/src/Domain.Socioboard/Models/Listening/FacebookGroupPost.cs b/src/Domain.Socioboard/Models/Listening/FacebookGroupPost.cs index f58048b47..e07842947 100644 --- a/src/Domain.Socioboard/Models/Listening/FacebookGroupPost.cs +++ b/src/Domain.Socioboard/Models/Listening/FacebookGroupPost.cs @@ -15,7 +15,7 @@ public class FaceBookGroupPost [BsonId] [JsonConverter(typeof(ObjectIdConverter))] public ObjectId Id { get; set; } - public string GroupId { get; set; } + public long GroupId { get; set; } public string GroupName { get; set; } public long PostId { get; set; } public string UserProfileId { get; set; } diff --git a/src/Domain.Socioboard/Models/Mongo/FacebookPagePromotionDetails.cs b/src/Domain.Socioboard/Models/Mongo/FacebookPagePromotionDetails.cs index 634ace2e8..30c99c3d6 100644 --- a/src/Domain.Socioboard/Models/Mongo/FacebookPagePromotionDetails.cs +++ b/src/Domain.Socioboard/Models/Mongo/FacebookPagePromotionDetails.cs @@ -2,10 +2,6 @@ using Domain.Socioboard.Helpers; using MongoDB.Bson; using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Domain.Socioboard.Models.Mongo { diff --git a/src/Domain.Socioboard/Models/Mongo/MongoDirectMessages.cs b/src/Domain.Socioboard/Models/Mongo/MongoDirectMessages.cs new file mode 100644 index 000000000..25c478c5e --- /dev/null +++ b/src/Domain.Socioboard/Models/Mongo/MongoDirectMessages.cs @@ -0,0 +1,29 @@ +using Domain.Socioboard.Helpers; +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using Newtonsoft.Json; + +namespace Domain.Socioboard.Models.Mongo +{ + [BsonIgnoreExtraElements] + public class MongoDirectMessages + { + [JsonConverter(typeof(ObjectIdConverter))] + public ObjectId id { get; set; } + public string message { get; set; } + public string recipientId { get; set; } + public string recipientScreenName { get; set; } + public string recipientProfileUrl { get; set; } + public string createdDate { get; set; } + public double timeStamp { get; set; } + public string entryDate { get; set; } + public string senderId { get; set; } + public string senderScreenName { get; set; } + public string senderProfileUrl { get; set; } + public string profileId { get; set; } + public Domain.Socioboard.Enum.MessageType type { get; set; } + public string messageId { get; set; } + public string image { get; set; } + public string ConversationLink { get; set; } + } +} diff --git a/src/Domain.Socioboard/Models/Mongo/MongoMessageModel.cs b/src/Domain.Socioboard/Models/Mongo/MongoMessageModel.cs new file mode 100644 index 000000000..bb99c383e --- /dev/null +++ b/src/Domain.Socioboard/Models/Mongo/MongoMessageModel.cs @@ -0,0 +1,38 @@ +using Domain.Socioboard.Enum; +using Domain.Socioboard.Helpers; +using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using Newtonsoft.Json; + +namespace Domain.Socioboard.Models.Mongo +{ + [BsonIgnoreExtraElements] + public class MongoMessageModel + { + [BsonId] + [JsonConverter(typeof(ObjectIdConverter))] + public ObjectId id { get; set; } + public string Message { get; set; } + public string messageDate { get; set; } + public double messageTimeStamp { get; set; } // unix time stamp of messageDate + public string profileId { get; set; } + public string fromId { get; set; } + public string fromName { get; set; } + public string fromProfileUrl { get; set; } + public string screenName { get; set; } + public string messageId { get; set; } + public MessageType type { get; set; } + public string inReplyToStatusUserId { get; set; } + public string sourceUrl { get; set; } + public string fromScreenName { get; set; } + public int FollowerCount { get; set; } + public int FollowingCount { get; set; } + public int readStatus { get; set; } + public int isArchived { get; set; } + public double positive { get; set; } + public double negative { get; set; } + public string RecipientId { get; set; } + public string RecipientName { get; set; } + public string mediaUrl { get; set; } + } +} diff --git a/src/Domain.Socioboard/Models/Mongo/MongoTwitterFeed.cs b/src/Domain.Socioboard/Models/Mongo/MongoTwitterFeed.cs index f371eb414..c37bcd4c8 100644 --- a/src/Domain.Socioboard/Models/Mongo/MongoTwitterFeed.cs +++ b/src/Domain.Socioboard/Models/Mongo/MongoTwitterFeed.cs @@ -22,7 +22,7 @@ public class MongoTwitterFeed public string fromProfileUrl { get; set; } public string screenName { get; set; } public string messageId { get; set; } - public TwitterMessageType type { get; set; } + public MessageType type { get; set; } public string inReplyToStatusUserId { get; set; } public string sourceUrl { get; set; } public string fromScreenName { get; set; } diff --git a/src/Domain.Socioboard/Models/PaymentTransaction.cs b/src/Domain.Socioboard/Models/PaymentTransaction.cs index 792eaba14..7d3851880 100644 --- a/src/Domain.Socioboard/Models/PaymentTransaction.cs +++ b/src/Domain.Socioboard/Models/PaymentTransaction.cs @@ -22,5 +22,6 @@ public class PaymentTransaction public virtual string Payername { get; set; } public virtual string payeremail { get; set; } public virtual DateTime subscrdate { get; set; } + public virtual Int32 bluesnapSubscriptions { get; set; } } } diff --git a/src/Domain.Socioboard/Services/AuthMessageSender.cs b/src/Domain.Socioboard/Services/AuthMessageSender.cs index 907ee6899..916181a4e 100644 --- a/src/Domain.Socioboard/Services/AuthMessageSender.cs +++ b/src/Domain.Socioboard/Services/AuthMessageSender.cs @@ -14,7 +14,7 @@ namespace Domain.Socioboard.Services public class AuthMessageSender : IEmailSender, ISmsSender { - public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "mailer12@socioboardmails.com", string Password = "RDmgjwos165s") + public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "", string Password = "") { string response = ""; try @@ -50,32 +50,33 @@ public string SendMail(string from, string passsword, string to, string bcc, str } - public string SendMailSendGrid(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "SocioleadPro", string Password = "radium1234!@#$") + public string SendMailSendGrid(string from, string password, string to, string bcc, string cc, string subject, string body, string smtpClientUserName = "", string smtpClientPassword = "") { try { - try { - MailMessage mailMsg = new MailMessage(); + var mailMsg = new MailMessage(); // To mailMsg.To.Add(new MailAddress(to)); + if (!string.IsNullOrEmpty(cc)) { mailMsg.CC.Add(new MailAddress(cc)); } + // From mailMsg.From = new MailAddress(from); // Subject and multipart/alternative Body mailMsg.Subject = subject; - string html = @body; + var html = body; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); // Init SmtpClient and send - SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); - System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(UserName, Password); + var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); + var credentials = new NetworkCredential(smtpClientUserName, smtpClientPassword); smtpClient.Credentials = credentials; smtpClient.Send(mailMsg); @@ -86,15 +87,10 @@ public string SendMailSendGrid(string from, string passsword, string to, string Console.WriteLine(ex.Message); return "Mail Not Send"; } - - //string posturl = "https://api.sendgrid.com/api/mail.send.json"; - //string postdata = "api_user=" + UserName + "&api_key=" + Password + "&to=" + to + "&toname=" + to + "&subject=" + subject + "&text=" + body + "&from=" + from; - //string ret = ApiSendGridHttp(posturl, postdata); - //return ret; - return "success"; } catch (Exception ex) { + Console.WriteLine(ex.Message); return "Mail Not Send"; } } diff --git a/src/Domain.Socioboard/ViewModels/TwitterTopFansViewModel.cs b/src/Domain.Socioboard/ViewModels/TwitterTopFansViewModel.cs index dc5d484f8..61967af22 100644 --- a/src/Domain.Socioboard/ViewModels/TwitterTopFansViewModel.cs +++ b/src/Domain.Socioboard/ViewModels/TwitterTopFansViewModel.cs @@ -14,12 +14,12 @@ public class TwitterFan public int totalCount { get; set; } public TwitterFan() { } - public TwitterFan(List lstMongoTwitterMessage) + public TwitterFan(List lstMongoTwitterMessage) { screenName = lstMongoTwitterMessage.First().fromScreenName; name = lstMongoTwitterMessage.First().fromName; - mentionsCount = lstMongoTwitterMessage.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterMention); - retweetsCount = lstMongoTwitterMessage.Count(t => t.type == Domain.Socioboard.Enum.TwitterMessageType.TwitterRetweet); + mentionsCount = lstMongoTwitterMessage.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterMention); + retweetsCount = lstMongoTwitterMessage.Count(t => t.type == Domain.Socioboard.Enum.MessageType.TwitterRetweet); totalCount = lstMongoTwitterMessage.Count(); } } diff --git a/src/Domain.Socioboard/compiler/resources/Mappings/AgencyUser.hbm.xml b/src/Domain.Socioboard/compiler/resources/Mappings/AgencyUser.hbm.xml index ad84289b9..a6da4c101 100644 --- a/src/Domain.Socioboard/compiler/resources/Mappings/AgencyUser.hbm.xml +++ b/src/Domain.Socioboard/compiler/resources/Mappings/AgencyUser.hbm.xml @@ -1,4 +1,4 @@ - + - + diff --git a/src/Domain.Socioboard/compiler/resources/Mappings/Facebookaccounts.hbm.xml b/src/Domain.Socioboard/compiler/resources/Mappings/Facebookaccounts.hbm.xml index 963e168e4..36167fff2 100644 --- a/src/Domain.Socioboard/compiler/resources/Mappings/Facebookaccounts.hbm.xml +++ b/src/Domain.Socioboard/compiler/resources/Mappings/Facebookaccounts.hbm.xml @@ -20,34 +20,34 @@ - + - + - + - + - + - + - + - + - + - + @@ -80,13 +80,13 @@ - + - + diff --git a/src/Domain.Socioboard/compiler/resources/Mappings/PaymentTransaction.hbm.xml b/src/Domain.Socioboard/compiler/resources/Mappings/PaymentTransaction.hbm.xml index b9c882d61..752aa977e 100644 --- a/src/Domain.Socioboard/compiler/resources/Mappings/PaymentTransaction.hbm.xml +++ b/src/Domain.Socioboard/compiler/resources/Mappings/PaymentTransaction.hbm.xml @@ -44,5 +44,8 @@ + + + \ No newline at end of file diff --git a/src/Socioboard.Facebook/Auth/Authentication.cs b/src/Socioboard.Facebook/Auth/Authentication.cs index 5fbcf0e18..1d82653a3 100644 --- a/src/Socioboard.Facebook/Auth/Authentication.cs +++ b/src/Socioboard.Facebook/Auth/Authentication.cs @@ -5,26 +5,29 @@ namespace Socioboard.Facebook.Auth { public static class Authentication { - public static string getAccessToken(string client_id, string redirect_uri, string client_secret, string code) + public static string GetAccessToken(string clientId, string redirectUri, string clientSecret, string code) { - FacebookClient fb = new FacebookClient(); - string profileId = string.Empty; - Dictionary parameters = new Dictionary(); - parameters.Add("client_id", client_id); - parameters.Add("redirect_uri", redirect_uri); - parameters.Add("client_secret", client_secret); - parameters.Add("code", code); - JsonObject fbaccess_token = null; + var fb = new FacebookClient(); + + var parameters = new Dictionary + { + {"client_id", clientId}, + {"redirect_uri", redirectUri}, + {"client_secret", clientSecret}, + {"code", code} + }; + + JsonObject fbaccessToken; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; - fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters); - return fbaccess_token["access_token"].ToString(); - } + fbaccessToken = (JsonObject)fb.Get("/oauth/access_token", parameters); + return fbaccessToken["access_token"].ToString(); - public static string GetFacebookRedirectLink(string FacebookAuthUrl, string ClientId, string RedirectUrl) - { - return FacebookAuthUrl + "&client_id=" + ClientId + "&redirect_uri=" + RedirectUrl + "&response_type=code"; } + public static string GetFacebookRedirectLink(string facebookAuthUrl, string clientId, string redirectUrl) + => $"{facebookAuthUrl}&client_id={clientId}&redirect_uri={redirectUrl}&response_type=code"; + + } diff --git a/src/Socioboard.Facebook/Data/FacebookApiHelper.cs b/src/Socioboard.Facebook/Data/FacebookApiHelper.cs new file mode 100644 index 000000000..7d76220c4 --- /dev/null +++ b/src/Socioboard.Facebook/Data/FacebookApiHelper.cs @@ -0,0 +1,488 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using Domain.Socioboard.Enum; +using Domain.Socioboard.Models; +using Facebook; +using Newtonsoft.Json.Linq; +using Socioboard.Facebook.Utils; + +namespace Socioboard.Facebook.Data +{ + public class FacebookApiHelper + { + + /// + /// To get the own feed details + /// + /// valid access token of facebook while logged in + /// + public static dynamic GetOwnFeedDetails(string accessToken) + { + var fb = new FacebookClient { AccessToken = accessToken }; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/me/feed?limit=99&fields=picture,created_time,message,description,story,from,likes.summary(true),comments.summary(true),type,application"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return "Invalid Access Token"; + } + } + + public static dynamic GetResponse(string url, string accessToken) + { + try + { + var fb = new FacebookClient { AccessToken = accessToken }; + return fb.Get(url); + } + catch (Exception) + { + return string.Empty; + } + } + + /// + /// To get the facebook user details + /// + /// valid access token of facebook while logged in + /// + public static object GetUserDetails(string accessToken) + { + var fb = new FacebookClient { AccessToken = accessToken }; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/me?fields=id,about,birthday,cover,education,email,gender,hometown,name,first_name,last_name,work,picture"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return "Invalid Access Token"; + } + } + + /// + /// To get the friend count of an account + /// + /// valid access token of facebook while logged in + /// + public static long GetFriendCounts(string accessToken) + { + var fb = new FacebookClient { AccessToken = accessToken }; + dynamic friends = fb.Get($"{FbConstants.FacebookApiVersion}/me/friends"); + try + { + return Convert.ToInt64(friends["summary"]["total_count"].ToString()); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return 0; + } + } + + public static List GetFacebookGroups(string accessToken) + { + var lstAddFacebookGroup = new List(); + var fb = new FacebookClient { AccessToken = accessToken }; + + if (accessToken == null) + return lstAddFacebookGroup; + + try + { + dynamic output = fb.Get($"{FbConstants.FacebookApiVersion}/me/groups"); + foreach (var item in output["data"]) + { + try + { + var objAddFacebookGroup = + new FacebookGroup + { + ProfileGroupId = item["id"].ToString(), + Name = item["name"].ToString(), + AccessToken = accessToken + }; + lstAddFacebookGroup.Add(objAddFacebookGroup); + } + catch (Exception ex) + { + Console.WriteLine(ex.StackTrace); + } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.StackTrace); + return null; + } + return lstAddFacebookGroup; + } + + public static List GetOwnPagesDetails(string accessToken) + { + var lstPages = new List(); + var fb = new FacebookClient { AccessToken = accessToken }; + + dynamic output = fb.Get($"{FbConstants.FacebookApiVersion}/me/accounts"); + foreach (var item in output["data"]) + { + try + { + var objAddFacebookPage = new Facebookpage + { + ProfilePageId = item["id"].ToString(), + Name = item["name"].ToString(), + AccessToken = item["access_token"].ToString(), + Email = string.Empty + }; + try + { + dynamic postLike = fb.Get($"{FbConstants.FacebookApiVersion}/{objAddFacebookPage.ProfilePageId}?fields=likes,name,username,fan_count"); + objAddFacebookPage.LikeCount = postLike["fan_count"].ToString(); + } + catch (Exception ex) + { + objAddFacebookPage.LikeCount = "0"; + Console.WriteLine(ex.Message); + } + lstPages.Add(objAddFacebookPage); + } + catch (Exception ex) + { + Console.WriteLine(ex.StackTrace); + } + } + return lstPages; + } + + public static bool MakeSubscribedWithApp(string pageAccessToken) + { + try + { + var fb = new FacebookClient { AccessToken = pageAccessToken }; + fb.Post($"{FbConstants.FacebookApiVersion}/me/subscribed_apps"); + return true; + } + catch (Exception) + { + return false; + } + } + + public static string GetPageDetails(string pageAccessToken) + { + try + { + var fb = new FacebookClient { AccessToken = pageAccessToken }; + return fb.Get($"{FbConstants.FacebookApiVersion}/me/?fields=name,fan_count,id,picture").ToString(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return string.Empty; + } + } + + public static dynamic GetPosts(string accessToken) + { + var fb = new FacebookClient {AccessToken = accessToken }; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/" + "me/posts?limit=99&fields=picture,created_time,message,description,story,from,likes.summary(true),comments.summary(true),type,application"); + } + catch (Exception) + { + return string.Empty; + } + } + + public static string GetPageNotifications(string pageAccessToken) + { + var fb = new FacebookClient {AccessToken = pageAccessToken}; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/me/notifications/?fields=title,from,to,created_time").ToString(); + } + catch (Exception) + { + return string.Empty; + } + } + + public static string GetPromotablePostsDetails(string pageAccessToken) + { + var fb = new FacebookClient {AccessToken = pageAccessToken }; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/me/promotable_posts?fields=picture,created_time,message,description,from&limit=99").ToString(); + } + catch (Exception) + { + return string.Empty; + } + } + + public static string GetConversations(string pageAccessToken) + { + var fb = new FacebookClient {AccessToken = pageAccessToken}; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/me/conversations").ToString(); + } + catch (Exception) + { + return string.Empty; + } + } + + public static string GetPageTaggedDetails(string pageAccessToken) + { + var fb = new FacebookClient {AccessToken = pageAccessToken}; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/me/tagged?fields=picture,created_time,message,description,from&limit=99").ToString();//v2.6 + } + catch (Exception) + { + return string.Empty; + } + } + + public static bool PostMessage(string message, string accessToken, string fbUserId, string link) + { + var fb = new FacebookClient { AccessToken = accessToken }; + var args = new Dictionary { ["message"] = message, ["link"] = link }; + fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args); + return true; + } + + public static bool PublishPostOnSchedule(string message, string accessToken, string fbUserId, string link, string scheduleTime) + { + var fb = new FacebookClient { AccessToken = accessToken }; + var args = new Dictionary { ["message"] = message, ["link"] = link }; + + //, ["scheduled_publish_time"] = scheduleTime, ["published"] = "false" + fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args); + return true; + } + + public static string PublishPost(FbProfileType profileType, string accessToken, string fbUserId, string message, string profileId, string mediaPath, string link) + { + var fb = new FacebookClient { AccessToken = accessToken }; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; + + var args = new Dictionary(); + + if (!string.IsNullOrEmpty(message)) + args["message"] = message; + + if (profileType == FbProfileType.FacebookProfile) + args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId); + + try + { + if (string.IsNullOrEmpty(link)) + { + if (string.IsNullOrEmpty(mediaPath) && !string.IsNullOrEmpty(message)) + { + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args).ToString(); + } + + if (mediaPath != null && !mediaPath.Contains("mp4") && !mediaPath.Contains("mov") && !mediaPath.Contains("mpeg") && + !mediaPath.Contains("wmv") && !mediaPath.Contains("avi") && !mediaPath.Contains("flv") && + !mediaPath.Contains("3gp")) + { + var uri = new Uri(mediaPath); + var extension = Path.GetExtension(uri.AbsolutePath).Replace(".", ""); + + var media = new FacebookMediaObject + { + FileName = "filename", + ContentType = "image/" + extension + }; + + var webClient = new WebClient(); + var img = webClient.DownloadData(mediaPath); + media.SetValue(img); + args["source"] = media; + + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/photos", args).ToString(); + } + else + { + var extension = string.Empty; + + if (mediaPath != null) + { + var filename = + mediaPath.Substring(mediaPath.IndexOf("get?id=", StringComparison.Ordinal) + 7); + + if (!string.IsNullOrWhiteSpace(filename)) + { + extension = filename.Substring(filename.IndexOf(".", StringComparison.Ordinal) + 1); + } + + var media = new FacebookMediaObject + { + FileName = filename, + ContentType = "video/" + extension + }; + + var webClient = new WebClient(); + var img = webClient.DownloadData(mediaPath); + media.SetValue(img); + + args["source"] = media; + } + + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/videos", args).ToString(); + } + } + + args["link"] = link; + + if (!string.IsNullOrEmpty(mediaPath)) + args["picture"] = mediaPath.Replace("&", "&"); + try + { + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args).ToString(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + + } + return string.Empty; + } + + public static string PublishPostOnPage(string accessToken, string fbUserId, string message, string mediaPath, string link) + { + var fb = new FacebookClient { AccessToken = accessToken }; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; + + var args = new Dictionary(); + + if (!string.IsNullOrEmpty(message)) + args["message"] = message; + + try + { + if (string.IsNullOrEmpty(link)) + { + if (string.IsNullOrEmpty(mediaPath) && !string.IsNullOrEmpty(message)) + { + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args).ToString(); + } + + if (!mediaPath.Contains("mp4") && !mediaPath.Contains("mov") && !mediaPath.Contains("mpeg") && + !mediaPath.Contains("wmv") && !mediaPath.Contains("avi") && !mediaPath.Contains("flv") && + !mediaPath.Contains("3gp")) + { + var uri = new Uri(mediaPath); + var extension = Path.GetExtension(uri.AbsolutePath).Replace(".", ""); + + var media = new FacebookMediaObject + { + FileName = "filename", + ContentType = "image/" + extension + }; + + var webClient = new WebClient(); + var img = webClient.DownloadData(mediaPath); + media.SetValue(img); + args["source"] = media; + + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/photos", args).ToString(); + } + else + { + var extension = string.Empty; + + var filename = + mediaPath.Substring(mediaPath.IndexOf("get?id=", StringComparison.Ordinal) + 7); + + if (!string.IsNullOrWhiteSpace(filename)) + { + extension = filename.Substring(filename.IndexOf(".", StringComparison.Ordinal) + 1); + } + + var media = new FacebookMediaObject + { + FileName = filename, + ContentType = "video/" + extension + }; + + var webClient = new WebClient(); + var img = webClient.DownloadData(mediaPath); + media.SetValue(img); + + args["source"] = media; + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/videos", args).ToString(); + } + } + + args["link"] = link; + + if (!string.IsNullOrEmpty(mediaPath)) + args["picture"] = mediaPath.Replace("&", "&"); + try + { + return fb.Post($"{FbConstants.FacebookApiVersion}/" + fbUserId + "/feed", args).ToString(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + + } + return string.Empty; + } + + public static string GetPageAccessToken(string pageId, string accessToken, string message) + { + try + { + var fb = new FacebookClient { AccessToken = accessToken }; + + var pageAccessTokenResponse = JObject.Parse(fb.Get($"{FbConstants.FacebookApiVersion}/{pageId}/?fields=access_token").ToString()); + + return pageAccessTokenResponse["access_token"].ToString(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return string.Empty; + } + } + + public static dynamic GetPostsLikeCommentShareCount(string accessToken, string postId, string profileId) + { + var fb = new FacebookClient { AccessToken = accessToken }; + try + { + return fb.Get($"{FbConstants.FacebookApiVersion}/" + $"{profileId}_{postId}" + "?fields=likes.summary(true),comments.summary(true),shares"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return "Invalid Access Token"; + } + } + + } +} \ No newline at end of file diff --git a/src/Socioboard.Facebook/Data/FbUser.cs b/src/Socioboard.Facebook/Data/FbUser.cs index 0aa79c4ea..f2f7a11f5 100644 --- a/src/Socioboard.Facebook/Data/FbUser.cs +++ b/src/Socioboard.Facebook/Data/FbUser.cs @@ -2,6 +2,7 @@ using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; +using Socioboard.Facebook.Utils; namespace Socioboard.Facebook.Data { @@ -13,7 +14,7 @@ public static object getFbUser(string accessToken) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/me?fields=id,about,bio,birthday,cover,education,email,gender,hometown,name,first_name,last_name,work,picture");//v2.6 + return fb.Get($"{FbConstants.FacebookApiVersion}/me?fields=id,about,birthday,cover,education,email,gender,hometown,name,first_name,last_name,work,picture");//v2.6 } catch (Exception ex) { @@ -25,7 +26,7 @@ public static Int64 getFbFriends(string accessToken) { FacebookClient fb = new FacebookClient(); fb.AccessToken = accessToken; - dynamic friends = fb.Get("v2.7/me/friends");//v2.1 + dynamic friends = fb.Get($"{FbConstants.FacebookApiVersion}/me/friends");//v2.1 try { return Convert.ToInt64(friends["summary"]["total_count"].ToString()); @@ -42,7 +43,8 @@ public static dynamic getFeeds(string accessToken) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/me/feed?limit=99&fields=picture,created_time,message,description,story,from,likes.summary(true),comments.summary(true),type,application");//v2.1 + var details = fb.Get($"{FbConstants.FacebookApiVersion}/me/feed?limit=99&fields=picture,created_time,message,description,story,from,likes.summary(true),comments.summary(true),type,application");//v2.1 + return details; } catch (Exception ex) { @@ -57,7 +59,7 @@ public static dynamic getFeeds(string accessToken, string facebookid) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/" + facebookid + "/posts?limit=99");//v2.1 + return fb.Get($"{FbConstants.FacebookApiVersion}/" + facebookid + "/posts?limit=99");//v2.1 } catch (Exception ex) { @@ -71,7 +73,7 @@ public static dynamic getFeedDetail(string accessToken, string PostId) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/" + PostId + "?fields=likes.summary(true),comments.summary(true),shares");//v2.1 + return fb.Get($"{FbConstants.FacebookApiVersion}/" + PostId + "?fields=likes.summary(true),comments.summary(true),shares");//v2.1 } catch (Exception ex) { @@ -84,7 +86,7 @@ public static dynamic postdetails(string accessToken, string PostId) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/" + PostId + "/insights");//v2.1 + return fb.Get($"{FbConstants.FacebookApiVersion}/" + PostId + "/insights");//v2.1 } catch (Exception ex) { @@ -99,7 +101,7 @@ public static dynamic conversations(string accessToken) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/me/conversations");//v2.1 + return fb.Get($"{FbConstants.FacebookApiVersion}/me/conversations");//v2.1 } catch (Exception ex) { @@ -113,7 +115,7 @@ public static dynamic notifications(string accessToken) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/me/notifications");//v2.1 + return fb.Get($"{FbConstants.FacebookApiVersion}/me/notifications");//v2.1 } catch (Exception ex) { @@ -121,33 +123,33 @@ public static dynamic notifications(string accessToken) } } - public static dynamic getPostComments(string accessToken, string postid) + public static dynamic GetPostComments(string accessToken, string postid) { - FacebookClient fb = new FacebookClient(); - fb.AccessToken = accessToken; + var fb = new FacebookClient {AccessToken = accessToken}; try { - return fb.Get("v2.7/" + postid + "/comments?limit=99");//v2.1 + return fb.Get($"{FbConstants.FacebookApiVersion}/" + postid + "/comments?limit=99");//v2.1 } catch (Exception ex) { + Console.WriteLine(ex.Message); return "Invalid Access Token"; } } - public static string postComments(string accessToken, string postid, string message) + public static string PostComments(string accessToken, string postid, string message) { - var args = new Dictionary(); - FacebookClient fb = new FacebookClient(); - fb.AccessToken = accessToken; - args["message"] = message; + var args = new Dictionary {["message"] = message}; + var fb = new FacebookClient {AccessToken = accessToken}; + try { - return fb.Post("v2.7/" + postid + "/comments", args).ToString();//v2.1 + return fb.Post($"{FbConstants.FacebookApiVersion}/" + postid + "/comments", args).ToString();//v2.1 } catch (Exception ex) { + Console.WriteLine(ex.Message); return "Invalid Access Token"; } } @@ -172,7 +174,7 @@ public static dynamic getPageTaggedPostDetails(string accessToken) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/me/tagged?fields=picture,created_time,message,description,from&limit=99");//v2.6 + return fb.Get($"{FbConstants.FacebookApiVersion}/me/tagged?fields=picture,created_time,message,description,from&limit=99");//v2.6 } catch (Exception ex) { @@ -186,7 +188,7 @@ public static dynamic getPromotablePostsDetails(string accessToken) fb.AccessToken = accessToken; try { - return fb.Get("v2.7/me/promotable_posts?fields=picture,created_time,message,description,from&limit=99");//v2.6 + return fb.Get($"{FbConstants.FacebookApiVersion}/me/promotable_posts?fields=picture,created_time,message,description,from&limit=99");//v2.6 } catch (Exception ex) { @@ -194,10 +196,6 @@ public static dynamic getPromotablePostsDetails(string accessToken) } } - - - - public static string SetPrivacy(string privacy, FacebookClient fb, string fbUserId) { try diff --git a/src/Socioboard.Facebook/Data/Fbpages.cs b/src/Socioboard.Facebook/Data/Fbpages.cs index a425c963b..560d97ccf 100644 --- a/src/Socioboard.Facebook/Data/Fbpages.cs +++ b/src/Socioboard.Facebook/Data/Fbpages.cs @@ -5,6 +5,7 @@ using System.IO; using System.Net; using System.Text; +using Socioboard.Facebook.Utils; namespace Socioboard.Facebook.Data { @@ -12,26 +13,27 @@ public class Fbpages { public static List Getfacebookpages(string accesstoken) { - List lstpages = new List(); - FacebookClient fb = new FacebookClient(); - fb.AccessToken = accesstoken; - dynamic profile = fb.Get("v2.7/me");//v2.1 - dynamic output = fb.Get("v2.7/me/accounts");//v2.1 + var lstpages = new List(); + var fb = new FacebookClient { AccessToken = accesstoken }; + dynamic profile = fb.Get($"{FbConstants.FacebookApiVersion}/me"); + dynamic output = fb.Get($"{FbConstants.FacebookApiVersion}/me/accounts"); foreach (var item in output["data"]) { try { - Domain.Socioboard.Models.Facebookpage objAddFacebookPage = new Domain.Socioboard.Models.Facebookpage(); - objAddFacebookPage.ProfilePageId = item["id"].ToString(); + var objAddFacebookPage = new Domain.Socioboard.Models.Facebookpage + { + ProfilePageId = item["id"].ToString() + }; try { - dynamic postlike = fb.Get("v2.7/" + item["id"] + "?fields=likes,name,username,fan_count"); + dynamic postlike = fb.Get($"{FbConstants.FacebookApiVersion}/" + item["id"] + "?fields=likes,name,username,fan_count"); objAddFacebookPage.LikeCount = postlike["fan_count"].ToString(); } catch (Exception ex) { objAddFacebookPage.LikeCount = "0"; - + Console.WriteLine(ex.Message); } objAddFacebookPage.Name = item["name"].ToString(); objAddFacebookPage.AccessToken = item["access_token"].ToString(); @@ -41,7 +43,8 @@ public class Fbpages } catch (Exception ex) { - objAddFacebookPage.Email = ""; + objAddFacebookPage.Email = string.Empty; + Console.WriteLine(ex.Message); } lstpages.Add(objAddFacebookPage); } @@ -53,55 +56,54 @@ public class Fbpages return lstpages; } - - public static object getFbPageData(string accessToken) + public static object GetFbPageData(string accessToken) { - FacebookClient fb = new FacebookClient(); - fb.AccessToken = accessToken; - + var fb = new FacebookClient { AccessToken = accessToken }; try { - return fb.Get("v2.7/me?fields=id,name,username,likes,fan_count,cover,emails"); + // username, emails, fan_count are deprecated,so removed in following request + // before fb.Get($"{FbConstants.FacebookApiVersion}/me?fields=id,name,username,likes,fan_count,cover,emails"); + + return fb.Get($"{FbConstants.FacebookApiVersion}/me?fields=id,name,likes,cover"); } catch (Exception ex) { + Console.WriteLine(ex.Message); return "Invalid Access Token"; } } - public static string getFbPageData(string accessToken,string PageId) + + public static string GetFbPageName(string accessToken, string pageId) { - FacebookClient fb = new FacebookClient(); - fb.AccessToken = accessToken; + var fb = new FacebookClient { AccessToken = accessToken }; try { - dynamic profile= fb.Get("v2.7/"+ PageId + "?fields=id,name"); - return profile["name"].ToString(); + dynamic profile = fb.Get($"{FbConstants.FacebookApiVersion}/" + pageId + "?fields=id,name"); + return profile["name"].ToString(); } catch (Exception ex) { + Console.WriteLine(ex.Message); return ""; } } - public static List GetFacebookFanAdds(string profileId, double Since, double Until) + public static string GetPosts(string accessToken, string id, string paginationUrl) { - List FbFansList = new List(); - - return FbFansList; + var fb = new FacebookClient { AccessToken = accessToken }; + try + { + return string.IsNullOrEmpty(paginationUrl) + ? fb.Get($"{FbConstants.FacebookApiVersion}/" + id + "/posts?limit=30").ToString() + : fb.Get(paginationUrl).ToString(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return ""; + } } - //public static dynamic subscribed_apps(string accessToken) - //{ - // FacebookClient fb = new FacebookClient(); - // fb.AccessToken = accessToken; - // try - // { - // return fb.Post("v2.7/me/subscribed_apps");//v2.6 - // } - // catch (Exception ex) - // { - // return "Invalid Access Token"; - // } - //} + public static string getFacebookRecentPost(string fbAccesstoken, string pageId) { string output = string.Empty; @@ -129,7 +131,7 @@ public static string getFacebookRecentPost(string fbAccesstoken, string pageId) return output; } - public static string getFacebookPageRecentPost(string fbAccesstoken, string pageId,string curser_next) + public static string getFacebookPageRecentPost(string fbAccesstoken, string pageId, string curser_next) { string output = string.Empty; string facebookSearchUrl = string.Empty; @@ -163,6 +165,7 @@ public static string getFacebookPageRecentPost(string fbAccesstoken, string page } return output; } + public static string subscribed_apps(string fbAccesstoken, string pageId) { string output = string.Empty; @@ -185,27 +188,31 @@ public static string subscribed_apps(string fbAccesstoken, string pageId) } catch (Exception e) { - + Console.WriteLine(e.Message); } return output; } - public static string schedulePage_Post(string accessToken,string link,string scheduled_publish_time) + public static string schedulePage_Post(string accessToken, string link, string scheduled_publish_time) { - FacebookClient fb = new FacebookClient(); - var args = new Dictionary(); - args["link"] = link; - args["scheduled_publish_time"] = scheduled_publish_time; - args["published"] = "false"; - fb.AccessToken = accessToken; + var fb = new FacebookClient { AccessToken = accessToken }; + var args = new Dictionary + { + ["link"] = link, + ["scheduled_publish_time"] = scheduled_publish_time, + ["published"] = "false" + }; + try { - return fb.Post("v2.8/me/feed",args).ToString();//v2.6 + return fb.Post("v2.8/me/feed", args).ToString();//v2.6 } catch (Exception ex) { + Console.WriteLine(ex.Message); return ""; } } + } } diff --git a/src/Socioboard.Facebook/Utils/FbConstants.cs b/src/Socioboard.Facebook/Utils/FbConstants.cs new file mode 100644 index 000000000..5c74cc129 --- /dev/null +++ b/src/Socioboard.Facebook/Utils/FbConstants.cs @@ -0,0 +1,8 @@ +namespace Socioboard.Facebook.Utils +{ + public class FbConstants + { + public static string FacebookApiVersion = "v3.1"; + + } +} \ No newline at end of file diff --git a/src/Socioboard.Google/Youtube.Core/Channels.cs b/src/Socioboard.Google/Youtube.Core/Channels.cs index 0987e7985..de69c152d 100644 --- a/src/Socioboard.Google/Youtube.Core/Channels.cs +++ b/src/Socioboard.Google/Youtube.Core/Channels.cs @@ -102,7 +102,5 @@ public string Get_Channel_List_serarch(string accesstoken, string search) } - - } } diff --git a/src/Socioboard.LinkedIn/App.Core/LinkedinPageUpdate.cs b/src/Socioboard.LinkedIn/App.Core/LinkedinPageUpdate.cs index d4f05953d..00e1cf26e 100644 --- a/src/Socioboard.LinkedIn/App.Core/LinkedinPageUpdate.cs +++ b/src/Socioboard.LinkedIn/App.Core/LinkedinPageUpdate.cs @@ -33,168 +33,77 @@ public struct CompanyPagePosts } public List GetPagePosts(oAuthLinkedIn OAuth, string CompanyPageId) { - CompanyPagePosts companypage_post = new CompanyPagePosts(); - Company companyConnection = new Company(); - - string companyPageData = companyConnection.GetLinkedIN_CompanyUpdateById(OAuth, CompanyPageId); - var Company_Data = JObject.Parse(companyPageData); - #region XmlParsing - //xmlResult = companyConnection.Get_CompanyUpdateById(OAuth, CompanyPageId); - - //XmlNodeList xmlNodeList = xmlResult.GetElementsByTagName("update"); - //foreach (XmlNode xn in xmlNodeList) - //{ - - // try - // { - // XmlElement Element = (XmlElement)xn; - - - - // try - // { - // companypage_post.Type = Element.GetElementsByTagName("update-type")[0].InnerText; - // } - // catch - // { } - // try - // { - // companypage_post.UpdateKey = Element.GetElementsByTagName("update-key")[0].InnerText; - // } - // catch - // { } - // try - // { - // companypage_post.PostId = Element.GetElementsByTagName("service-provider-share-id")[0].InnerText; - // } - // catch - // { - - // } - - // try - // { - // double timestamp = Convert.ToDouble(Element.GetElementsByTagName("timestamp")[0].InnerText); - // companypage_post.PostDate = JavaTimeStampToDateTime(timestamp); - // } - // catch - // { + var companypagePost = new CompanyPagePosts(); + var companyConnection = new Company(); - // } - // try - // { - // companypage_post.Posts = Element.GetElementsByTagName("comment")[0].InnerText; - // } - // catch - // { + var companyPageData = companyConnection.GetLinkedIN_CompanyUpdateById(OAuth, CompanyPageId); + var companyData = JObject.Parse(companyPageData); - // } - // try - // { - // companypage_post.PostImageUrl = Element.GetElementsByTagName("shortened-url")[0].InnerText; - // } - // catch - // { - // companypage_post.PostImageUrl = null; - // } + if(companyData["values"]==null) + return CompanyPagePostsList; - // try - // { - // string likes = Element.GetElementsByTagName("num-likes")[0].InnerText; - // companypage_post.Likes = Convert.ToInt16(likes); - // } - // catch - // { - // } - // try - // { - // string cnt = string.Empty; - // XmlElement numofcomments = xmlResult.DocumentElement; - // if (numofcomments.HasAttribute("total")) - // { - // cnt = numofcomments.GetAttribute("total"); - // } - // companypage_post.Comments = Convert.ToInt16(cnt); - // } - // catch - // { - // } - - - - // CompanyPagePostsList.Add(companypage_post); - // } - // catch { } - //} - #endregion - - foreach (var item in Company_Data["values"]) + foreach (var item in companyData["values"]) { try { - companypage_post.Type = item["updateType"].ToString(); - + companypagePost.Type = item["updateType"].ToString(); } catch { } try { - companypage_post.UpdateKey = item["updateKey"].ToString(); - + companypagePost.UpdateKey = item["updateKey"].ToString(); } catch { } try { - companypage_post.PostId = item["updateContent"]["companyStatusUpdate"]["share"]["id"].ToString(); - + companypagePost.PostId = item["updateContent"]["companyStatusUpdate"]["share"]["id"].ToString(); } catch { } try { - companypage_post.Posts = item["updateContent"]["companyStatusUpdate"]["share"]["comment"].ToString(); - + companypagePost.Posts = item["updateContent"]["companyStatusUpdate"]["share"]["comment"].ToString(); } catch { } try { string datetime=item["updateContent"]["companyStatusUpdate"]["share"]["timestamp"].ToString(); - companypage_post.PostDate = JavaTimeStampToDateTime(double.Parse(datetime)); - - } + companypagePost.PostDate = JavaTimeStampToDateTime(double.Parse(datetime)); + } catch { } try { - companypage_post.PostImageUrl = item["updateContent"]["companyStatusUpdate"]["share"]["content"]["thumbnailUrl"].ToString(); + companypagePost.PostImageUrl = item["updateContent"]["companyStatusUpdate"]["share"]["content"]["thumbnailUrl"].ToString(); } catch { - companypage_post.PostImageUrl = ""; + companypagePost.PostImageUrl = ""; } try { string likes = item["numLikes"].ToString(); - companypage_post.Likes = Convert.ToInt16(likes); + companypagePost.Likes = Convert.ToInt16(likes); } catch { } try { - string url = "https://api.linkedin.com/v1/companies/" + CompanyPageId + "/updates/key=" + companypage_post.UpdateKey + "/update-comments?format=json"; + string url = "https://api.linkedin.com/v1/companies/" + CompanyPageId + "/updates/key=" + companypagePost.UpdateKey + "/update-comments?format=json"; string response = OAuth.APIWebRequest("GET", url, null); var comment = JObject.Parse(response); string Comments = comment["_total"].ToString(); - companypage_post.Comments = Convert.ToInt16(Comments); + companypagePost.Comments = Convert.ToInt16(Comments); } catch { } - CompanyPagePostsList.Add(companypage_post); + CompanyPagePostsList.Add(companypagePost); } return CompanyPagePostsList; diff --git a/src/Socioboard.Twitter/App.Core/Globals.cs b/src/Socioboard.Twitter/App.Core/Globals.cs index b6e845a3a..99ef47a3a 100644 --- a/src/Socioboard.Twitter/App.Core/Globals.cs +++ b/src/Socioboard.Twitter/App.Core/Globals.cs @@ -86,6 +86,9 @@ public static class Globals public static string GetDirectMessagesShowUrl = "https://api.twitter.com/1.1/direct_messages/show.json"; public static string PostDirectMessagesDestroyUrl = "https://api.twitter.com/1.1/direct_messages/destroy.json"; public static string PostDirectMesagesNewUrl = "https://api.twitter.com/1.1/direct_messages/new.json"; + + public static string TwitterPostDirectMessageUrl = "https://api.twitter.com/1.1/direct_messages/events/new.json"; + #endregion #region Account Methods diff --git a/src/Socioboard.Twitter/App.Core/PhotoUpload.cs b/src/Socioboard.Twitter/App.Core/PhotoUpload.cs index 9f9eca08b..211aad225 100644 --- a/src/Socioboard.Twitter/App.Core/PhotoUpload.cs +++ b/src/Socioboard.Twitter/App.Core/PhotoUpload.cs @@ -305,25 +305,19 @@ public bool NewTweet(string imageFile, string message, oAuthTwitter oAuth, ref s } - try - { - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - // HttpContext.Current.Response.Write(""); - if (response.StatusCode == HttpStatusCode.OK) - { - bupdated = true; - } + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) + { + // HttpContext.Current.Response.Write(""); - myfunctioncalled = myfunctioncalled + "myfunctioncalled: " + response.ToString(); + if (response.StatusCode == HttpStatusCode.OK) + { + bupdated = true; } + myfunctioncalled = myfunctioncalled + "myfunctioncalled: " + response.ToString(); } - catch (Exception ex) - { - } } @@ -332,6 +326,8 @@ public bool NewTweet(string imageFile, string message, oAuthTwitter oAuth, ref s myfunctioncalled = myfunctioncalled + "myfunctioncalled: " + ex.Message + ">>> " + ex.StackTrace; Console.WriteLine(ex.Message); // logger.Error(ex.Message); + + } diff --git a/src/Socioboard.Twitter/Authentication/oAuthTwitter.cs b/src/Socioboard.Twitter/Authentication/oAuthTwitter.cs index a45e886ce..105f36456 100644 --- a/src/Socioboard.Twitter/Authentication/oAuthTwitter.cs +++ b/src/Socioboard.Twitter/Authentication/oAuthTwitter.cs @@ -12,10 +12,21 @@ namespace Socioboard.Twitter.Authentication { public class oAuthTwitter : OAuthBase { - // ILog logger = LogManager.GetLogger(typeof(oAuthTwitter)); - public enum Method { GET, POST, DELETE }; - public const string REQUEST_TOKEN = "https://api.twitter.com/oauth/request_token"; - public const string AUTHORIZE = "https://api.twitter.com/oauth/authorize"; + // ILog logger = LogManager.GetLogger(typeof(oAuthTwitter)); + public enum Method + { + GET, + POST, + DELETE + } + // OAuth.OAuthRequest oauth = new OAuth.OAuthRequest(); + #region Properties + + + public const string RequestToken = "https://api.twitter.com/oauth/request_token"; + + public const string Authorize = "https://api.twitter.com/oauth/authorize"; + public const string ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token"; private string _consumerKey = ""; @@ -26,12 +37,11 @@ public enum Method { GET, POST, DELETE }; private string _oauthVerifier = ""; private string _twitterUser = ""; private string _profileimage = ""; - // OAuth.OAuthRequest oauth = new OAuth.OAuthRequest(); - #region Properties - public const string OauthVersion = "1.0"; + public const string OauthSignatureMethod = "HMAC-SHA1"; + public string CallBackUrl { get; set; } public string ConsumerKey { set; get; } public string ConsumerKeySecret { set; get; } @@ -40,36 +50,36 @@ public enum Method { GET, POST, DELETE }; public string OAuthVerifer { get; set; } public string TwitterScreenName { get { return _twitterUser; } set { _twitterUser = value; } } public string ProfileImage { get { return _profileimage; } set { _profileimage = value; } } - public string TwitterUserId{ get; set;} + public string TwitterUserId { get; set; } - #endregion public oAuthTwitter() - { - + { + } - public oAuthTwitter(string consumerkey,string consumerSecret) + public oAuthTwitter(string consumerkey, string consumerSecret) { - this.ConsumerKey = consumerkey; - this.ConsumerKeySecret = consumerSecret; + ConsumerKey = consumerkey; + ConsumerKeySecret = consumerSecret; } - public oAuthTwitter(string consumerkey, string consumerSecret,string callbackUrl) + public oAuthTwitter(string consumerkey, string consumerSecret, string callbackUrl) { - this.CallBackUrl = callbackUrl; - this.ConsumerKey = consumerkey; - this.ConsumerKeySecret = consumerSecret; + CallBackUrl = callbackUrl; + ConsumerKey = consumerkey; + ConsumerKeySecret = consumerSecret; } - public oAuthTwitter(string consumerkey, string consumerSecret,string oauthToken,string oauthTokenSecret) + + public oAuthTwitter(string consumerkey, string consumerSecret, string oauthToken, string oauthTokenSecret) { - this.AccessTokenSecret = oauthTokenSecret; - this.AccessToken = oauthToken; - this.ConsumerKey = consumerkey; - this.ConsumerKeySecret = consumerSecret; + AccessTokenSecret = oauthTokenSecret; + AccessToken = oauthToken; + ConsumerKey = consumerkey; + ConsumerKeySecret = consumerSecret; } @@ -85,7 +95,7 @@ public string AuthorizationLinkGet() try { SortedDictionary slt = new SortedDictionary(); - string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, slt); + string response = OAuthWebRequest(Method.GET, RequestToken, slt); if (response.Length > 0) { //response contains token and token secret. We only need the token. @@ -101,7 +111,7 @@ public string AuthorizationLinkGet() if (qs["oauth_token"] != null) { - ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"]; + ret = Authorize + "?oauth_token=" + qs["oauth_token"]; } } } @@ -117,104 +127,88 @@ public string AuthorizationLinkGet() /// /// The oauth_token is supplied by Twitter's authorization page following the callback. /// An oauth_verifier parameter is provided to the client either in the pre-configured callback URL - public void AccessTokenGet(string authToken, string oauthVerifier) + public void GetTwitterAccessToken(string authToken, string oauthVerifier) { try { string resourceUrl = string.Format(ACCESS_TOKEN); - var requestParameters = new SortedDictionary(); - requestParameters.Add("oauth_consumer_key", this.ConsumerKey); - requestParameters.Add("oauth_token", this.AccessToken); - requestParameters.Add("oauth_signature_method", "HMA-SHA1"); - requestParameters.Add("oauth_verifier", oauthVerifier); - string oauthnonce = this.CreateOauthNonce(); - string timestamp = CreateOAuthTimestamp(); + var requestParameters = new SortedDictionary + { + {"oauth_consumer_key", ConsumerKey}, + {"oauth_token", AccessToken}, + {"oauth_signature_method", "HMA-SHA1"}, + {"oauth_verifier", oauthVerifier} + }; + + var oauthnonce = CreateOauthNonce(); + var timestamp = CreateOAuthTimestamp(); requestParameters.Add("oauth_nonce", oauthnonce); requestParameters.Add("oauth_version", OauthVersion); - string signature = this.CreateOauthSignature(resourceUrl, Method.POST, oauthnonce, timestamp, requestParameters); + var signature = CreateOauthSignature(resourceUrl, Method.POST, oauthnonce, timestamp, requestParameters); requestParameters.Add("oauth_signature", signature); - var response = oAuthWebRequest(Method.POST, resourceUrl, requestParameters); + var response = OAuthWebRequest(Method.POST, resourceUrl, requestParameters); + if (response.Length > 0) { - NameValueCollection qs = HttpUtility.ParseQueryString(response); - this.AccessToken = qs["oauth_token"]; - this.AccessTokenSecret = qs["oauth_token_secret"]; - this.TwitterScreenName = qs["screen_name"]; - this.TwitterUserId = qs["user_id"]; + var qs = HttpUtility.ParseQueryString(response); + AccessToken = qs["oauth_token"]; + AccessTokenSecret = qs["oauth_token_secret"]; + TwitterScreenName = qs["screen_name"]; + TwitterUserId = qs["user_id"]; } + } catch (Exception ex) { - // logger.Error(ex.StackTrace); + Console.WriteLine(ex.Message); } } - - - - - - - - /// /// Submit a web request using oAuth. /// /// GET or POST - /// The full url, including the querystring. - /// Data to post (querystring format) + /// The full url, including the querystring. + /// Data to post /// The web server response. - public string oAuthWebRequest(Method method, string resourceUrl, SortedDictionary requestParameters) + public string OAuthWebRequest(Method method, string resourceUrl, SortedDictionary requestParameters) { - - string resultString = string.Empty; - + var resultString = string.Empty; try { ServicePointManager.Expect100Continue = false; HttpWebRequest request = null; - - - if (method == Method.POST) + switch (method) { - var postBody = requestParameters.ToWebString(); - - request = (HttpWebRequest)WebRequest.Create(resourceUrl); - request.Method = method.ToString(); - //if (resourceUrl == Globals.StatusUpdateUrl) - //{ - // request.ContentType = "multipart/form-data; type=\"image/jpeg\"; start=\"\";boundary=\"--0246824681357ACXZabcxyz\""; - - //} - request.ContentType = "application/x-www-form-urlencoded"; - request.ProtocolVersion = HttpVersion.Version11; - using (var stream = request.GetRequestStream()) + case Method.POST: { - byte[] content = Encoding.ASCII.GetBytes(postBody); - stream.Write(content, 0, content.Length); + var postBody = requestParameters.ToWebString(); + request = (HttpWebRequest)WebRequest.Create(resourceUrl); + request.Method = method.ToString(); + request.ContentType = "application/x-www-form-urlencoded"; + request.ProtocolVersion = HttpVersion.Version11; + using (var stream = request.GetRequestStream()) + { + var content = Encoding.ASCII.GetBytes(postBody); + stream.Write(content, 0, content.Length); + } + break; } - } - else if (method == Method.GET) - { - request = (HttpWebRequest)WebRequest.Create(resourceUrl + "?" - + requestParameters.ToWebString()); - request.Method = method.ToString(); - - } - else - { - //other verbs can be addressed here... + case Method.GET: + request = (HttpWebRequest)WebRequest.Create(resourceUrl + "?" + requestParameters.ToWebString()); + request.Method = method.ToString(); + break; + default: + break; } if (request != null) { - var authHeader = CreateHeader(resourceUrl, method, requestParameters); request.Headers.Add("Authorization", authHeader); - var response = request.GetResponse(); - + var response = request.GetResponse(); using (var sd = new StreamReader(response.GetResponseStream())) { resultString = sd.ReadToEnd(); @@ -231,33 +225,57 @@ public string oAuthWebRequest(Method method, string resourceUrl, SortedDictionar } + public string SendDirectMessage(string url,string recipientId,string Message, SortedDictionary requestParameters) + { + var resultString = string.Empty; + try + { + + ServicePointManager.Expect100Continue = false; + HttpWebRequest request = null; + var authHeader = CreateHeader(url, Method.POST, requestParameters); + request = (HttpWebRequest)WebRequest.Create(url); + WebHeaderCollection headers = new WebHeaderCollection(); + headers.Add("authorization: " + authHeader); + + request.Headers = headers; + + request.ContentType = "application/json"; + request.MediaType = "application/json"; + request.Accept = "application/json"; + request.Method = "POST"; + + var postBody = "{\"event\": {\"type\": \"message_create\", \"message_create\": {\"target\": {\"recipient_id\": \""+ recipientId .ToString()+ "\"}, \"message_data\": {\"text\": \""+ Message .ToString()+ "\"}}}}"; + + var content = Encoding.ASCII.GetBytes(postBody); + request.ContentLength = content.Length; + + using (var stream = request.GetRequestStream()) + { + stream.Write(content, 0, content.Length); + } + var response = request.GetResponse(); + using (var sd = new StreamReader(response.GetResponseStream())) + { + resultString = sd.ReadToEnd(); + response.Close(); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + return resultString; + } + public string oAuthWebRequest(Method method, string resourceUrl, string hello) => "hello"; - - - - - - - - - - - - public string oAuthWebRequest(Method method, string resourceUrl, string hello) - { - - return "hello"; - } - public string CreateOauthNonce() - { - return Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); - } + public string CreateOauthNonce() => Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); public string CreateHeader(string resourceUrl, Method method, SortedDictionary requestParameters) @@ -269,13 +287,10 @@ public string CreateHeader(string resourceUrl, Method method, //The oAuth signature is then used to generate the Authentication header. - if (!string.IsNullOrEmpty(AccessToken)) { - const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + - "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + - "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + - "oauth_version=\"{6}\""; + const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +"oauth_version=\"{6}\""; + var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauthNonce), Uri.EscapeDataString(OauthSignatureMethod), @@ -290,17 +305,15 @@ public string CreateHeader(string resourceUrl, Method method, else { - const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + - "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + - "oauth_signature=\"{4}\", oauth_version=\"{5}\""; + const string headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +"oauth_signature=\"{4}\", oauth_version=\"{5}\""; + var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauthNonce), Uri.EscapeDataString(OauthSignatureMethod), Uri.EscapeDataString(oauthTimestamp), Uri.EscapeDataString(ConsumerKey), Uri.EscapeDataString(oauthSignature), - Uri.EscapeDataString(OauthVersion) - ); + Uri.EscapeDataString(OauthVersion)); return authHeader; } @@ -310,110 +323,53 @@ public string CreateOauthSignature(string resourceUrl, Method method, string oau SortedDictionary requestParameters) { //firstly we need to add the standard oauth parameters to the sorted list - - string oauthSignature=string.Empty; - - try - { - try - { - requestParameters.Add("oauth_consumer_key", ConsumerKey); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } + var oauthSignature = string.Empty; try { - requestParameters.Add("oauth_nonce", oauthNonce); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } - try - { - requestParameters.Add("oauth_signature_method", OauthSignatureMethod); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } + if (!string.IsNullOrEmpty(ConsumerKey) && !requestParameters.ContainsKey("oauth_consumer_key")) + requestParameters.Add("oauth_consumer_key", ConsumerKey); - try - { - requestParameters.Add("oauth_timestamp", oauthTimestamp); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } - if (!string.IsNullOrEmpty(AccessToken)) - { - try - { - requestParameters.Add("oauth_token", AccessToken); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } - } - try - { - requestParameters.Add("oauth_version", OauthVersion); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } + if (!string.IsNullOrEmpty(oauthNonce) && !requestParameters.ContainsKey("oauth_nonce")) + requestParameters.Add("oauth_nonce", oauthNonce); - try - { - if (!string.IsNullOrEmpty(OAuthVerifer)) + if (!string.IsNullOrEmpty(OauthSignatureMethod) && !requestParameters.ContainsKey("oauth_signature_method")) + requestParameters.Add("oauth_signature_method", OauthSignatureMethod); - try - { - requestParameters.Add("oauth_verifier", OAuthVerifer); - } - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - } - } + if (!string.IsNullOrEmpty(oauthTimestamp) && !requestParameters.ContainsKey("oauth_timestamp")) + requestParameters.Add("oauth_timestamp", oauthTimestamp); - catch (Exception ex) - { - Console.WriteLine(ex.StackTrace); - - } - - - var sigBaseString = requestParameters.ToWebString(); + if (!string.IsNullOrEmpty(AccessToken) && !requestParameters.ContainsKey("oauth_token")) + requestParameters.Add("oauth_token", AccessToken); - var signatureBaseString = string.Concat(method.ToString(), "&", Uri.EscapeDataString(resourceUrl), "&", - Uri.EscapeDataString(sigBaseString.ToString())); + if (!string.IsNullOrEmpty(OauthVersion) && !requestParameters.ContainsKey("oauth_version")) + requestParameters.Add("oauth_version", OauthVersion); + if (!string.IsNullOrEmpty(OAuthVerifer) && !requestParameters.ContainsKey("oauth_verifier")) + requestParameters.Add("oauth_verifier", OAuthVerifer); - //Using this base string, we then encrypt the data using a composite of the - //secret keys and the HMAC-SHA1 algorithm. - var compositeKey = string.Concat(Uri.EscapeDataString(ConsumerKeySecret), "&", - Uri.EscapeDataString(AccessTokenSecret)); + if (requestParameters.Count > 0) + { + var sigBaseString = requestParameters.ToWebString(); + var signatureBaseString = string.Concat(method.ToString(), "&", Uri.EscapeDataString(resourceUrl), "&", + Uri.EscapeDataString(sigBaseString)); + //Using this base string, we then encrypt the data using a composite of the + //secret keys and the HMAC-SHA1 algorithm. + var compositeKey = string.Concat(Uri.EscapeDataString(ConsumerKeySecret), "&", + Uri.EscapeDataString(AccessTokenSecret)); - using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey))) + using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey))) + { + oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString))); + } + } + } + catch (Exception ex) { - oauthSignature = Convert.ToBase64String( - hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString))); + Console.WriteLine(ex.StackTrace); } - - } - catch (Exception ex) - { - Console.WriteLine("Error : " + ex.StackTrace); - } - + return oauthSignature; } @@ -427,153 +383,9 @@ public static string CreateOAuthTimestamp() return timestamp; } - - /// - /// Web Request Wrapper - /// - /// Http Method - /// Full url to the web resource - /// Data to post in querystring format - /// The web server response. - //public string WebRequest(Method method, string url, string postData) - //{ - // HttpWebRequest webRequest = null; - // StreamWriter requestWriter = null; - // string responseData = ""; - - // webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; - // webRequest.Method = method.ToString(); - // webRequest.ServicePoint.Expect100Continue = false; - // //webRequest.UserAgent = "Identify your application please."; - // //webRequest.Timeout = 20000; - - // if (method == Method.POST || method == Method.DELETE) - // { - // // webRequest.ContentType = "application/x-www-form-urlencoded"; - // webRequest.ContentType = "application/xml"; - // // webRequest.ContentType = "multipart/form-data;"; - // //POST the data. - // requestWriter = new StreamWriter(webRequest.GetRequestStream()); - // try - // { - // requestWriter.Write(postData); - // } - // catch - // { - // throw; - // } - // finally - // { - // requestWriter.Close(); - // requestWriter = null; - // } - // } - - // responseData = WebResponseGet(webRequest); - - // webRequest = null; - - // return responseData; - - //} - - ///// - ///// Process the web response. - ///// - ///// The request object. - ///// The response data. - //public string WebResponseGet(HttpWebRequest webRequest) - //{ - // StreamReader responseReader = null; - // string responseData = ""; - - // try - // { - // responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); - // responseData = responseReader.ReadToEnd(); - // } - // catch - // { - // throw; - // } - // finally - // { - // webRequest.GetResponse().GetResponseStream().Close(); - // responseReader.Close(); - // responseReader = null; - // } - - // return responseData; - //} - - //public string webRequestWithContentType(oAuthTwitter oAuth, string imageFile, string contentType, string RequestUrl, string postData) - //{ - // HttpWebRequest request = null; - // request = System.Net.WebRequest.Create(RequestUrl) as HttpWebRequest; - // oauthMgr["consumer_key"] = ConfigurationManager.AppSettings["consumerKey"]; - // oauthMgr["consumer_secret"] = ConfigurationManager.AppSettings["consumerSecret"]; - // oauthMgr["token"] = oAuth.Token; - // oauthMgr["token_secret"] = oAuth.TokenSecret; - // var authzHeader = oauthMgr.GenerateAuthzHeader(RequestUrl, "POST"); - // request.Method = "POST"; - // request.PreAuthenticate = true; - // request.AllowWriteStreamBuffering = true; - // request.Headers.Add("Authorization", authzHeader); - - // string boundary = "======" + - // Guid.NewGuid().ToString().Substring(18).Replace("-", "") + - // "======"; - - // var separator = "--" + boundary; - // var footer = "\r\n" + separator + "--\r\n"; - - // string shortFileName = Path.GetFileName(imageFile); - // string fileContentType = GetMimeType(shortFileName); - // string fileHeader = string.Format("Content-Disposition: file; " + - // "name=\"media\"; filename=\"{0}\"", - // shortFileName); - // var encoding = System.Text.Encoding.GetEncoding("iso-8859-1"); - - // var contents = new System.Text.StringBuilder(); - // contents.AppendLine(separator); - // contents.AppendLine("Content-Disposition: form-data; name=\"status\""); - // contents.AppendLine(); - // contents.AppendLine(oAuth.UrlEncode(postData)); - // contents.AppendLine(separator); - // contents.AppendLine(fileHeader); - // contents.AppendLine(string.Format("Content-Type: {0}", fileContentType)); - // contents.AppendLine(); - - // request.ServicePoint.Expect100Continue = false; - // request.ContentType = "multipart/form-data; boundary=" + boundary; - // // actually send the request - // using (var s = request.GetRequestStream()) - // { - // byte[] bytes = encoding.GetBytes(contents.ToString()); - // s.Write(bytes, 0, bytes.Length); - // bytes = File.ReadAllBytes(imageFile); - // s.Write(bytes, 0, bytes.Length); - // bytes = encoding.GetBytes(footer); - // s.Write(bytes, 0, bytes.Length); - // } - // string strUpdate = oAuth.WebResponseGet(request); - // return strUpdate; - //} - //public static string GetMimeType(String filename) - //{ - - // var extension = System.IO.Path.GetExtension(filename).ToLower(); - // var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension); - - // string result = - // ((regKey != null) && (regKey.GetValue("Content Type") != null)) - // ? regKey.GetValue("Content Type").ToString() - // : "image/unknown"; - // return result; - //} - } } + public static class Extensions { public static string ToWebString(this SortedDictionary source) diff --git a/src/Socioboard.Twitter/Twitter.Core/AccountMethods/Account.cs b/src/Socioboard.Twitter/Twitter.Core/AccountMethods/Account.cs index 354ee5ebf..753beb2d3 100644 --- a/src/Socioboard.Twitter/Twitter.Core/AccountMethods/Account.cs +++ b/src/Socioboard.Twitter/Twitter.Core/AccountMethods/Account.cs @@ -70,7 +70,7 @@ public XmlDocument Rate_Limit_Status(TwitterUser User) public XmlDocument Rate_Limit_Status(oAuthTwitter OAuth, SortedDictionary strdic) { - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, Globals.RateLimitStatusUrl, strdic); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET, Globals.RateLimitStatusUrl, strdic); xmlResult.Load(new StringReader(response)); return xmlResult; } @@ -85,7 +85,7 @@ public XmlDocument Rate_Limit_Status(oAuthTwitter OAuth, SortedDictionary strdic = new SortedDictionary(); - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, Globals.VerifyCredentialsUrl, strdic); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET, Globals.VerifyCredentialsUrl, strdic); //xmlResult.Load(new StringReader(response)); if (!response.StartsWith("[")) response = "[" + response + "]"; diff --git a/src/Socioboard.Twitter/Twitter.Core/DirectMessageMethods/DirectMessage.cs b/src/Socioboard.Twitter/Twitter.Core/DirectMessageMethods/DirectMessage.cs index 133bfaa71..dc2333b07 100644 --- a/src/Socioboard.Twitter/Twitter.Core/DirectMessageMethods/DirectMessage.cs +++ b/src/Socioboard.Twitter/Twitter.Core/DirectMessageMethods/DirectMessage.cs @@ -161,7 +161,7 @@ public JArray Get_Direct_Messages(oAuthTwitter oAuth,int count) SortedDictionary strdic = new SortedDictionary(); strdic.Add("count",count.ToString()); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetDirectMesagesUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); return JArray.Parse(response); } @@ -176,7 +176,7 @@ public JArray Get_Direct_Messages_Sent(oAuthTwitter oAuth, int count) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetDirectMessagesSentUrl; SortedDictionary strdic = new SortedDictionary(); strdic.Add("count", count.ToString()); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -194,7 +194,7 @@ public JArray Get_Direct_Messages_Show_ById(oAuthTwitter oAuth, string directMes SortedDictionary strdic = new SortedDictionary(); strdic.Add("id", directMessageId); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -227,9 +227,12 @@ public JArray Post_Direct_Messages_New(oAuthTwitter oAuth,string textMessage, st { string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostDirectMesagesNewUrl; SortedDictionary strdic = new SortedDictionary(); - strdic.Add("text", textMessage); - strdic.Add("user_id", userId); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + // strdic.Add("text", textMessage); + // strdic.Add("user_id", userId); + + var datas= oAuth.SendDirectMessage(Globals.TwitterPostDirectMessageUrl, userId, textMessage, strdic); + + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); diff --git a/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/Blocks.cs b/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/Blocks.cs index e9c609c72..4114afcfb 100644 --- a/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/Blocks.cs +++ b/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/Blocks.cs @@ -14,7 +14,7 @@ public string BlocksUserByScreenName(oAuthTwitter OAuth, string screenName) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("screen_name", screenName); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostBlockCreateUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); return response; } @@ -23,7 +23,7 @@ public string BlocksUserByUserId(oAuthTwitter OAuth, string userId) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("user_id", userId); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostBlockCreateUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); return response; } @@ -32,7 +32,7 @@ public string UnBlocksUserByScreenName(oAuthTwitter OAuth, string screenName) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("screen_name", screenName); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostBlocksDestroyUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); return response; } @@ -41,7 +41,7 @@ public string UnBlocksUserByUserId(oAuthTwitter OAuth, string userId) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("user_id", userId); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostBlocksDestroyUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); return response; } diff --git a/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/FollowerManage.cs b/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/FollowerManage.cs index 2d0472881..286898b70 100644 --- a/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/FollowerManage.cs +++ b/src/Socioboard.Twitter/Twitter.Core/FollowersMethods/FollowerManage.cs @@ -14,7 +14,7 @@ public string FollowUserByScreenName(oAuthTwitter OAuth, string screenName) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("screen_name", screenName); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsCreateUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); return response; } @@ -23,7 +23,7 @@ public string FollowUserByUserId(oAuthTwitter OAuth, string userId) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("user_id", userId); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsCreateUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, stringDictionary); return response; } @@ -32,7 +32,7 @@ public string RelatnFriendshipByScreenName(oAuthTwitter OAuth, string screenName SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("target_screen_name", screenName); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendshipsShowUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, stringDictionary); return response; } @@ -41,7 +41,7 @@ public string RelatnFriendshipByUserId(oAuthTwitter OAuth, string userId) SortedDictionary stringDictionary = new SortedDictionary(); stringDictionary.Add("target_id", userId); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendshipsShowUrl; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, stringDictionary); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, stringDictionary); return response; } diff --git a/src/Socioboard.Twitter/Twitter.Core/FriendshipMethods/Friendship.cs b/src/Socioboard.Twitter/Twitter.Core/FriendshipMethods/Friendship.cs index d02831f6b..e89b516cd 100644 --- a/src/Socioboard.Twitter/Twitter.Core/FriendshipMethods/Friendship.cs +++ b/src/Socioboard.Twitter/Twitter.Core/FriendshipMethods/Friendship.cs @@ -99,7 +99,7 @@ public XmlDocument Friendships_Destroy(TwitterUser User, int UserId) public XmlDocument Friendships_Create(oAuthTwitter oAuth, string ScreenName, SortedDictionary strdic) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.FollowerUrl + ScreenName; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); xmlResult.Load(new StringReader(response)); return xmlResult; } @@ -162,7 +162,7 @@ public JArray Get_Friendships_No_Retweets_Id(oAuthTwitter oAuth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendshipsNoRetweetsIdUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -177,7 +177,7 @@ public JArray Get_Friends_Id_Url(oAuthTwitter oAuth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendsIdUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl,strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl,strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -192,7 +192,7 @@ public JArray Get_Followers_Id_Url(oAuthTwitter oAuth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFollowersIdUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -207,7 +207,7 @@ public JArray Get_Friendships_Lookup(oAuthTwitter oAuth) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendshipsLookUpUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -222,7 +222,7 @@ public JArray Get_Friendships_Incoming(oAuthTwitter oAuth) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendshipsIncomingUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -237,7 +237,7 @@ public JArray Get_Friendships_Outgoing(oAuthTwitter oAuth) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFrienshipsOutgoingUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -254,7 +254,7 @@ public JArray Post_Friendships_Create(oAuthTwitter oAuth,string UserId) SortedDictionary strdic = new SortedDictionary(); strdic.Add("user_id", UserId); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsCreateUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -266,7 +266,7 @@ public JArray Post_Friendships_Create_New(oAuthTwitter oAuth, string UserId, str strdic.Add("user_id", UserId); strdic.Add("screen_name", screen_name); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsCreateUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -284,7 +284,7 @@ public JArray Post_Friendship_Destroy(oAuthTwitter oAuth,string UserId) string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsDestroyUrl; SortedDictionary strdic = new SortedDictionary(); strdic.Add("user_id", UserId); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl,strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl,strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -296,7 +296,7 @@ public JArray Post_Friendship_Destroy_New(oAuthTwitter oAuth, string UserId, str strdic.Add("user_id", UserId); strdic.Add("screen_name", screen_name); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsDestroyUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -313,7 +313,7 @@ public JArray Post_Friendships_Update(oAuthTwitter oAuth,string UserId,bool devi strdic.Add("user_id", UserId); strdic.Add("device", device.ToString()); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostFriendshipsDestroyUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -330,7 +330,7 @@ public JArray Get_Friendships_Show(oAuthTwitter oAuth,string source_screenname,s strdic.Add("source_screen_name",source_screenname); strdic.Add("target_screen_name", getScreenname); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendshipsShowUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl,strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl,strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -346,7 +346,7 @@ public JArray Get_Friends_List(oAuthTwitter oAuth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendsListUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -362,7 +362,7 @@ public JArray Get_Followers_List(oAuthTwitter oAuth) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFollowersListUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); diff --git a/src/Socioboard.Twitter/Twitter.Core/SearchMethods/Search.cs b/src/Socioboard.Twitter/Twitter.Core/SearchMethods/Search.cs index 2ca117bbc..b987dec6e 100644 --- a/src/Socioboard.Twitter/Twitter.Core/SearchMethods/Search.cs +++ b/src/Socioboard.Twitter/Twitter.Core/SearchMethods/Search.cs @@ -95,7 +95,7 @@ public JObject SearchMethodForTwtUser(oAuthTwitter OAuth, string SearchKey, stri /// Json Text Of Trends public string Trends(oAuthTwitter OAuth, SortedDictionary strdic) { - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, Socioboard.Twitter.App.Core.Globals.TrendsUrl, strdic); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET, Socioboard.Twitter.App.Core.Globals.TrendsUrl, strdic); return response; } @@ -118,7 +118,7 @@ public JArray Get_Search_Tweets(oAuthTwitter oAuth, string SearchKeyword) SortedDictionary strdic = new SortedDictionary(); strdic.Add("q", SearchKeyword); strdic.Add("count", "30"); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -135,7 +135,7 @@ public JArray Get_Search_Tweets(oAuthTwitter oAuth, string SearchKeyword, string strdic.Add("q", SearchKeyword); strdic.Add("geocode",geoCode); strdic.Add("count", "20"); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); diff --git a/src/Socioboard.Twitter/Twitter.Core/SocialGraphMethods/SocialGraph.cs b/src/Socioboard.Twitter/Twitter.Core/SocialGraphMethods/SocialGraph.cs index c9d4b49c4..488d2a69c 100644 --- a/src/Socioboard.Twitter/Twitter.Core/SocialGraphMethods/SocialGraph.cs +++ b/src/Socioboard.Twitter/Twitter.Core/SocialGraphMethods/SocialGraph.cs @@ -68,7 +68,7 @@ public XmlDocument FollowersId(TwitterUser User, string ScreenName) public XmlDocument FriendsId(oAuthTwitter OAuth, string ScreenName, SortedDictionary strdic) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.FriendsIdUrl + ScreenName; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET,RequestUrl,strdic); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET,RequestUrl,strdic); xmlResult.Load(new StringReader(response)); return xmlResult; } diff --git a/src/Socioboard.Twitter/Twitter.Core/StatusMethods/Status.cs b/src/Socioboard.Twitter/Twitter.Core/StatusMethods/Status.cs index e285df6ca..7043013ee 100644 --- a/src/Socioboard.Twitter/Twitter.Core/StatusMethods/Status.cs +++ b/src/Socioboard.Twitter/Twitter.Core/StatusMethods/Status.cs @@ -103,7 +103,7 @@ public XmlDocument UpdateStatus(oAuthTwitter oAuth, string StatusText, SortedDic try { string RequestUrl = Socioboard.Twitter.App.Core.Globals.UpdateStatusUrl + "?status="; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); xmlResult.Load(new StringReader(response)); } diff --git a/src/Socioboard.Twitter/Twitter.Core/TimeLineMethods/TimeLine.cs b/src/Socioboard.Twitter/Twitter.Core/TimeLineMethods/TimeLine.cs index 1b4ec9d14..bed86df89 100644 --- a/src/Socioboard.Twitter/Twitter.Core/TimeLineMethods/TimeLine.cs +++ b/src/Socioboard.Twitter/Twitter.Core/TimeLineMethods/TimeLine.cs @@ -92,7 +92,7 @@ public XmlDocument Status_RetweetedByMe(TwitterUser User, string Count) public XmlDocument Status_Mention(oAuthTwitter OAuth, string Count, SortedDictionary strdic) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.MentionUrl + Count; - string response = OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = OAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); xmlResult.Load(new StringReader(response)); return xmlResult; } @@ -167,7 +167,7 @@ public JArray Get_Statuses_Mentions_Timeline(oAuthTwitter oAuth) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.statusesMentionTimelineUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); return JArray.Parse(response); } #endregion @@ -188,7 +188,7 @@ public JArray Get_Statuses_User_Timeline(oAuthTwitter oAuth) - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); return JArray.Parse(response); } @@ -201,7 +201,7 @@ public JArray Get_Statuses_User_Timeline(oAuthTwitter oAuth,string ProfileId) strdic.Add("user_id", ProfileId); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); return JArray.Parse(response); } @@ -219,7 +219,7 @@ public JArray Get_Statuses_Home_Timeline(oAuthTwitter oAuth) string RequestUrl = Socioboard.Twitter.App.Core.Globals.statusesHomeTimelineUrl; SortedDictionary strdic = new SortedDictionary(); strdic.Add("count", "100"); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); return JArray.Parse(response); } #endregion @@ -234,7 +234,7 @@ public JArray Get_Statuses_Retweet_Of_Me(oAuthTwitter oAuth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.statusesRetweetsOfMeUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); return JArray.Parse(response); } #endregion @@ -245,7 +245,7 @@ public JArray Get_User_Followers(oAuthTwitter oAuth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFollowersListUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -257,7 +257,7 @@ public JArray Get_User_FollowersWithCurser(oAuthTwitter oAuth, string curser) //string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFollowersListUrl + "?cursor="+curser; SortedDictionary strdic = new SortedDictionary(); strdic.Add("cursor", curser); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); diff --git a/src/Socioboard.Twitter/Twitter.Core/TweetMethods/Tweet.cs b/src/Socioboard.Twitter/Twitter.Core/TweetMethods/Tweet.cs index 63b68ef21..7d63518ad 100644 --- a/src/Socioboard.Twitter/Twitter.Core/TweetMethods/Tweet.cs +++ b/src/Socioboard.Twitter/Twitter.Core/TweetMethods/Tweet.cs @@ -35,7 +35,7 @@ public JArray Get_Statuses_RetweetsById(oAuthTwitter oAuth, string UserId) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.StatusesRetweetByIdUrl + UserId + ".json"; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -53,7 +53,7 @@ public JArray Get_Statuses_ShowById(oAuthTwitter oAuth, string UserId) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.StatusShowByIdUrl + UserId; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -71,7 +71,7 @@ public JArray Post_Statuses_DestroyById(oAuthTwitter oAuth, string UserId) { SortedDictionary strdic = new SortedDictionary(); string RequestUrl = Socioboard.Twitter.App.Core.Globals.StatusDestroyByIdUrl + UserId + ".json"; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -92,7 +92,7 @@ public JArray Post_Statuses_Update(oAuthTwitter oAuth, string statuses) SortedDictionary strdic = new SortedDictionary(); strdic.Add("status", statuses); string RequestUrl = Socioboard.Twitter.App.Core.Globals.StatusUpdateUrl; - response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; } @@ -117,7 +117,7 @@ public JArray Post_Statuses_RetweetsById(oAuthTwitter oAuth, string UserId, stri { string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostStatusesRetweetByIdUrl + UserId + ".json"; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -158,7 +158,7 @@ public JArray Get_Statuses_retweetersById(oAuthTwitter oAuth, string StatusId) strdic.Add("id", StatusId); strdic.Add("count", "100"); strdic.Add("stringify_ids", "true"); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -170,7 +170,7 @@ public JArray Post_StatusesUpdate(oAuthTwitter oAuth, string statuses) string RequestUrl = Socioboard.Twitter.App.Core.Globals.StatusUpdateUrl; SortedDictionary strdic = new SortedDictionary(); strdic.Add("status", statuses); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -182,7 +182,7 @@ public JArray Post_StatusesUpdate(oAuthTwitter oAuth, string statuses, string sc SortedDictionary strdic = new SortedDictionary(); strdic.Add("status", "@" + screen_name + " " + statuses); strdic.Add("in_reply_to_status_id", statusid); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -195,7 +195,7 @@ public JArray Post_favorites(oAuthTwitter oAuth, string desirestatusId) string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostStatusFavoritesById; SortedDictionary strdic = new SortedDictionary(); strdic.Add("id", desirestatusId); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -209,7 +209,7 @@ public JArray Post_report_as_spammer(oAuthTwitter oAuth, string userScreaanNameo string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostUserReportAsSpammerById; SortedDictionary strdic = new SortedDictionary(); strdic.Add("screen_name", userScreaanNameorId); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); diff --git a/src/Socioboard.Twitter/Twitter.Core/UserMethods/Users.cs b/src/Socioboard.Twitter/Twitter.Core/UserMethods/Users.cs index 693c98244..cb63ee931 100644 --- a/src/Socioboard.Twitter/Twitter.Core/UserMethods/Users.cs +++ b/src/Socioboard.Twitter/Twitter.Core/UserMethods/Users.cs @@ -27,7 +27,7 @@ public Users() public int FollowersCount(oAuthTwitter oAuth, string screenname, SortedDictionary strdic) { string RequestUrl = "https://api.twitter.com/1/users/lookup.xml?screen_name=" + screenname; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); @@ -122,7 +122,7 @@ public JArray Get_Account_Settings(oAuthTwitter oAuth) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetAccountSettingsUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -140,7 +140,7 @@ public JArray Get_Account_Verify_Credentials(oAuthTwitter oAuth) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetAccountVerifyCredentialsUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -178,7 +178,7 @@ public JArray Post_Account_Settings(oAuthTwitter oAuth, string trend_location_wo if (time_zone != null) strdic.Add("time_zone" , time_zone); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -198,7 +198,7 @@ public JArray Post_Account_Update_Delivery_Device(oAuthTwitter oAuth, string dev SortedDictionary strdic = new SortedDictionary(); strdic.Add("device", device); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -234,7 +234,7 @@ public JArray Post_Account_Update_Profile(oAuthTwitter oAuth, string name,string strdic.Add("description",description); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -265,7 +265,7 @@ public JArray Post_Account_Update_Profile_Background_Image(oAuthTwitter oAuth, s if (tile != null) strdic.Add("tile",tile); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -302,7 +302,7 @@ public JArray Post_Account_Update_Profile_Colors(oAuthTwitter oAuth, string prof if (profile_text_color != null) strdic.Add("profile_text_color", profile_text_color); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -327,7 +327,7 @@ public JArray Post_Account_Update_Profile_Image(oAuthTwitter oAuth, string image if (image != null) strdic.Add("image", image); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -340,7 +340,7 @@ public JArray Get_Users_Suggestions(oAuthTwitter oauth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetUserSuggestions; SortedDictionary strdic = new SortedDictionary(); - string response = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oauth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -352,7 +352,7 @@ public JArray Get_Users_SuggestionsSlug(oAuthTwitter oauth) { string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetUserSuggestions; SortedDictionary strdic = new SortedDictionary(); - string response = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oauth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -378,7 +378,7 @@ public JArray Get_Followers_ById(oAuthTwitter oauth, string Userid) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFollowersIdUrl; SortedDictionary strdic = new SortedDictionary(); strdic.Add("user_id", Userid); - string response = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oauth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -391,7 +391,7 @@ public JArray Get_Friends_ById(oAuthTwitter oauth, string Userid) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetFriendsIdUrl; SortedDictionary strdic = new SortedDictionary(); strdic.Add("user_id", Userid); - string response = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oauth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -409,7 +409,7 @@ public JArray Get_Blocks_List(oAuthTwitter oAuth) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetBlocksListUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -427,7 +427,7 @@ public JArray Get_Blocks_Ids(oAuthTwitter oAuth) string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetBlocksIdUrl; SortedDictionary strdic = new SortedDictionary(); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -448,7 +448,7 @@ public JArray Post_Blocks_Create(oAuthTwitter oAuth, string user_id) strdic.Add("user_id", user_id); string RequestUrl = Socioboard.Twitter.App.Core.Globals.PostBlockCreateUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -470,7 +470,7 @@ public JArray Post_Blocks_Destroy(oAuthTwitter oAuth, string user_id) strdic.Add("user_id", user_id); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -490,7 +490,7 @@ public JArray Get_Users_LookUp(oAuthTwitter oAuth,string user_id) strdic.Add("user_id", user_id); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -508,7 +508,7 @@ public JArray Get_Users_LookUp_ByScreenName(oAuthTwitter oAuth, string screen_na SortedDictionary strdic = new SortedDictionary(); strdic.Add("screen_name", screen_name); string RequestUrl = Socioboard.Twitter.App.Core.Globals.GetUsersLookUpUrl; - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl,strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl,strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -528,7 +528,7 @@ public JArray Get_Users_Show(oAuthTwitter oAuth, string user_id) strdic.Add("user_id", user_id); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -548,7 +548,7 @@ public JArray Get_Users_Search(oAuthTwitter oAuth, string keyword,string count) strdic.Add("q", keyword); strdic.Add("count", count); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -568,7 +568,7 @@ public JArray Get_Users_Contributees(oAuthTwitter oAuth, string user_id) strdic.Add("user_id", user_id); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -588,7 +588,7 @@ public JArray Get_Users_Contributors(oAuthTwitter oAuth, string user_id) strdic.Add("user_id", user_id); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); @@ -611,7 +611,7 @@ public string Post_Account_Remove_Profile_Banner(oAuthTwitter oAuth) - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); return response; } #endregion @@ -639,7 +639,7 @@ public string Post_Account_Update_Profile_Banner(oAuthTwitter oAuth, string bann if (height != null) strdic.Add("height", height.ToString()); strdic.Add("width", width.ToString()); strdic.Add("offset_left", offset_left);strdic.Add("offset_top", offset_top); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.POST, RequestUrl, strdic); return response; } #endregion @@ -657,7 +657,7 @@ public JArray Get_Users_Profile_Banner(oAuthTwitter oAuth, string user_id) strdic.Add("user_id", user_id); - string response = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); + string response = oAuth.OAuthWebRequest(oAuthTwitter.Method.GET, RequestUrl, strdic); if (!response.StartsWith("[")) response = "[" + response + "]"; return JArray.Parse(response); diff --git a/src/Socioboard.Twitter/TwitterUtilites/TwitterApiBase.cs b/src/Socioboard.Twitter/TwitterUtilites/TwitterApiBase.cs new file mode 100644 index 000000000..61ca3cef8 --- /dev/null +++ b/src/Socioboard.Twitter/TwitterUtilites/TwitterApiBase.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Socioboard.Twitter.Twitter.Core; + +namespace Socioboard.Twitter.TwitterUtilites +{ + public abstract class TwitterApiBase + { + public TwitterApiBase(string consumerKey, string consumerKeySecret, string accessToken, string accessTokenSecret) + { + this.consumerKey = consumerKey; + this.consumerKeySecret = consumerKeySecret; + this.accessToken = accessToken; + this.accessTokenSecret = accessTokenSecret; + sigHasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", consumerKeySecret, accessTokenSecret))); + } + + const string TwitterApiBaseUrl = "https://api.twitter.com/1.1/"; + + readonly string consumerKey, consumerKeySecret, accessToken, accessTokenSecret; + + readonly HMACSHA1 sigHasher; + + readonly DateTime epochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + protected virtual Task PrepareAuth(string url, Dictionary data4Auth, string JsonString) + { + var fullUrl = TwitterApiBaseUrl + url; + + // Build the OAuth HTTP Header from the data. + string oAuthHeader = GenerateOAuthHeader(data4Auth, fullUrl); + + // Setting Content details + var JsonData = new StringContent(JsonString, Encoding.UTF8, "application/json"); + + return SendRequest(fullUrl, oAuthHeader, JsonData); + } + + protected virtual Task PrepareAuth(string url, Dictionary data) + { + var fullUrl = TwitterApiBaseUrl + url; + + // Build the OAuth HTTP Header from the data. + string oAuthHeader = GenerateOAuthHeader(data, fullUrl); + + // Build the form data (exclude OAuth stuff that's already in the header). + var formData = new FormUrlEncodedContent(data.Where(kvp => !kvp.Key.StartsWith("oauth_"))); + + return SendRequest(fullUrl, oAuthHeader, formData); + } + + + + protected virtual async Task SendRequest(string fullUrl, string oAuthHeader, StringContent jsondata) + { + using (var http = new HttpClient()) + { + http.DefaultRequestHeaders.Add("Authorization", oAuthHeader); + var httpResp = await http.PostAsync(fullUrl, jsondata); + var respBody = await httpResp.Content.ReadAsStringAsync(); + return respBody; + } + } + + protected virtual async Task SendRequest(string fullUrl, string oAuthHeader, FormUrlEncodedContent formData) + { + using (var http = new HttpClient()) + { + http.DefaultRequestHeaders.Add("Authorization", oAuthHeader); + + var httpResp = await http.PostAsync(fullUrl, formData); + var respBody = await httpResp.Content.ReadAsStringAsync(); + + return respBody; + } + } + + + protected virtual string GetJsonString(TwitterJsonElements twitterJsonElements) + { + return twitterJsonElements == null ? null : + JsonConvert.SerializeObject( + value: twitterJsonElements, + settings: new JsonSerializerSettings() + { + NullValueHandling = NullValueHandling.Ignore + }); + } + + protected virtual string CreateOauthNonce() => Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); + + protected virtual string GenerateOAuthHeader(Dictionary data,string fullUrl) + { + // Timestamps are in seconds since 1/1/1970. + var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds); + + // Add all the OAuth headers we'll need to use when constructing the hash. + data.Add("oauth_consumer_key", consumerKey); + data.Add("oauth_signature_method", "HMAC-SHA1"); + data.Add("oauth_timestamp", timestamp.ToString()); + data.Add("oauth_nonce", CreateOauthNonce()); // Required, but Twitter doesn't appear to use it, so "a" will do. + data.Add("oauth_token", accessToken); + data.Add("oauth_version", "1.0"); + + // Generate the OAuth signature and add it to our payload. + data.Add("oauth_signature", GenerateSignature(fullUrl, data)); + + return "OAuth " + string.Join( + ", ", + data + .Where(kvp => kvp.Key.StartsWith("oauth_")) + .Select(kvp => string.Format("{0}=\"{1}\"", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value))) + .OrderBy(s => s) + ); + } + + protected virtual string GenerateSignature(string url, Dictionary data) + { + var sigString = string.Join( + "&", + data.Union(data) + .Select(kvp => string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value))) + .OrderBy(s => s) + ); + + var fullSigData = string.Format( + "{0}&{1}&{2}", + "POST", + Uri.EscapeDataString(url), + Uri.EscapeDataString(sigString.ToString()) + ); + + return Convert.ToBase64String(sigHasher.ComputeHash(new ASCIIEncoding().GetBytes(fullSigData.ToString()))); + } + } +} \ No newline at end of file diff --git a/src/Socioboard.Twitter/TwitterUtilites/TwitterApiHelper.cs b/src/Socioboard.Twitter/TwitterUtilites/TwitterApiHelper.cs new file mode 100644 index 000000000..0588953f5 --- /dev/null +++ b/src/Socioboard.Twitter/TwitterUtilites/TwitterApiHelper.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Socioboard.Twitter.Twitter.Core; + +namespace Socioboard.Twitter.TwitterUtilites +{ + public class TwitterApiHelper : TwitterApiBase + { + public TwitterApiHelper(string consumerKey, string consumerKeySecret, string accessToken, string accessTokenSecret) + : base(consumerKey, consumerKeySecret, accessToken, accessTokenSecret) { } + + public Task DirectMessage(string text, string recipientID) + { + TwitterJsonElements jsonobject = new TwitterJsonElements + { + Events = new TwitterEvent + { + Type = "message_create", + CreateMessage = new CreateMessage + { + Target = new Target { RecipientId = recipientID }, + MessageData = new MessageData { TextMessage = text } + }, + } + }; + + var JsonString = GetJsonString(jsonobject); + + var data4Auth = new Dictionary { }; + + return PrepareAuth("direct_messages/events/new.json", data4Auth, JsonString); + } + + + public Task Tweet(string text) + { + var data = new Dictionary { + { "status", text }, + { "trim_user", "1" } + }; + + return PrepareAuth("statuses/update.json", data); + } + } +} \ No newline at end of file diff --git a/src/Socioboard.Twitter/TwitterUtilites/TwitterEvent.cs b/src/Socioboard.Twitter/TwitterUtilites/TwitterEvent.cs new file mode 100644 index 000000000..f8a52e184 --- /dev/null +++ b/src/Socioboard.Twitter/TwitterUtilites/TwitterEvent.cs @@ -0,0 +1,39 @@ +using Newtonsoft.Json; + +namespace Socioboard.Twitter.TwitterUtilites +{ + public class TwitterEvent + { + [JsonProperty(PropertyName = "type")] + public string Type; + + [JsonProperty(PropertyName = "message_create")] + public CreateMessage CreateMessage; + } + + + #region DirectMessage + + public class CreateMessage + { + [JsonProperty(PropertyName = "target")] + public Target Target; + + [JsonProperty(PropertyName = "message_data")] + public MessageData MessageData; + } + + public class Target + { + [JsonProperty(PropertyName = "recipient_id")] + public string RecipientId; + } + + public class MessageData + { + [JsonProperty(PropertyName = "text")] + public string TextMessage; + } + + #endregion +} \ No newline at end of file diff --git a/src/Socioboard.Twitter/TwitterUtilites/TwitterJsonElements.cs b/src/Socioboard.Twitter/TwitterUtilites/TwitterJsonElements.cs new file mode 100644 index 000000000..695bb38f5 --- /dev/null +++ b/src/Socioboard.Twitter/TwitterUtilites/TwitterJsonElements.cs @@ -0,0 +1,11 @@ +using Newtonsoft.Json; +using Socioboard.Twitter.Twitter.Core; + +namespace Socioboard.Twitter.TwitterUtilites +{ + public class TwitterJsonElements + { + [JsonProperty(PropertyName = "event")] + public TwitterEvent Events { get; set; } + } +} \ No newline at end of file diff --git a/src/Socioboard/Controllers/FacebookManagerController.cs b/src/Socioboard/Controllers/FacebookManagerController.cs index 5247db012..ade46bc30 100644 --- a/src/Socioboard/Controllers/FacebookManagerController.cs +++ b/src/Socioboard/Controllers/FacebookManagerController.cs @@ -101,7 +101,7 @@ public async Task Facebook(string code) string accessToken = string.Empty; try { - accessToken = Socioboard.Facebook.Auth.Authentication.getAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); + accessToken = Socioboard.Facebook.Auth.Authentication.GetAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); } catch (Exception ex) { @@ -278,7 +278,7 @@ public async Task AddFbAcc(string code) string accessToken = string.Empty; try { - accessToken = Socioboard.Facebook.Auth.Authentication.getAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); + accessToken = Socioboard.Facebook.Auth.Authentication.GetAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); } catch (Exception ex) { @@ -310,7 +310,7 @@ public async Task AddFbPage(string code) string accessToken = string.Empty; try { - accessToken = Socioboard.Facebook.Auth.Authentication.getAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); + accessToken = Socioboard.Facebook.Auth.Authentication.GetAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); } catch (Exception ex) { @@ -351,7 +351,7 @@ public async Task ReConnectAcc(string code) string accessToken = string.Empty; try { - accessToken = Socioboard.Facebook.Auth.Authentication.getAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); + accessToken = Socioboard.Facebook.Auth.Authentication.GetAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); } catch (Exception ex) { @@ -394,7 +394,7 @@ public async Task ReConnectfbpage(string code) string accessToken = string.Empty; try { - accessToken = Socioboard.Facebook.Auth.Authentication.getAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); + accessToken = Socioboard.Facebook.Auth.Authentication.GetAccessToken(_appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl, _appSettings.FacebookClientSecretKey, code); } catch (Exception ex) { diff --git a/src/Socioboard/Controllers/GoogleManagerController.cs b/src/Socioboard/Controllers/GoogleManagerController.cs index 911779a04..fc2ea984b 100644 --- a/src/Socioboard/Controllers/GoogleManagerController.cs +++ b/src/Socioboard/Controllers/GoogleManagerController.cs @@ -84,7 +84,7 @@ public async Task Google(string code) string googleSocial = HttpContext.Session.GetObjectFromJson("Google"); string plan = HttpContext.Session.GetObjectFromJson("RegisterPlan"); - if(googleSocial== "Youtube_Account") + if (googleSocial == "Youtube_Account") { googleLogin = null; } @@ -165,7 +165,7 @@ public async Task Google(string code) [HttpGet] public ActionResult getGoogleLoginUrl(string plan) { - HttpContext.Session.SetObjectAsJson("googlepluslogin","Google_Login"); + HttpContext.Session.SetObjectAsJson("googlepluslogin", "Google_Login"); if (!string.IsNullOrEmpty(plan)) { HttpContext.Session.SetObjectAsJson("RegisterPlan", plan); @@ -236,7 +236,7 @@ public async Task AddGoogleAccount(string Op) { HttpContext.Session.SetObjectAsJson("Google", "Gplus_Account"); string googleurl = "https://accounts.google.com/o/oauth2/auth?client_id=" + _appSettings.GoogleConsumerKey + "&redirect_uri=" + _appSettings.GoogleRedirectUri + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.media.upload+https://www.googleapis.com/auth/plus.stream.write+https://www.googleapis.com/auth/plus.stream.read+https://www.googleapis.com/auth/plus.circles.read&response_type=code&access_type=offline&approval_prompt=force&access.domainRestricted=true"; - return Redirect(googleurl); + return Redirect(googleurl); } else if (Op == "page") { @@ -360,29 +360,30 @@ public async Task ReconnectGoogle(string option) { int count = 0; string profileCount = ""; - // List groups = new List(); + // List groups = new List(); Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - - - if (option == "recgplus") - { - HttpContext.Session.SetObjectAsJson("Google", "ReconGplusAccount"); - string googleurl = "https://accounts.google.com/o/oauth2/auth?client_id=" + _appSettings.GoogleConsumerKey + "&redirect_uri=" + _appSettings.GoogleRedirectUri + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.media.upload+https://www.googleapis.com/auth/plus.stream.write+https://www.googleapis.com/auth/plus.stream.read+https://www.googleapis.com/auth/plus.circles.read+https://www.googleapis.com/auth/plus.circles.write&response_type=code&access_type=offline&approval_prompt=force&access.domainRestricted=true"; - return Content(googleurl); - } - - else - { - HttpContext.Session.SetObjectAsJson("Google", "ReconnectYTAcc"); - string googleurl = "https://accounts.google.com/o/oauth2/auth?client_id=" + _appSettings.GoogleConsumerKey + "&redirect_uri=" + _appSettings.GoogleRedirectUri + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/youtube.force-ssl&response_type=code&access_type=offline&approval_prompt=force"; - return Content(googleurl); - } + + + if (option == "recgplus") + { + HttpContext.Session.SetObjectAsJson("Google", "ReconGplusAccount"); + string googleurl = "https://accounts.google.com/o/oauth2/auth?client_id=" + _appSettings.GoogleConsumerKey + "&redirect_uri=" + _appSettings.GoogleRedirectUri + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.media.upload+https://www.googleapis.com/auth/plus.stream.write+https://www.googleapis.com/auth/plus.stream.read+https://www.googleapis.com/auth/plus.circles.read&response_type=code&access_type=offline&approval_prompt=force&access.domainRestricted=true"; + // string googleurl = "https://accounts.google.com/o/oauth2/auth?client_id=" + _appSettings.GoogleConsumerKey + "&redirect_uri=" + _appSettings.GoogleRedirectUri + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.media.upload+https://www.googleapis.com/auth/plus.stream.write+https://www.googleapis.com/auth/plus.stream.read+https://www.googleapis.com/auth/plus.circles.read+https://www.googleapis.com/auth/plus.circles.write&response_type=code&access_type=offline&approval_prompt=force&access.domainRestricted=true"; + return Content(googleurl); + } + + else + { + HttpContext.Session.SetObjectAsJson("Google", "ReconnectYTAcc"); + string googleurl = "https://accounts.google.com/o/oauth2/auth?client_id=" + _appSettings.GoogleConsumerKey + "&redirect_uri=" + _appSettings.GoogleRedirectUri + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/youtube.force-ssl&response_type=code&access_type=offline&approval_prompt=force"; + return Content(googleurl); + } } public async Task ReconnectGplusAcc(string code) { Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - // string groupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); + // string groupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); List> Parameters = new List>(); Parameters.Add(new KeyValuePair("code", code)); //Parameters.Add(new KeyValuePair("groupId", groupId)); diff --git a/src/Socioboard/Controllers/HomeController.cs b/src/Socioboard/Controllers/HomeController.cs index 175a13413..dde875571 100644 --- a/src/Socioboard/Controllers/HomeController.cs +++ b/src/Socioboard/Controllers/HomeController.cs @@ -36,6 +36,7 @@ public override void OnActionExecuting(ActionExecutingContext filterContext) { Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); Domain.Socioboard.Models.SessionHistory session = HttpContext.Session.GetObjectFromJson("revokedata"); + if (session != null) { SortedDictionary strdi = new SortedDictionary(); @@ -1124,84 +1125,79 @@ public async Task Active(string id, string Token) [HttpGet] public async Task PayPalAccount(string emailId, bool IsLogin) { - HttpResponseMessage userresponse = await WebApiReq.GetReq("/api/User/GetUserData?emailId=" + emailId, "", "", _appSettings.ApiDomain); + var userresponse = await WebApiReq.GetReq("/api/User/GetUserData?emailId=" + emailId, "", "", _appSettings.ApiDomain); + if (userresponse.IsSuccessStatusCode) { - string package = string.Empty; - User user = await userresponse.Content.ReadAsAsync(); + var package = string.Empty; + var user = await userresponse.Content.ReadAsAsync(); HttpContext.Session.SetObjectAsJson("User", user); - if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Free) - { - package = "Free"; - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Deluxe) - { - package = "Deluxe"; - - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Premium) - { - package = "Premium"; - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Topaz) - { - package = "Topaz"; - - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Platinum) - { - package = "Platinum"; - - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Gold) - { - package = "Gold"; - - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Ruby) - { - package = "Ruby"; - - } - else if (user.AccountType == Domain.Socioboard.Enum.SBAccountType.Standard) - { - package = "Standard"; - - } - List> Parameter = new List>(); - Parameter.Add(new KeyValuePair("packagename", package)); - HttpResponseMessage respons = await WebApiReq.PostReq("/api/PaymentTransaction/GetPackage", Parameter, "", "", _appSettings.ApiDomain); - if (respons.IsSuccessStatusCode) + switch (user.AccountType) + { + case Domain.Socioboard.Enum.SBAccountType.Free: + package = "Free"; + break; + case Domain.Socioboard.Enum.SBAccountType.Deluxe: + package = "Deluxe"; + break; + case Domain.Socioboard.Enum.SBAccountType.Premium: + package = "Premium"; + break; + case Domain.Socioboard.Enum.SBAccountType.Topaz: + package = "Topaz"; + break; + case Domain.Socioboard.Enum.SBAccountType.Platinum: + package = "Platinum"; + break; + case Domain.Socioboard.Enum.SBAccountType.Gold: + package = "Gold"; + break; + case Domain.Socioboard.Enum.SBAccountType.Ruby: + package = "Ruby"; + break; + case Domain.Socioboard.Enum.SBAccountType.Standard: + package = "Standard"; + break; + } + + var parameter = new List> + { + new KeyValuePair("packagename", package) + }; + + var paymentResponse = await WebApiReq.PostReq("/api/PaymentTransaction/GetPackage", parameter, "", "", _appSettings.ApiDomain); + + if (paymentResponse.IsSuccessStatusCode) { try { - Domain.Socioboard.Models.Package _Package = await respons.Content.ReadAsAsync(); - HttpContext.Session.SetObjectAsJson("Package", _Package); + var sessionPackage = await paymentResponse.Content.ReadAsAsync(); + HttpContext.Session.SetObjectAsJson("Package", sessionPackage); + if (!IsLogin) { + HttpContext.Session.SetObjectAsJson("paymentsession", true); if (user.PaymentType == Domain.Socioboard.Enum.PaymentType.paypal) - { - HttpContext.Session.SetObjectAsJson("paymentsession", true); - string paypalUrl = Helpers.Payment.RecurringPaymentWithPayPal(_Package.amount, _Package.packagename, user.FirstName + " " + user.LastName, user.PhoneNumber, user.EmailId, "USD", _appSettings.paypalemail, _appSettings.callBackUrl, _appSettings.failUrl, _appSettings.callBackUrl, _appSettings.cancelurl, _appSettings.notifyUrl, "", _appSettings.PaypalURL); + { + var paypalUrl = Payment.RecurringPaymentWithPayPal(sessionPackage.amount, sessionPackage.packagename, user.FirstName + " " + user.LastName, user.PhoneNumber, user.EmailId, "USD", _appSettings.paypalemail, _appSettings.callBackUrl, _appSettings.failUrl, _appSettings.callBackUrl, _appSettings.cancelurl, _appSettings.notifyUrl, "", _appSettings.PaypalURL); return Content(paypalUrl); } else { - HttpContext.Session.SetObjectAsJson("paymentsession", true); return RedirectToAction("paymentWithPayUMoney", "Index"); } } else { + HttpContext.Session.SetObjectAsJson("paymentsession", true); if (user.PaymentType == Domain.Socioboard.Enum.PaymentType.paypal) { - HttpContext.Session.SetObjectAsJson("paymentsession", true); - return Redirect(Helpers.Payment.RecurringPaymentWithPayPal(_Package.amount, _Package.packagename, user.FirstName + " " + user.LastName, user.PhoneNumber, user.EmailId, "USD", _appSettings.paypalemail, _appSettings.callBackUrl, _appSettings.failUrl, _appSettings.callBackUrl, _appSettings.cancelurl, _appSettings.notifyUrl, "", _appSettings.PaypalURL)); + + return Redirect(Payment.RecurringPaymentWithPayPal(sessionPackage.amount, sessionPackage.packagename, user.FirstName + " " + user.LastName, user.PhoneNumber, user.EmailId, "USD", _appSettings.paypalemail, _appSettings.callBackUrl, _appSettings.failUrl, _appSettings.callBackUrl, _appSettings.cancelurl, _appSettings.notifyUrl, "", _appSettings.PaypalURL)); } else { - HttpContext.Session.SetObjectAsJson("paymentsession", true); return RedirectToAction("paymentWithPayUMoney", "Index", new { contesnt = false }); } } @@ -1639,5 +1635,34 @@ public async Task payBlueSnap(string emailId) return View(); } + [HttpPost] + public async Task ipnBluesnap(string transactionType, long subscriptionId) + { + try + { + _logger.LogInformation("========================================transactiontype======================================"); + _logger.LogInformation(transactionType); + _logger.LogInformation("========================================subscriptionId======================================"); + _logger.LogInformation(subscriptionId.ToString()); + + + + List> Parameter = new List>(); + Parameter.Add(new KeyValuePair("subscriptionId", subscriptionId.ToString())); + + HttpResponseMessage respons = await WebApiReq.PostReq("/api/PaymentTransaction/GetBlueSnapSubscription", Parameter, "", "", _appSettings.ApiDomain); + } + catch (Exception ex) + { + _logger.LogInformation("========================================exception======================================"); + + _logger.LogInformation(ex.Message); + } + + + + return Ok(); + } + } } diff --git a/src/Socioboard/Controllers/IndexController.cs b/src/Socioboard/Controllers/IndexController.cs index 5b1bac297..d88397dce 100644 --- a/src/Socioboard/Controllers/IndexController.cs +++ b/src/Socioboard/Controllers/IndexController.cs @@ -147,7 +147,7 @@ public override void OnActionExecuting(ActionExecutingContext filterContext) HttpContext.Session.SetObjectAsJson("User", _user); } } - + } } } @@ -158,7 +158,7 @@ public override void OnActionExecuting(ActionExecutingContext filterContext) // GET: // // [ResponseCache(Duration = 604800)] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] - // [ResponseCache(Duration = 100)] + // [ResponseCache(Duration = 100)] public async Task Index() { //await Task.Run(() => @@ -170,11 +170,15 @@ public async Task Index() //{ // UserSession(); //}).Start(); - // await UserSession(); - Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - string twostep = HttpContext.Session.GetObjectFromJson("twosteplogin"); - bool paymentsession = HttpContext.Session.GetObjectFromJson("paymentsession"); - if (paymentsession == true) + // await UserSession(); + + var user = HttpContext.Session.GetObjectFromJson("User"); + + var twostep = HttpContext.Session.GetObjectFromJson("twosteplogin"); + + var paymentsession = HttpContext.Session.GetObjectFromJson("paymentsession"); + + if (paymentsession) { user = null; HttpContext.Session.Remove("User"); @@ -183,8 +187,10 @@ public async Task Index() HttpContext.Session.Remove("paymentsession"); HttpContext.Session.Clear(); } + ViewBag.ApiDomain = _appSettings.ApiDomain; ViewBag.Domain = _appSettings.Domain; + if (user == null) { return View(); @@ -200,18 +206,17 @@ public async Task Index() if (user.ExpiryDate < DateTime.UtcNow) { return RedirectToAction("UpgradePlans", "Index"); - } } catch (Exception) { return RedirectToAction("Index", "Index"); } - //return RedirectToAction("Index", "Home"); + //return RedirectToAction("Index", "Home"); return View(); } - } + //[HttpGet] //private async Task UserSession() //{ @@ -290,7 +295,7 @@ public async Task Index() // } // catch (Exception ex) // { - + // } //} @@ -416,7 +421,7 @@ public ActionResult SignIn() { return RedirectToAction("Index", "Index"); } - return RedirectToAction("Index", "Home"); + return RedirectToAction("Index", "Home"); //return View(); } } @@ -484,113 +489,98 @@ public async Task AjaxPluginLogin() public async Task PaymentSuccessful() { - string output = "false"; - string plan = ""; - Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - Domain.Socioboard.Models.Package _Package = HttpContext.Session.GetObjectFromJson("Package"); - string trasactionId = Generatetxnid(); + var output = "false"; + + var user = HttpContext.Session.GetObjectFromJson("User"); + var package = HttpContext.Session.GetObjectFromJson("Package"); + + var trasactionId = Generatetxnid(); + + #region Fetching the details from Paypal + string media = Request.Form["charset"]; - string subscr_date = Request.Form["subscr_date"]; - if (string.IsNullOrEmpty(subscr_date)) - { - subscr_date = Request.Form["payment_date"]; - } - string ipn_track_id = Request.Form["ipn_track_id"]; - string payer_email = Request.Form["payer_email"]; + + string subscrDate = Request.Form["subscr_date"]; + + if (string.IsNullOrEmpty(subscrDate)) + subscrDate = Request.Form["payment_date"]; + + + string ipnTrackId = Request.Form["ipn_track_id"]; + + string payerEmail = Request.Form["payer_email"]; + string amount = Request.Form["amount3"]; + if (string.IsNullOrEmpty(amount)) { amount = Request.Form["mc_gross"]; } - string mc_currency = Request.Form["mc_currency"]; - string Payername = Request.Form["first_name"] + " " + Request.Form["last_name"]; - string txn_type = Request.Form["txn_type"]; - string item_name = Request.Form["item_name"]; - string payment_status = Request.Form["payment_status"]; - if (string.IsNullOrEmpty(payment_status)) + + string mcCurrency = Request.Form["mc_currency"]; + + string payername = Request.Form["first_name"] + " " + Request.Form["last_name"]; + + string txnType = Request.Form["txn_type"]; + + string itemName = Request.Form["item_name"]; + + string paymentStatus = Request.Form["payment_status"]; + + if (string.IsNullOrEmpty(paymentStatus)) { - payment_status = "Completed"; + paymentStatus = "Completed"; } + string paymentId = Request.Form["subscr_id"]; + if (string.IsNullOrEmpty(paymentId)) { paymentId = Request.Form["txn_id"]; } - if (_Package.packagename == "Free") - { - plan = "Free"; - } - else if (_Package.packagename == "Deluxe") - { - plan = "Deluxe"; - - } - else if (_Package.packagename == "Premium") - { - plan = "Premium"; - - } - else if (_Package.packagename == "Topaz") - { - plan = "Topaz"; - } - else if (_Package.packagename == "Platinum") - { - plan = "Platinum"; - - } - else if (_Package.packagename == "Gold") - { - plan = "Gold"; + #endregion - } - else if (_Package.packagename == "Ruby") - { - plan = "Ruby"; + var plan = package.packagename; - } - else if (_Package.packagename == "Standard") + var parameters = new List> { - plan = "Standard"; + new KeyValuePair("userId", user.Id.ToString()), + new KeyValuePair("UserName", user.FirstName + " " + user.LastName), + new KeyValuePair("email", user.EmailId), + new KeyValuePair("amount", package.amount), + new KeyValuePair("PaymentType", user.PaymentType.ToString()), + new KeyValuePair("trasactionId", trasactionId), + new KeyValuePair("paymentId", paymentId), + new KeyValuePair("accType", plan), + new KeyValuePair("subscr_date", subscrDate.Replace("PDT", "").Replace("PST", "")), + new KeyValuePair("payer_email", payerEmail), + new KeyValuePair("Payername", payername), + new KeyValuePair("payment_status", paymentStatus), + new KeyValuePair("item_name", itemName), + new KeyValuePair("media", media) + }; + + var response = await WebApiReq.PostReq("/api/PaymentTransaction/UpgradeAccount", parameters, "", "", _appSettings.ApiDomain); - } - List> Parameters = new List>(); - Parameters.Add(new KeyValuePair("userId", user.Id.ToString())); - Parameters.Add(new KeyValuePair("UserName", user.FirstName + " " + user.LastName)); - Parameters.Add(new KeyValuePair("email", user.EmailId)); - Parameters.Add(new KeyValuePair("amount", _Package.amount)); - Parameters.Add(new KeyValuePair("PaymentType", user.PaymentType.ToString())); - Parameters.Add(new KeyValuePair("trasactionId", trasactionId)); - Parameters.Add(new KeyValuePair("paymentId", paymentId)); - Parameters.Add(new KeyValuePair("accType", plan)); - Parameters.Add(new KeyValuePair("subscr_date", subscr_date.Replace("PDT","").Replace("PST", ""))); - Parameters.Add(new KeyValuePair("payer_email", payer_email)); - Parameters.Add(new KeyValuePair("Payername", Payername)); - Parameters.Add(new KeyValuePair("payment_status", payment_status)); - Parameters.Add(new KeyValuePair("item_name", item_name)); - Parameters.Add(new KeyValuePair("media", media)); - HttpResponseMessage response = await WebApiReq.PostReq("/api/PaymentTransaction/UpgradeAccount", Parameters, "", "", _appSettings.ApiDomain); if (response.IsSuccessStatusCode) { try { string data = await response.Content.ReadAsStringAsync(); if (data == "payment done") - { - List> _Parameters = new List>(); - //_Parameters.Add(new KeyValuePair("Id", user.Id.ToString())); - HttpResponseMessage _response = await WebApiReq.GetReq("/api/User/GetUser?Id=" + user.Id.ToString(), "", "", _appSettings.ApiDomain); + { + var responseMessage = await WebApiReq.GetReq("/api/User/GetUser?Id=" + user.Id, "", "", _appSettings.ApiDomain); + if (response.IsSuccessStatusCode) { try { - Domain.Socioboard.Models.User _user = await _response.Content.ReadAsAsync(); - if(user.ReferralStatus == "InActive" && user.ReferdBy!=null) + Domain.Socioboard.Models.User _user = await responseMessage.Content.ReadAsAsync(); + if (user.ReferralStatus == "InActive" && user.ReferdBy != null) { - List> ReffralParameters = new List>(); - ReffralParameters.Add(new KeyValuePair("userId", user.Id.ToString())); - HttpResponseMessage refrralresponse = await WebApiReq.PostReq("/api/User/UpdateRefrralStatus", Parameters, "", "", _appSettings.ApiDomain); + + var refrralresponse = await WebApiReq.PostReq("/api/User/UpdateRefrralStatus", parameters, "", "", _appSettings.ApiDomain); if (refrralresponse.IsSuccessStatusCode) { HttpContext.Session.SetObjectAsJson("User", _user); @@ -601,14 +591,12 @@ public async Task PaymentSuccessful() HttpContext.Session.SetObjectAsJson("User", _user); return RedirectToAction("Index", "Index"); } - } else { HttpContext.Session.SetObjectAsJson("User", _user); return RedirectToAction("Index", "Index"); } - } catch { } } @@ -826,7 +814,7 @@ public async void PaymentNotify(string code) List> Parameters = new List>(); Parameters.Add(new KeyValuePair("subscr_id", subscr_id)); Parameters.Add(new KeyValuePair("txn_id", txn_id)); - Parameters.Add(new KeyValuePair("subscr_date", subscr_date.Replace("PDT", "").Replace("PST",""))); + Parameters.Add(new KeyValuePair("subscr_date", subscr_date.Replace("PDT", "").Replace("PST", ""))); Parameters.Add(new KeyValuePair("payer_email", payer_email)); Parameters.Add(new KeyValuePair("Payername", Payername)); Parameters.Add(new KeyValuePair("payment_status", payment_status)); @@ -1050,7 +1038,7 @@ public async Task PayUMoneySuccessful(FormCollection form) string amount = Request.Form["amount"].ToString(); string productinfo = Request.Form["productinfo"].ToString(); Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - + List> Parameters = new List>(); Parameters.Add(new KeyValuePair("userId", user.Id.ToString())); Parameters.Add(new KeyValuePair("UserName", user.FirstName + " " + user.LastName)); @@ -1119,10 +1107,9 @@ public async void SendInvoiceMerchant(string customerPhone, string customerEmail public string Generatetxnid() { - - Random rnd = new Random(); - string strHash = Generatehash512(rnd.ToString() + DateTime.Now); - string txnid1 = strHash.ToString().Substring(0, 20); + var rnd = new Random(); + var strHash = Generatehash512(rnd.ToString() + DateTime.Now); + var txnid1 = strHash.Substring(0, 20); return txnid1; } @@ -1246,9 +1233,9 @@ public IActionResult Careers() } - + [Route("PrivacyPolicy")] - + public IActionResult Privacy() { return View(); diff --git a/src/Socioboard/Controllers/TwitterManagerController.cs b/src/Socioboard/Controllers/TwitterManagerController.cs index 56145428c..8dbdd3d17 100644 --- a/src/Socioboard/Controllers/TwitterManagerController.cs +++ b/src/Socioboard/Controllers/TwitterManagerController.cs @@ -82,148 +82,148 @@ public TwitterManagerController(ILogger logger, Micros [HttpGet] public async Task AddTwitterAccount(bool follow) { - int count = 0; - string profileCount = ""; - List groups = new List(); - Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - HttpResponseMessage response = await WebApiReq.GetReq("/api/Groups/GetUserGroups?userId=" + user.Id, "", "", _appSettings.ApiDomain); + var count = 0; + var profileCount = string.Empty; + var groups = new List(); + var user = HttpContext.Session.GetObjectFromJson("User"); + var response = await WebApiReq.GetReq("/api/Groups/GetUserGroups?userId=" + user.Id, "", "", _appSettings.ApiDomain); + if (response.IsSuccessStatusCode) { try { groups = await response.Content.ReadAsAsync>(); } - catch { } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } } - string sessionSelectedGroupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); + + var sessionSelectedGroupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); + if (!string.IsNullOrEmpty(sessionSelectedGroupId)) { - HttpResponseMessage groupProfilesResponse = await WebApiReq.GetReq("/api/GroupProfiles/GetGroupProfiles?groupId=" + sessionSelectedGroupId, "", "", _appSettings.ApiDomain); + var groupProfilesResponse = await WebApiReq.GetReq("/api/GroupProfiles/GetAllGroupProfiles?groupId=" + sessionSelectedGroupId, "", "", _appSettings.ApiDomain); if (groupProfilesResponse.IsSuccessStatusCode) { - List groupProfiles = await groupProfilesResponse.Content.ReadAsAsync>(); + var groupProfiles = await groupProfilesResponse.Content.ReadAsAsync>(); profileCount = groupProfiles.Count.ToString(); } } else { - long selectedGroupId = groups.FirstOrDefault(t => t.groupName == Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName).id; + var selectedGroupId = groups.FirstOrDefault(t => t.groupName == Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName).id; HttpContext.Session.SetObjectAsJson("selectedGroupId", selectedGroupId); ViewBag.selectedGroupId = selectedGroupId; - HttpResponseMessage groupProfilesResponse = await WebApiReq.GetReq("/api/GroupProfiles/GetGroupProfiles?groupId=" + selectedGroupId, "", "", _appSettings.ApiDomain); + var groupProfilesResponse = await WebApiReq.GetReq("/api/GroupProfiles/GetAllGroupProfiles?groupId=" + selectedGroupId, "", "", _appSettings.ApiDomain); if (groupProfilesResponse.IsSuccessStatusCode) { - List groupProfiles = await groupProfilesResponse.Content.ReadAsAsync>(); + var groupProfiles = await groupProfilesResponse.Content.ReadAsAsync>(); profileCount = groupProfiles.Count.ToString(); } } - // string profileCount = await ProfilesHelper.GetUserProfileCount(user.Id, _appSettings, _logger); + // string profileCount = await ProfilesHelper.GetUserProfileCount(user.Id, _appSettings, _logger); try { count = Convert.ToInt32(profileCount); } - catch (Exception ex) + catch (Exception) { TempData["Error"] = "Error while getting profile count."; return RedirectToAction("Index", "Home"); } - int MaxCount = Domain.Socioboard.Helpers.SBHelper.GetMaxProfileCount(user.AccountType); + + var MaxCount = Domain.Socioboard.Helpers.SBHelper.GetMaxProfileCount(user.AccountType); + if (count >= MaxCount) { TempData["Error"] = "Max profile Count reached."; return RedirectToAction("Index", "Home"); } - else + + HttpContext.Session.SetObjectAsJson("Twitter", follow ? "Twitter_Account_Follow" : "Twitter_Account"); + + var credentials = new OAuthCredentials { - if (follow) - { - HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account_Follow"); - } - else - { - HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account"); - } - OAuthCredentials credentials = new OAuthCredentials() - { - Type = OAuthType.RequestToken, - SignatureMethod = OAuthSignatureMethod.HmacSha1, - ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, - ConsumerKey = _appSettings.twitterConsumerKey, - ConsumerSecret = _appSettings.twitterConsumerScreatKey, - CallbackUrl = _appSettings.twitterRedirectionUrl - }; - // Use Hammock to create a rest client - var client = new RestClient - { - Authority = "https://api.twitter.com/oauth", - Credentials = credentials, - }; - // Use Hammock to create a request - var request = new RestRequest - { - Path = "request_token" - }; - // Get the response from the request - var _response = client.Request(request); - var collection = HttpUtility.ParseQueryString(_response.Content); - //string str = collection[1].ToString(); - //HttpContext.Current.Session["requestSecret"] = collection[1]; - string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0] ; - HttpContext.Session.SetObjectAsJson("requestSecret", collection[1]); - - return Redirect(rest); - } + Type = OAuthType.RequestToken, + SignatureMethod = OAuthSignatureMethod.HmacSha1, + ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, + ConsumerKey = _appSettings.twitterConsumerKey, + ConsumerSecret = _appSettings.twitterConsumerScreatKey, + CallbackUrl = _appSettings.twitterRedirectionUrl + }; + + // Use Hammock to create a rest client + var client = new RestClient + { + Authority = "https://api.twitter.com/oauth", + Credentials = credentials, + }; + + // Use Hammock to create a request + var request = new RestRequest + { + Path = "request_token" + }; + + // Get the response from the request + var _response = client.Request(request); + var collection = HttpUtility.ParseQueryString(_response.Content); + + string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0]; + HttpContext.Session.SetObjectAsJson("requestSecret", collection[1]); + + return Redirect(rest); + } [HttpGet] public async Task Twitter(string oauth_token, string oauth_verifier) { - string groupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); - string requestSecret = HttpContext.Session.GetObjectFromJson("requestSecret"); - string twitterSession = HttpContext.Session.GetObjectFromJson("Twitter"); - if (twitterSession.Equals("Twitter_Account") || twitterSession.Equals("Twitter_Account_Follow")) - { - Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - List> Parameters = new List>(); - Parameters.Add(new KeyValuePair("requestToken", oauth_token)); - Parameters.Add(new KeyValuePair("requestSecret", requestSecret)); - Parameters.Add(new KeyValuePair("requestVerifier", oauth_verifier)); - Parameters.Add(new KeyValuePair("groupId", groupId)); - Parameters.Add(new KeyValuePair("userId", user.Id.ToString())); - if (twitterSession.Equals("Twitter_Account_Follow")) - { - Parameters.Add(new KeyValuePair("follow","true")); + var groupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); + var requestSecret = HttpContext.Session.GetObjectFromJson("requestSecret"); + var twitterSession = HttpContext.Session.GetObjectFromJson("Twitter"); - } - HttpContext.Session.SetObjectAsJson("Twitter", null); - + if (!twitterSession.Equals("Twitter_Account") && !twitterSession.Equals("Twitter_Account_Follow")) + return View(); - HttpResponseMessage response = await WebApiReq.PostReq("/api/Twitter/AddTwitterAccount", Parameters, "", "", _appSettings.ApiDomain); - if (response.IsSuccessStatusCode) - { - TempData["Success"] = await response.Content.ReadAsStringAsync(); - return RedirectToAction("Index", "Home"); - } - else - { - TempData["Error"] = await response.Content.ReadAsStringAsync(); - return RedirectToAction("Index", "Home"); - } + var user = HttpContext.Session.GetObjectFromJson("User"); + var parameters = new List> + { + new KeyValuePair("requestToken", oauth_token), + new KeyValuePair("requestSecret", requestSecret), + new KeyValuePair("requestVerifier", oauth_verifier), + new KeyValuePair("groupId", groupId), + new KeyValuePair("userId", user.Id.ToString()) + }; + + if (twitterSession.Equals("Twitter_Account_Follow")) + { + parameters.Add(new KeyValuePair("follow", "true")); } - return View(); + + HttpContext.Session.SetObjectAsJson("Twitter", null); + + + var response = await WebApiReq.PostReq("/api/Twitter/AddTwitterAccount", parameters, "", "", _appSettings.ApiDomain); + + var action = response.IsSuccessStatusCode ? "Success" : "Error"; + TempData[action] = await response.Content.ReadAsStringAsync(); + return RedirectToAction("Index", "Home"); } [Route("socioboard/Reconntwtacc/")] [HttpGet("Reconntwtacc")] - public ActionResult Reconntwtacc(bool code ) + public ActionResult Reconntwtacc(bool code) { - return RedirectToAction("ReconnectTwitter", "TwitterManager", new { code = true}); + return RedirectToAction("ReconnectTwitter", "TwitterManager", new { code = true }); // return Content(Socioboard.Facebook.Auth.Authentication.GetFacebookRedirectLink(_appSettings.FacebookAuthUrl, _appSettings.FacebookClientId, _appSettings.FacebookRedirectUrl)); @@ -237,50 +237,50 @@ public async Task ReconnectTwitter(bool code) string profileCount = ""; List groups = new List(); Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson("User"); - + string sessionSelectedGroupId = HttpContext.Session.GetObjectFromJson("selectedGroupId"); - - - - - if (code) - { - HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account_Follow"); - } - else - { - HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account"); - } - OAuthCredentials credentials = new OAuthCredentials() - { - Type = OAuthType.RequestToken, - SignatureMethod = OAuthSignatureMethod.HmacSha1, - ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, - ConsumerKey = _appSettings.twitterConsumerKey, - ConsumerSecret = _appSettings.twitterConsumerScreatKey, - CallbackUrl = "https://www.socioboard.com/TwitterManager/RecTwitter" - }; - // Use Hammock to create a rest client - var client = new RestClient - { - Authority = "https://api.twitter.com/oauth", - Credentials = credentials, - }; - // Use Hammock to create a request - var request = new RestRequest - { - Path = "request_token" - }; - // Get the response from the request - var _response = client.Request(request); - var collection = HttpUtility.ParseQueryString(_response.Content); - //string str = collection[1].ToString(); - //HttpContext.Current.Session["requestSecret"] = collection[1]; - string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0]; - HttpContext.Session.SetObjectAsJson("requestSecret", collection[1]); - - return Content(rest); - + + + + + if (code) + { + HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account_Follow"); + } + else + { + HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account"); + } + OAuthCredentials credentials = new OAuthCredentials() + { + Type = OAuthType.RequestToken, + SignatureMethod = OAuthSignatureMethod.HmacSha1, + ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, + ConsumerKey = _appSettings.twitterConsumerKey, + ConsumerSecret = _appSettings.twitterConsumerScreatKey, + CallbackUrl = "https://www.socioboard.com/TwitterManager/RecTwitter" + }; + // Use Hammock to create a rest client + var client = new RestClient + { + Authority = "https://api.twitter.com/oauth", + Credentials = credentials, + }; + // Use Hammock to create a request + var request = new RestRequest + { + Path = "request_token" + }; + // Get the response from the request + var _response = client.Request(request); + var collection = HttpUtility.ParseQueryString(_response.Content); + //string str = collection[1].ToString(); + //HttpContext.Current.Session["requestSecret"] = collection[1]; + string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0]; + HttpContext.Session.SetObjectAsJson("requestSecret", collection[1]); + + return Content(rest); + } @@ -297,7 +297,7 @@ public async Task RecTwitter(string oauth_token, string oauth_ver Parameters.Add(new KeyValuePair("requestToken", oauth_token)); Parameters.Add(new KeyValuePair("requestSecret", requestSecret)); Parameters.Add(new KeyValuePair("requestVerifier", oauth_verifier)); - // Parameters.Add(new KeyValuePair("groupId", groupId)); + // Parameters.Add(new KeyValuePair("groupId", groupId)); Parameters.Add(new KeyValuePair("userId", user.Id.ToString())); if (twitterSession.Equals("Twitter_Account_Follow")) { diff --git a/src/Socioboard/Themes/Socioboard/Views/Home/payBlueSnap.cshtml b/src/Socioboard/Themes/Socioboard/Views/Home/payBlueSnap.cshtml index 33f2a3b1e..70a01d03e 100644 --- a/src/Socioboard/Themes/Socioboard/Views/Home/payBlueSnap.cshtml +++ b/src/Socioboard/Themes/Socioboard/Views/Home/payBlueSnap.cshtml @@ -15,7 +15,6 @@ } } -

Rajsekhar

@@ -33,13 +32,11 @@
-
+
- -
-
+ / - +
@@ -61,7 +58,7 @@