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);
            string userlocalscheduletime = localscheduletime;

            try
            {
                // _logger.LogError("ScheduleMessageHelperscheduleTime>>>>" + scheduleTime);
                // var dt = DateTime.Parse(scheduleTime);
                // scheduledMessage.scheduleTime = Convert.ToDateTime(TimeZoneInfo.ConvertTimeToUtc(dt));
                //scheduledMessage.scheduleTime = Convert.ToDateTime(scheduleTime) ;
                // scheduledMessage.scheduleTime = Convert.ToDateTime(CompareDateWithclient(DateTime.UtcNow.ToString(),scheduleTime));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);
            }
            DateTime fromTime = scheduledMessage.scheduleTime.AddMinutes(-scheduledMessage.scheduleTime.Minute);
            DateTime toTime   = scheduledMessage.scheduleTime.AddMinutes(-scheduledMessage.scheduleTime.Minute).AddHours(1);

            try
            {
                int count = dbr.Find <ScheduledMessage>(t => t.scheduleTime > fromTime && t.scheduleTime <= toTime && t.profileId == profileId).Count();
                if (count > _AppSettings.FacebookScheduleMessageMaxLimit)
                {
                    _logger.LogError("Facebook Max limit Reached.");
                    return("Max limit Reached.");
                }
            }
            catch (Exception)
            {
            }
            scheduledMessage.status            = Domain.Socioboard.Enum.ScheduleStatus.Pending;
            scheduledMessage.userId            = userId;
            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.localscheduletime = userlocalscheduletime;
            scheduledMessage.socialprofileName = socialprofileName;
            int ret = dbr.Add <DaywiseSchedule>(scheduledMessage);

            if (ret == 1)
            {
                return("Scheduled.");
            }
            else
            {
                return("Not Scheduled.");
            }
        }
Esempio n. 2
0
        public IActionResult AddAdsUrl(long userId, string url)
        {
            try
            {
                var ads = new AdsOffers();

                var dbr = new DatabaseRepository(_logger, _env);

                var match = Regex.Match(url, @"^(?:\w+://)?([^/?]*)");

                var homePageUrl = match.Value;

                var lstAdsOffers = dbr.Find <AdsOffers>(t => t.UserId == userId || t.WebsiteUrl.Contains(homePageUrl));

                if (lstAdsOffers.Count != 0)
                {
                    return(BadRequest("Sorry, Either user or given url already register for this offer!"));
                }

                var contents = AdsOffersRepository.FindUrlForAds(homePageUrl);

                if (contents != "Ads found on website")
                {
                    return(BadRequest("Ads not found on website"));
                }

                var lstUser = dbr.Find <User>(t => t.Id == userId);

                var mailId = lstUser.First().EmailId;

                if (lstUser.Count > 0)
                {
                    ads.adsaccountstatus = AdsOfferAccountStatus.Active;
                    ads.adcreateddate    = DateTime.UtcNow;
                    ads.UserId           = userId;
                    ads.Verified         = AdsStatus.Verified;
                    ads.WebsiteUrl       = homePageUrl;
                    ads.EmailId          = mailId;
                    ads.Verifieddate     = DateTime.UtcNow.Date;
                    var savedStatus = dbr.Add(ads);

                    if (savedStatus != 1)
                    {
                        return(Ok("Ads found on website"));
                    }

                    lstUser.First().Adsstatus           = AdsStatus.Verified;
                    lstUser.First().TrailStatus         = UserTrailStatus.active;
                    lstUser.First().PaymentType         = PaymentType.paypal;
                    lstUser.First().PayPalAccountStatus = PayPalAccountStatus.added;
                    lstUser.First().AccountType         = SBAccountType.Standard;
                    lstUser.First().PaymentStatus       = SBPaymentStatus.Paid;
                    dbr.Update(lstUser.First());
                }

                return(Ok("Ads found on website"));
            }
            catch (Exception)
            {
                return(BadRequest("Something went wrong please try after sometime"));
            }
        }
        public async Task <string> FBPlugingCreateBoard(string boardName, string twitterHashTag, string instagramHashTag, string gplusHashTag, long userId, Helper.Cache _redisCache, Helper.AppSettings settings, ILogger _logger, DatabaseRepository dbr)
        {
            if (boardName.Contains("~") || boardName.Contains("@") || boardName.Contains("$") || boardName.Contains("%") || boardName.Contains("^") || boardName.Contains("*") || boardName.Contains("(") || boardName.Contains(")") || boardName.Contains("'") || boardName.Contains("?") || boardName.Contains("+") || boardName.Contains("'\'") || boardName.Contains("| ") || boardName.Contains("/"))
            {
                return("You cannot create board with special characters");
            }
            else
            {
                IList <Domain.Socioboard.Models.MongoBoards> boards = new List <Domain.Socioboard.Models.MongoBoards>();
                try
                {
                    boards = dbr.Find <Domain.Socioboard.Models.MongoBoards>(t => t.boardName.Equals(boardName.ToLower()));
                }
                catch (Exception e)
                {
                }
                string Bid = string.Empty;
                if (boards == null || boards.Count() == 0)
                {
                    Domain.Socioboard.Models.MongoBoards board = new Domain.Socioboard.Models.MongoBoards();
                    board.isActive     = Domain.Socioboard.Enum.boardStatus.active;
                    board.boardName    = boardName.ToLower();
                    board.createDate   = DateTime.UtcNow;
                    board.userId       = userId;
                    board.trendingtype = Domain.Socioboard.Enum.TrendingType.facebook;
                    board.boardId      = Guid.NewGuid().ToString();
                    if (board.boardName.ToLower().Contains(" "))
                    {
                        board.TempboardName = board.boardName.Replace(" ", "_");
                    }
                    else
                    {
                        board.TempboardName = boardName.ToLower();
                    }
                    if (!string.IsNullOrEmpty(twitterHashTag) && twitterHashTag != "undefined")
                    {
                        TwitterRepository tr = new TwitterRepository();
                        board.twitterHashTag = await tr.AddTwitterHashTagFBPlugin(twitterHashTag, board.boardId, _redisCache, settings, _logger);
                    }
                    if (!string.IsNullOrEmpty(instagramHashTag) && instagramHashTag != "undefined")
                    {
                        InstagramRepository instRepo = new InstagramRepository();
                        board.instagramHashTag = await instRepo.AddInstagramHashTagFBPlugin(instagramHashTag, board.boardId, _redisCache, settings, _logger);
                    }
                    if (!string.IsNullOrEmpty(gplusHashTag) && gplusHashTag != "undefined")
                    {
                        GplusRepository gplusRepo = new GplusRepository();
                        board.gplusHashTag = await gplusRepo.AddGplusHashTagFBPlugin(gplusHashTag, board.boardId, _redisCache, settings, _logger);
                    }

                    dbr.Add <Domain.Socioboard.Models.MongoBoards>(board);
                    return("successfulyy added.");
                }
                else
                {
                    Bid = boards.First().boardId;
                    Domain.Socioboard.Models.MongoBoards board = dbr.Single <Domain.Socioboard.Models.MongoBoards>(t => t.boardId == Bid);
                    //TwitterRepository tr = new TwitterRepository();
                    //board.twitterHashTag = await tr.AddTwitterHashTagFBPlugin(twitterHashTag, board.boardId, _redisCache, settings, _logger);
                    //InstagramRepository instRepo = new InstagramRepository();
                    //board.instagramHashTag = await instRepo.AddInstagramHashTagFBPlugin(instagramHashTag, board.boardId, _redisCache, settings, _logger);
                    //GplusRepository gplusRepo = new GplusRepository();
                    //board.gplusHashTag = await gplusRepo.AddGplusHashTagFBPlugin(gplusHashTag, board.boardId, _redisCache, settings, _logger);
                    //board.isActive = Domain.Socioboard.Enum.boardStatus.active;
                    board.createDate = DateTime.UtcNow;
                    dbr.Update <Domain.Socioboard.Models.MongoBoards>(board);
                    return("successfulyy Updated Board.");
                }
            }
        }
Esempio n. 4
0
        public static string PostTwitterMessage(AppSettings _AppSettings, Cache _redisCache, string message, string profileid, long userid, string url, bool isScheduled, DatabaseRepository dbr, ILogger _logger, string sscheduledmsgguid = "")
        {
            bool   rt    = false;
            string ret   = "";
            string str   = "";
            int    Twtsc = 0;

            Domain.Socioboard.Models.TwitterAccount objTwitterAccount = Api.Socioboard.Repositories.TwitterRepository.getTwitterAccount(profileid, _redisCache, dbr);
            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;

            Tweet twt = new Tweet();

            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    PhotoUpload ph  = new PhotoUpload();
                    string      res = string.Empty;
                    rt = ph.NewTweet(url, message, OAuthTwt, ref res);
                }
                catch (Exception ex)
                {
                    _logger.LogError("PostTwitterMessageWithImage" + ex.StackTrace);
                    _logger.LogError("PostTwitterMessageWithImage" + ex.Message);
                }
            }
            else
            {
                try
                {
                    JArray post = twt.Post_Statuses_Update(OAuthTwt, message);
                    ret = post[0]["id_str"].ToString();
                }
                catch (Exception ex)
                {
                    _logger.LogError("PostTwitterMessage" + ex.StackTrace);
                    _logger.LogError("PostTwitterMessage" + ex.Message);
                }
            }

            if (!string.IsNullOrEmpty(ret) || rt == true)
            {
                ScheduledMessage scheduledMessage = new ScheduledMessage();
                scheduledMessage.createTime        = DateTime.UtcNow;
                scheduledMessage.picUrl            = objTwitterAccount.profileImageUrl;
                scheduledMessage.profileId         = profileid;
                scheduledMessage.profileType       = Domain.Socioboard.Enum.SocialProfileType.Twitter;
                scheduledMessage.scheduleTime      = DateTime.UtcNow;
                scheduledMessage.shareMessage      = message;
                scheduledMessage.socialprofileName = objTwitterAccount.twitterScreenName;
                scheduledMessage.userId            = userid;
                scheduledMessage.status            = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                scheduledMessage.url = url;
                dbr.Add <ScheduledMessage>(scheduledMessage);
            }
            else
            {
                str = "Message not posted";
            }

            return(str);
        }
        public static string ComposeTwitterMessage(string message, string profileid, long userid, string picurl, bool isScheduled, DatabaseRepository dbr, Domain.Socioboard.Models.TwitterAccount TwitterAccount, Domain.Socioboard.Models.ScheduledMessage schmessage, Domain.Socioboard.Models.User _user)
        {
            bool   rt  = false;
            string ret = "";
            string str = "Message posted";

            if (message.Length > 140)
            {
                message = message.Substring(0, 135);
            }
            Domain.Socioboard.Models.TwitterAccount objTwitterAccount = TwitterAccount;
            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;

            Tweet twt = new Tweet();

            if (!string.IsNullOrEmpty(picurl))
            {
                try
                {
                    PhotoUpload ph  = new PhotoUpload();
                    string      res = string.Empty;
                    rt = ph.NewTweet(picurl, message, OAuthTwt, ref res);
                }
                catch (Exception ex)
                {
                    apiHitsCount = MaxapiHitsCount;
                }
            }
            else
            {
                try
                {
                    JArray post = twt.Post_Statuses_Update(OAuthTwt, message);
                    ret = post[0]["id_str"].ToString();
                }
                catch (Exception ex)
                {
                    apiHitsCount = MaxapiHitsCount;
                }
            }

            if (!string.IsNullOrEmpty(ret) || rt == true)
            {
                schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                //schmessage.url = ret;
                dbr.Update <ScheduledMessage>(schmessage);
                Domain.Socioboard.Models.Notifications notify = new Notifications();
                Notifications lstnotifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (lstnotifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Scheduled";
                    notify.notificationtime = schmessage.localscheduletime;
                    notify.NotificationType = "Schedule Successfully";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userid;
                    dbr.Add <Notifications>(notify);
                    if (_user.scheduleSuccessUpdates)
                    {
                        string sucResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
                else
                {
                    //if (_user.scheduleSuccessUpdates)
                    //{
                    //    string sucResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    //}
                }
            }
            else
            {
                str = "Message not posted";
                Domain.Socioboard.Models.Notifications notify = new Notifications();
                Notifications lstnotifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (lstnotifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Failed";
                    notify.notificationtime = schmessage.localscheduletime;
                    notify.NotificationType = "Schedule Failed";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userid;
                    dbr.Add <Notifications>(notify);
                    if (_user.scheduleFailureUpdates)
                    {
                        string falResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
                else
                {
                    //if (_user.scheduleFailureUpdates)
                    //{
                    //    string falResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    //}
                }
            }

            return(str);
        }
        public static string DaywiseComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Models.DaywiseSchedule schmessage, Domain.Socioboard.Models.User _user)
        {
            string ret = "";
            var    dbr = new DatabaseRepository();

            try
            {
                var pageAccessToken = FacebookApiHelper.GetPageAccessToken(fbUserId, accessToken, string.Empty);
                var response        = FacebookApiHelper.PublishPostOnPage(pageAccessToken, fbUserId, message,
                                                                          imagePath, link);

                var isPublished = response.Contains("id");

                if (isPublished)
                {
                    var selectDayObject = JsonConvert.DeserializeObject <List <string> >(schmessage.weekdays);

                    schmessage.scheduleTime = DateTimeHelper.GetNextScheduleDate(selectDayObject, schmessage.scheduleTime);

                    if (schmessage.scheduleTime.Date == DateTime.Today)
                    {
                        schmessage.scheduleTime = schmessage.scheduleTime.AddDays(7);
                    }

                    dbr.Update(schmessage);
                    var notify        = new Notifications();
                    var notifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                    if (notifications == null)
                    {
                        notify.MsgId            = schmessage.id;
                        notify.MsgStatus        = "Scheduled";
                        notify.notificationtime = schmessage.localscheduletime.ToString();
                        notify.NotificationType = "Schedule Successfully";
                        notify.ReadOrUnread     = "Unread";
                        notify.UserId           = userId;
                        dbr.Add(notify);
                        if (_user.scheduleSuccessUpdates)
                        {
                            var sucResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime.ToString(), true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                apiHitsCount = MaxapiHitsCount;
                var notify        = new Notifications();
                var notifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (notifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Failed";
                    notify.notificationtime = schmessage.localscheduletime.ToString();
                    notify.NotificationType = "Schedule Failed";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userId;
                    dbr.Add(notify);
                    if (_user.scheduleFailureUpdates)
                    {
                        string falResponse = SendMailbySendGrid(AppSettings.from_mail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime.ToString(), false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
            }
            return(ret);
        }
Esempio n. 7
0
        public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Models.ScheduledMessage schmessage, Domain.Socioboard.Models.User _user)
        {
            string             ret = "";
            DatabaseRepository dbr = new DatabaseRepository();
            FacebookClient     fb  = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;


            var args = new Dictionary <string, object>();


            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (string.IsNullOrEmpty(link))
                {
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        if (!string.IsNullOrEmpty(message))
                        {
                            args["message"] = message;
                        }

                        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;
                            string extension = string.Empty;
                            extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                            var media = new FacebookMediaObject
                            {
                                FileName    = "filename",
                                ContentType = "image/" + extension
                            };
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["source"] = media;
                            ret            = fb.Post("v2.7/" + fbUserId + "/photos", args).ToString();
                        }
                        else
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            filename = imagePath.Substring(imagePath.IndexOf("get?id=") + 7);
                            if (!string.IsNullOrWhiteSpace(filename))
                            {
                                extension = filename.Substring(filename.IndexOf(".") + 1);
                            }
                            var media = new FacebookMediaObject
                            {
                                FileName    = filename,
                                ContentType = "video/" + extension
                            };
                            //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            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();
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        if (message.Contains("https://") || message.Contains("http://"))
                        {
                            link = message;
                            if (link.Contains("https://"))
                            {
                                string links = getBetween(link + "###", "https", "###");
                                links = "https" + links;
                                try
                                {
                                    link = links.Split(' ')[0].ToString();
                                }
                                catch (Exception)
                                {
                                    link = links;
                                }
                            }
                            if (link.Contains("http://"))
                            {
                                string links = getBetween(link + "###", "http", "###");
                                links = "http" + links;
                                try
                                {
                                    link = links.Split(' ')[0].ToString();
                                }
                                catch (Exception)
                                {
                                    link = links;
                                }
                            }
                            message         = message.Replace(link, "");
                            args["message"] = message;
                        }
                        else
                        {
                            args["message"] = message;
                        }
                    }
                    else
                    {
                        args["message"] = message;
                    }
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        args["picture"] = imagePath.Replace("&amp;", "&");
                    }
                    ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();
                }

                schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                //schmessage.url = ret;
                dbr.Update <ScheduledMessage>(schmessage);
                Domain.Socioboard.Models.Notifications notify = new Notifications();
                Notifications lstnotifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (lstnotifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Scheduled";
                    notify.notificationtime = schmessage.localscheduletime;
                    notify.NotificationType = "Schedule Successfully";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userId;
                    dbr.Add <Notifications>(notify);
                    if (_user.scheduleSuccessUpdates)
                    {
                        string sucResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
                else
                {
                    if (_user.scheduleSuccessUpdates)
                    {
                        string sucResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, true, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
            }
            catch (Exception ex)
            {
                apiHitsCount = MaxapiHitsCount;
                Domain.Socioboard.Models.Notifications notify = new Notifications();
                Notifications lstnotifications = dbr.Single <Notifications>(t => t.MsgId == schmessage.id);
                if (lstnotifications == null)
                {
                    notify.MsgId            = schmessage.id;
                    notify.MsgStatus        = "Failed";
                    notify.notificationtime = schmessage.localscheduletime;
                    notify.NotificationType = "Schedule Failed";
                    notify.ReadOrUnread     = "Unread";
                    notify.UserId           = userId;
                    dbr.Add <Notifications>(notify);
                    if (_user.scheduleFailureUpdates)
                    {
                        string falResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
                else
                {
                    if (_user.scheduleFailureUpdates)
                    {
                        string falResponse = SendMailbySendGrid(AppSettings.frommail, "", _user.EmailId, "", "", "", "", _user.FirstName, schmessage.localscheduletime, false, AppSettings.sendGridUserName, AppSettings.sendGridPassword);
                    }
                }
            }
            return(ret);
        }
        public IActionResult Register(User user)
        {
            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.UserName            = "******";
            user.PayPalAccountStatus = Domain.Socioboard.Enum.PayPalAccountStatus.notadded;
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            DatabaseRepository dbr     = new DatabaseRepository(_logger, _appEnv);
            IList <User>       lstUser = dbr.Find <User>(t => t.EmailId.Equals(user.EmailId));

            if (lstUser != null && lstUser.Count() > 0)
            {
                return(BadRequest("EmailID Exist"));
            }
            IList <User> lstUser1 = dbr.Find <User>(a => a.PhoneNumber.Equals(user.PhoneNumber));

            if (lstUser1 != null && lstUser1.Count() > 0)
            {
                return(BadRequest("Phone Number Exist"));
            }
            int  SavedStatus = dbr.Add <Domain.Socioboard.Models.User>(user);
            User nuser       = dbr.Single <User>(t => t.EmailId.Equals(user.EmailId));

            if (SavedStatus == 1 && nuser != null)
            {
                Groups group = new Groups();
                group.adminId = nuser.Id;
                // group.id = nuser.Id;
                group.createdDate = DateTime.UtcNow;
                group.groupName   = Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName;
                SavedStatus       = dbr.Add <Groups>(group);
                if (SavedStatus == 1)
                {
                    long GroupId = dbr.FindSingle <Domain.Socioboard.Models.Groups>(t => t.adminId == group.adminId && t.groupName.Equals(group.groupName)).id;
                    GroupMembersRepository.createGroupMember(GroupId, nuser, _redisCache, dbr);
                }
                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 conformation Link", html, _appSettings.SendgridUserName, _appSettings.SendGridPassword);
                }
                catch
                {
                    return(Ok());
                }
            }
            else
            {
                return(BadRequest("Can't create user"));
            }
            return(Ok("Email verification mail sent successfully."));
        }
Esempio n. 9
0
        public IActionResult AddAdsUrl(long userId, string url)
        {
            try
            {
                Domain.Socioboard.Models.AdsOffers ads = new AdsOffers();

                DatabaseRepository dbr          = new DatabaseRepository(_logger, _env);
                IList <AdsOffers>  lstAdsOffers = dbr.Find <AdsOffers>(t => t.UserId == userId);
                if (lstAdsOffers.Count == 0)
                {
                    Match match = Regex.Match(url, @"^(?:\w+://)?([^/?]*)");
                    //string domain = match.Groups[1].Value;
                    string            homepageurl = match.Value;
                    IList <AdsOffers> lstwebsites = dbr.Find <AdsOffers>(t => t.WebsiteUrl.Contains(homepageurl));
                    if (lstwebsites.Count == 0)
                    {
                        string lstcontent = Repositories.AdsOffersRepository.findUrlForAds(homepageurl);
                        //string lstcontents = Repositories.AdsOffersRepository.GetHomePage(url);
                        if (lstcontent == "Ads found on website")
                        {
                            IList <User> lstUser = dbr.Find <User>(t => t.Id == userId);
                            string       mailid  = lstUser.First().EmailId;
                            if (lstUser != null && lstUser.Count() > 0)
                            {
                                ads.adsaccountstatus = Domain.Socioboard.Enum.AdsOfferAccountStatus.Active;
                                ads.adcreateddate    = DateTime.UtcNow;
                                ads.UserId           = userId;
                                ads.Verified         = Domain.Socioboard.Enum.AdsStatus.Verified;
                                ads.WebsiteUrl       = homepageurl;
                                ads.EmailId          = mailid;
                                ads.Verifieddate     = DateTime.UtcNow.Date;
                                int SavedStatus = dbr.Add <Domain.Socioboard.Models.AdsOffers>(ads);
                                if (SavedStatus == 1)
                                {
                                    lstUser.First().Adsstatus           = Domain.Socioboard.Enum.AdsStatus.Verified;
                                    lstUser.First().TrailStatus         = Domain.Socioboard.Enum.UserTrailStatus.active;
                                    lstUser.First().PaymentType         = Domain.Socioboard.Enum.PaymentType.paypal;
                                    lstUser.First().PayPalAccountStatus = Domain.Socioboard.Enum.PayPalAccountStatus.added;
                                    lstUser.First().AccountType         = Domain.Socioboard.Enum.SBAccountType.Standard;
                                    lstUser.First().PaymentStatus       = Domain.Socioboard.Enum.SBPaymentStatus.Paid;
                                    //int SavedUserStatus = dbr.Add<Domain.Socioboard.Models.User>(user);
                                    int SavedUserStatus = dbr.Update <User>(lstUser.First());
                                    // int SavedUserStatus = dbr.Update<User>(user);
                                }
                            }
                            return(Ok("Ads found on website"));
                        }
                        else
                        {
                            return(BadRequest("Ads not found on website"));
                        }
                    }
                    else
                    {
                        return(BadRequest("website already register for this offer"));
                    }
                }
                else
                {
                    return(BadRequest("you already register for this offer"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest("Something went wrong please try after sometime"));
            }

            // return Ok();
        }
Esempio n. 10
0
        public IActionResult InviteGroupMembers(long groupId, string members)
        {
            List <Groupmembers> lstGrpMembers = new List <Groupmembers>();

            if (string.IsNullOrEmpty(members))
            {
                return(BadRequest("members should not be null."));
            }
            else
            {
                string[] lstmem = members.Split(';');
                foreach (var item in lstmem)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        Groupmembers grpMember = new Groupmembers();
                        string[]     memData   = item.Split(':');
                        grpMember.email     = memData[2];
                        grpMember.firstName = memData[0];
                        grpMember.lastName  = memData[1];
                        lstGrpMembers.Add(grpMember);
                    }
                }
            }


            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            Domain.Socioboard.Models.Groups grp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.id == groupId).FirstOrDefault();
            if (grp == null)
            {
                return(BadRequest("wrong group Id"));
            }
            else if (grp.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName))
            {
                return(BadRequest("you can't invite members to default group."));
            }
            foreach (var member in lstGrpMembers)
            {
                User inMemUser = _redisCache.Get <User>(member.email.Trim());
                if (inMemUser == null)
                {
                    inMemUser = dbr.Find <User>(t => t.EmailId.Equals(member.email.Trim())).FirstOrDefault();
                }
                member.groupid      = groupId;
                member.memberCode   = Domain.Socioboard.Helpers.SBHelper.RandomString(15);
                member.isAdmin      = false;
                member.memberStatus = Domain.Socioboard.Enum.GroupMemberStatus.MailSent;
                if (inMemUser != null)
                {
                    member.userId     = inMemUser.Id;
                    member.profileImg = inMemUser.ProfilePicUrl;
                    //todo : code to add in user notification list.
                }
                Groupmembers temp = dbr.Find <Groupmembers>(t => t.groupid == groupId && t.email == member.email).FirstOrDefault();
                if (temp == null)
                {
                    dbr.Add <Groupmembers>(member);
                    _redisCache.Delete(Domain.Socioboard.Consatants.SocioboardConsts.CacheGroupMembers + groupId);
                    string path = _appEnv.WebRootPath + "\\views\\mailtemplates\\groupinvitation.html";
                    string html = System.IO.File.ReadAllText(path);
                    html = html.Replace("[FirstName]", member.firstName);
                    html = html.Replace("[JoinLink]", _appSettings.Domain + "/Home/GroupInvite?Token=" + member.memberCode + "&email=" + member.email);
                    _emailSender.SendMailSendGrid(_appSettings.frommail, "", member.email, "", "", "Socioboard Team Invitation Link", html, _appSettings.SendgridUserName, _appSettings.SendGridPassword);
                }
            }

            return(Ok());
        }
        public IActionResult GoogleLogin(string code, SBAccountType accType)
        {
            var    refreshToken = string.Empty;
            string accessToken;

            var objoAuthTokenGPlus = new oAuthTokenGPlus(_appSettings.GoogleConsumerKey,
                                                         _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            var objToken = new oAuthToken(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret,
                                          _appSettings.GoogleRedirectUri);
            JObject userInfo;

            try
            {
                var objRefresh     = objoAuthTokenGPlus.GetRefreshToken(code);
                var objAccessToken = JObject.Parse(objRefresh);

                _logger.LogInformation(objAccessToken.ToString());
                try
                {
                    refreshToken = objAccessToken["refresh_token"].ToString();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.StackTrace);
                }

                accessToken = objAccessToken["access_token"].ToString();
                var user = objToken.GetUserInfo("self", accessToken);
                _logger.LogInformation(user);
                userInfo = JObject.Parse(JArray.Parse(user)[0].ToString());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);

                return(Ok("Access Token Not Found"));
            }

            var emailId = string.Empty;

            try
            {
                emailId = Convert.ToString(userInfo["email"]);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);
            }

            if (string.IsNullOrEmpty(emailId))
            {
                return(Ok("Google not returning Email"));
            }

            try
            {
                var inMemUser = _redisCache.Get <User>(emailId);
                if (inMemUser != null)
                {
                    return(Ok(inMemUser));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);
            }

            var dbr          = new DatabaseRepository(_logger, _appEnv);
            var signedInUser = dbr.FindFirstMatch <User>(t => t.EmailId.Equals(emailId));


            if (signedInUser != null)
            {
                if (!signedInUser.SocialLoginEnableGo)
                {
                    return(Ok("Account isn't sign-up with google!"));
                }

                CustomTaskFactory.Instance.Start(() =>
                {
                    if (signedInUser.RefrralCode == null)
                    {
                        signedInUser.RefrralCode = $"{SocioboardApiConstants.ApplicationName}" + signedInUser.Id;
                    }

                    signedInUser.LastLoginTime = DateTime.UtcNow;
                    dbr.Update(signedInUser);
                    _redisCache.Set(signedInUser.EmailId, signedInUser);
                });

                return(Ok(signedInUser));
            }

            var googleUser = new User
            {
                AccountType         = accType,
                PaymentType         = PaymentType.paypal,
                ActivationStatus    = SBUserActivationStatus.Active,
                CreateDate          = DateTime.UtcNow,
                EmailId             = emailId,
                ExpiryDate          = DateTime.UtcNow.AddDays(1),
                UserName            = $"{SocioboardApiConstants.ApplicationName}",
                EmailValidateToken  = "Google",
                UserType            = "User",
                LastLoginTime       = DateTime.UtcNow,
                SocialLoginEnableGo = true,
                SocialLoginEnableFb = false,
                PaymentStatus       = SBPaymentStatus.UnPaid,
                RegistrationType    = SBRegistrationType.Google,
                TrailStatus         = UserTrailStatus.active
            };

            if (googleUser.AccountType == SBAccountType.Free)
            {
                googleUser.ExpiryDate = DateTime.UtcNow.AddDays(15);
            }

            try
            {
                googleUser.FirstName = Convert.ToString(userInfo["name"]);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);
            }

            var savedStatus = dbr.Add(googleUser);

            var googleUserAccount = dbr.FindFirstMatch <User>(t => t.EmailId.Equals(googleUser.EmailId));

            CustomTaskFactory.Instance.Start(() =>
            {
                if (savedStatus != 1 || googleUserAccount == null)
                {
                    return;
                }

                _redisCache.Set(emailId, googleUserAccount);

                var group         = new Groups();
                group.adminId     = googleUserAccount.Id;
                group.createdDate = DateTime.UtcNow;
                group.groupName   = SocioboardConsts.DefaultGroupName;
                savedStatus       = dbr.Add(group);

                if (savedStatus != 1)
                {
                    return;
                }

                var groupDetails = dbr.Find <Groups>(t =>
                                                     t.adminId == googleUserAccount.Id &&
                                                     t.groupName.Equals(SocioboardConsts.DefaultGroupName))
                                   .FirstOrDefault();

                if (groupDetails == null)
                {
                    return;
                }

                GroupMembersRepository.CreateGroupMember(groupDetails.id, googleUserAccount, _redisCache, dbr);

                GplusRepository.AddGplusAccount(userInfo, dbr, googleUserAccount.Id, groupDetails.id, accessToken,
                                                refreshToken,
                                                _redisCache, _appSettings, _logger);
            });


            return(Ok(googleUserAccount));
        }
        public IActionResult GoogleLoginPhone(string refreshToken, string accessToken, SBAccountType accType)
        {
            var ret        = string.Empty;
            var objRefresh = string.Empty;

            var ObjoAuthTokenGPlus = new oAuthTokenGPlus(_appSettings.GoogleConsumerKey,
                                                         _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            var objToken = new oAuthToken(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret,
                                          _appSettings.GoogleRedirectUri);
            var userinfo = new JObject();

            try
            {
                var user = objToken.GetUserInfo("self", accessToken);
                _logger.LogInformation(user);
                userinfo = JObject.Parse(JArray.Parse(user)[0].ToString());
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
                ret = "Access Token Not Found";
                return(Ok(ret));
            }

            var EmailId = string.Empty;

            try
            {
                EmailId = Convert.ToString(userinfo["email"]);
            }
            catch
            {
            }

            if (string.IsNullOrEmpty(EmailId))
            {
                return(Ok("Google Not retuning Email"));
            }


            try
            {
                var inMemUser = _redisCache.Get <User>(EmailId);
                if (inMemUser != null)
                {
                    return(Ok(inMemUser));
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
            }


            var dbr     = new DatabaseRepository(_logger, _appEnv);
            var lstUser = dbr.Find <User>(t => t.EmailId.Equals(EmailId));

            if (lstUser != null && lstUser.Count() > 0)
            {
                var d1 = DateTime.UtcNow;
                //User userTable = dbr.Single<User>(t => t.EmailId == EmailId);
                //userTable.LastLoginTime = d1;
                lstUser.First().LastLoginTime = d1;
                dbr.Update(lstUser.First());
                _redisCache.Set(lstUser.First().EmailId, lstUser.First());
                return(Ok(lstUser.First()));
            }

            {
                var gplusAcc = GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);
                if (gplusAcc != null && gplusAcc.IsActive)
                {
                    return(BadRequest("GPlus account added by other user."));
                }


                var user = new User();
                if (accType == SBAccountType.Free)
                {
                    user.AccountType = SBAccountType.Free;
                }
                else if (accType == SBAccountType.Deluxe)
                {
                    user.AccountType = SBAccountType.Deluxe;
                }
                else if (accType == SBAccountType.Premium)
                {
                    user.AccountType = SBAccountType.Premium;
                }
                else if (accType == SBAccountType.Topaz)
                {
                    user.AccountType = SBAccountType.Topaz;
                }
                else if (accType == SBAccountType.Platinum)
                {
                    user.AccountType = SBAccountType.Platinum;
                }
                else if (accType == SBAccountType.Gold)
                {
                    user.AccountType = SBAccountType.Gold;
                }
                else if (accType == SBAccountType.Ruby)
                {
                    user.AccountType = SBAccountType.Ruby;
                }
                else if (accType == SBAccountType.Standard)
                {
                    user.AccountType = SBAccountType.Standard;
                }
                user.PaymentType         = PaymentType.paypal;
                user.ActivationStatus    = SBUserActivationStatus.Active;
                user.CreateDate          = DateTime.UtcNow;
                user.EmailId             = EmailId;
                user.ExpiryDate          = DateTime.UtcNow.AddDays(30);
                user.UserName            = "******";
                user.EmailValidateToken  = "Google";
                user.UserType            = "User";
                user.LastLoginTime       = DateTime.UtcNow;
                user.PaymentStatus       = SBPaymentStatus.UnPaid;
                user.SocialLoginEnableGo = true;
                try
                {
                    user.FirstName = Convert.ToString(userinfo["name"]);
                }
                catch
                {
                }

                user.RegistrationType = SBRegistrationType.Google;

                var SavedStatus = dbr.Add(user);
                var nuser       = dbr.Single <User>(t => t.EmailId.Equals(user.EmailId));
                if (SavedStatus == 1 && nuser != null)
                {
                    var group = new Groups();
                    group.adminId     = nuser.Id;
                    group.createdDate = DateTime.UtcNow;
                    group.groupName   = SocioboardConsts.DefaultGroupName;
                    SavedStatus       = dbr.Add(group);
                    if (SavedStatus == 1)
                    {
                        var ngrp = dbr.Find <Groups>(t =>
                                                     t.adminId == nuser.Id && t.groupName.Equals(SocioboardConsts.DefaultGroupName))
                                   .FirstOrDefault();
                        GroupMembersRepository.CreateGroupMember(ngrp.id, nuser, _redisCache, dbr);
                        // Adding GPlus Profile
                        GplusRepository.AddGplusAccount(userinfo, dbr, nuser.Id, ngrp.id, accessToken, refreshToken,
                                                        _redisCache, _appSettings, _logger);
                    }
                }

                return(Ok(nuser));
            }
        }
Esempio n. 13
0
        public void GetLatestTrendsFromTwiter()
        {
            try
            {
                string homepageUrl = "https://twitter.com/";
                string trendsUrl   = "https://twitter.com/i/trends?k=0b49e0976b&pc=true&personalized=false&show_context=true&src=module&woeid=23424977";

                string homePageResponse = getHtmlfromUrl(trendsUrl);

                try
                {
                    string[] GetTrends = Regex.Split(homePageResponse, "data-trend-name=");
                    GetTrends = GetTrends.Skip(1).ToArray();
                    foreach (string item in GetTrends)
                    {
                        try
                        {
                            string temptrend = string.Empty;
                            string trend     = getBetween(item, "\"", "\\\"").Replace("&#39;", "'");
                            trend = Regex.Replace(trend, @"\\u[\d\w]{4}", String.Empty);
                            trend = trend.Replace("#", "");
                            if (!string.IsNullOrEmpty(trend) && !trend.Contains("_") && !trend.Contains("__"))
                            {
                                if (trend.ToLower().Contains(" "))
                                {
                                    temptrend = trend.Replace(" ", "_");
                                }
                                else if (trend.ToLower().Contains("/"))
                                {
                                    temptrend = trend.Replace("/", "_");
                                }
                                else if (trend.ToLower().Contains("'\'"))
                                {
                                    temptrend = trend.Replace("'\'", "_");
                                }
                                else
                                {
                                    temptrend = trend.ToLower();
                                }
                                //Trendingkeyword _Trendingkeyword = new Trendingkeyword();
                                //_Trendingkeyword.Id = ObjectId.GenerateNewId();
                                //_Trendingkeyword.strId = ObjectId.GenerateNewId().ToString();
                                //_Trendingkeyword.keyword = trend;
                                //_Trendingkeyword.TrendingType = Domain.Socioboard.Enum.TrendingType.twitter;
                                //_Trendingkeyword.trendingdate= SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow);
                                //MongoRepository mongorepo = new MongoRepository("Trendingkeyword");
                                //var ret=mongorepo.Find<Trendingkeyword>(t => t.keyword == trend && t.TrendingType==Domain.Socioboard.Enum.TrendingType.twitter);
                                //var task = Task.Run(async () =>
                                //{
                                //    return await ret;
                                //});
                                //int count = task.Result.Count;
                                //if(count<1)
                                //{
                                //    mongorepo.Add<Trendingkeyword>(_Trendingkeyword);
                                //    AddTwittertrendingHashTagFeeds(trend, _Trendingkeyword.strId, "");
                                //}
                                DatabaseRepository dbr = new DatabaseRepository();
                                List <Domain.Socioboard.Models.MongoBoards> boards = new List <Domain.Socioboard.Models.MongoBoards>();
                                try
                                {
                                    boards = dbr.Find <Domain.Socioboard.Models.MongoBoards>(t => t.boardName.Equals(trend.ToLower()) && t.isActive == Domain.Socioboard.Enum.boardStatus.active).ToList();
                                    string Bid = string.Empty;
                                    if (boards == null || boards.Count() == 0)
                                    {
                                        //Bid = boards.First().boardId;
                                        Domain.Socioboard.Models.MongoBoards board = new Domain.Socioboard.Models.MongoBoards();
                                        board.TempboardName    = temptrend.ToLower();
                                        board.isActive         = Domain.Socioboard.Enum.boardStatus.active;
                                        board.boardName        = trend.ToLower();
                                        board.trendingtype     = Domain.Socioboard.Enum.TrendingType.twitter;
                                        board.createDate       = DateTime.UtcNow;
                                        board.boardId          = Guid.NewGuid().ToString();
                                        board.twitterHashTag   = AddTwitterHashTag(trend, board.boardId);
                                        board.instagramHashTag = AddInstagramHashTag(trend, board.boardId);
                                        board.gplusHashTag     = AddGplusHashTag(trend, board.boardId);
                                        dbr.Add <Domain.Socioboard.Models.MongoBoards>(board);
                                        string boardcreation = getHtmlfromUrl("https://api.socioboard.com/api/BoardMe/AddTOSiteMap?boardName=" + board.boardName);
                                        if (boardcreation.Contains("true"))
                                        {
                                            Console.WriteLine("created new sitemap for twitter trending keyword" + boardcreation);
                                        }

                                        Console.WriteLine("created new bord for twitter trending keyword" + board.boardName);
                                    }
                                    else
                                    {
                                        Bid = boards.First().boardId;
                                        Domain.Socioboard.Models.MongoBoards board = dbr.Single <Domain.Socioboard.Models.MongoBoards>(t => t.boardId == Bid);
                                        // board.TempboardName = temptrend;
                                        board.isActive   = Domain.Socioboard.Enum.boardStatus.active;
                                        board.createDate = DateTime.UtcNow;
                                        //board.boardId = board.boardId;
                                        //board.facebookHashTag = AddFacebookHashTag(trds[0], trds[1], board.boardId, ref HttpHelper, ref facebookUser);
                                        //board.twitterHashTag = AddTwitterHashTag(trend, board.boardId);
                                        //board.instagramHashTag = AddInstagramHashTag(trend, board.boardId);
                                        //board.gplusHashTag = AddGplusHashTag(trend, board.boardId);
                                        dbr.Update <Domain.Socioboard.Models.MongoBoards>(board);
                                        string boardcreation = getHtmlfromUrl("https://api.socioboard.com/api/BoardMe/AddTOSiteMap?boardName=" + board.boardName);
                                        if (boardcreation.Contains("true"))
                                        {
                                            Console.WriteLine("created new sitemap for twitter trending keyword" + boardcreation);
                                        }

                                        Console.WriteLine("created new bord for twitter trending keyword" + board.boardName);
                                    }
                                }

                                catch (Exception e)
                                {
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 14
0
        public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, DatabaseRepository dbr, ILogger _logger)
        {
            string ret = "";

            FacebookClient fb = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    Uri    u         = new Uri(imagePath);
                    string filename  = string.Empty;
                    string extension = string.Empty;
                    extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                    var media = new FacebookMediaObject
                    {
                        FileName    = "filename",
                        ContentType = "image/" + extension
                    };
                    //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                    var    webClient = new WebClient();
                    byte[] img       = webClient.DownloadData(imagePath);
                    media.SetValue(img);
                    args["source"] = media;
                    ret            = fb.Post("v2.7/" + fbUserId + "/photos", args).ToString();//v2.1
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    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;
                scheduledMessage.profileType  = Domain.Socioboard.Enum.SocialProfileType.Facebook;
                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";
                dbr.Add <ScheduledMessage>(scheduledMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _logger.LogError(ex.StackTrace);
            }
            return(ret);
        }
Esempio n. 15
0
        public IActionResult GoogleLogin(string code, Domain.Socioboard.Enum.SBAccountType accType)
        {
            string ret          = string.Empty;
            string objRefresh   = string.Empty;
            string refreshToken = string.Empty;
            string access_token = string.Empty;

            oAuthTokenGPlus ObjoAuthTokenGPlus = new oAuthTokenGPlus(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            oAuthToken      objToken           = new oAuthToken(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            JObject         userinfo           = new JObject();

            try
            {
                objRefresh = ObjoAuthTokenGPlus.GetRefreshToken(code);
                JObject objaccesstoken = JObject.Parse(objRefresh);
                _logger.LogInformation(objaccesstoken.ToString());
                try
                {
                    refreshToken = objaccesstoken["refresh_token"].ToString();
                }
                catch { }
                access_token = objaccesstoken["access_token"].ToString();
                string user = objToken.GetUserInfo("self", access_token.ToString());
                _logger.LogInformation(user);
                userinfo = JObject.Parse(JArray.Parse(user)[0].ToString());
            }
            catch (Exception ex)
            {
                //access_token = objaccesstoken["access_token"].ToString();
                //ObjoAuthTokenGPlus.RevokeToken(access_token);
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
                ret = "Access Token Not Found";
                return(Ok(ret));
            }

            string EmailId = string.Empty;

            try
            {
                EmailId = (Convert.ToString(userinfo["email"]));
            }
            catch { }
            if (string.IsNullOrEmpty(EmailId))
            {
                return(Ok("Google Not retuning Email"));
            }


            try
            {
                User inMemUser = _redisCache.Get <User>(EmailId);
                if (inMemUser != null)
                {
                    return(Ok(inMemUser));
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
            }



            DatabaseRepository         dbr       = new DatabaseRepository(_logger, _appEnv);
            IList <User>               lstUser   = dbr.Find <User>(t => t.EmailId.Equals(EmailId));
            IList <Googleplusaccounts> lstgacc   = dbr.Find <Googleplusaccounts>(t => t.EmailId.Equals(EmailId));
            IList <User>               userTable = dbr.Find <User>(t => t.Id == lstgacc.First().UserId);

            if (lstUser != null && lstUser.Count() > 0)
            {
                if (lstUser.FirstOrDefault().SocialLoginEnableGo == true)
                {
                    if (lstUser.First().ActivationStatus == Domain.Socioboard.Enum.SBUserActivationStatus.Active)
                    {
                        if (lstUser.First().RefrralCode == null)
                        {
                            lstUser.First().RefrralCode = "SOCIOBOARD_" + lstUser.First().Id;
                        }
                        DateTime d1 = DateTime.UtcNow;
                        //User userTable = dbr.Single<User>(t => t.EmailId == EmailId);
                        //userTable.LastLoginTime = d1;
                        lstUser.First().LastLoginTime = d1;
                        dbr.Update <User>(lstUser.First());
                        _redisCache.Set <User>(lstUser.First().EmailId, lstUser.First());
                        return(Ok(lstUser.First()));
                    }
                    else if (lstUser.First().ActivationStatus == Domain.Socioboard.Enum.SBUserActivationStatus.Disable)
                    {
                        return(Ok("Your account is disabled. Please contact socioboard support for more assistance"));
                    }
                    else
                    {
                        return(Ok("Something went wrong please try after sometime"));
                    }
                }
                else
                {
                    return(Ok(" Oh! it's look like social signin with google has disabled"));
                }
            }
            else if (lstgacc != null && lstgacc.Count() > 0 && lstUser.Count() == 0)
            {
                if (lstgacc.First().IsActive == true)
                {
                    if (userTable.First().SocialLoginEnableGo == true)
                    {
                        DateTime d1 = DateTime.UtcNow;
                        //IList<User> userTable = dbr.Find<User>(t => t.Id == lstgacc.First().UserId);
                        userTable.First().LastLoginTime = d1;
                        dbr.Update <User>(userTable.First());
                        _redisCache.Set <User>(userTable.First().EmailId, userTable.First());
                        return(Ok(userTable.First()));
                    }
                    else
                    {
                        return(Ok("it's look like you have disable your social signin option for gplus acc."));
                    }
                }
                else
                {
                    return(Ok("Google account added by other user"));
                }
            }
            else
            {
                Domain.Socioboard.Models.Googleplusaccounts gplusAcc = Api.Socioboard.Repositories.GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);
                if (gplusAcc != null && gplusAcc.IsActive == true)
                {
                    return(BadRequest("GPlus account added by other user."));
                }


                Domain.Socioboard.Models.User user = new Domain.Socioboard.Models.User();
                if (accType == Domain.Socioboard.Enum.SBAccountType.Free)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Free;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Deluxe)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Deluxe;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Premium)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Premium;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Topaz)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Topaz;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Platinum)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Platinum;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Gold)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Gold;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Ruby)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Ruby;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Standard)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Standard;
                }
                user.PaymentType        = Domain.Socioboard.Enum.PaymentType.paypal;
                user.ActivationStatus   = Domain.Socioboard.Enum.SBUserActivationStatus.Active;
                user.CreateDate         = DateTime.UtcNow;
                user.EmailId            = EmailId;
                user.ExpiryDate         = DateTime.UtcNow.AddDays(1);
                user.UserName           = "******";
                user.EmailValidateToken = "Google";
                user.UserType           = "User";
                user.LastLoginTime      = DateTime.UtcNow;
                user.PaymentStatus      = Domain.Socioboard.Enum.SBPaymentStatus.UnPaid;
                try
                {
                    user.FirstName = (Convert.ToString(userinfo["name"]));
                }
                catch { }
                user.RegistrationType = Domain.Socioboard.Enum.SBRegistrationType.Google;

                int  SavedStatus = dbr.Add <Domain.Socioboard.Models.User>(user);
                User nuser       = dbr.Single <User>(t => t.EmailId.Equals(user.EmailId));
                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 <Groups>(group);
                    if (SavedStatus == 1)
                    {
                        Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == nuser.Id && t.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName)).FirstOrDefault();
                        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);
                    }
                }
                return(Ok(nuser));
            }
        }
        public IActionResult FacebookLogin(string AccessToken, Domain.Socioboard.Enum.SBAccountType accType)
        {
            dynamic profile = FbUser.getFbUser(AccessToken);

            if (Convert.ToString(profile) == "Invalid Access Token")
            {
                return(Ok("Invalid Access Token"));
            }
            try
            {
                string EmailId = string.Empty;
                try
                {
                    EmailId = (Convert.ToString(profile["email"]));
                }
                catch { }
                if (string.IsNullOrEmpty(EmailId))
                {
                    return(Ok("Facebook Not retuning Email"));
                }

                try
                {
                    User inMemUser = _redisCache.Get <User>(EmailId);
                    if (inMemUser != null)
                    {
                        return(Ok(inMemUser));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogInformation(ex.Message);
                    _logger.LogError(ex.StackTrace);
                }

                DatabaseRepository dbr     = new DatabaseRepository(_logger, _appEnv);
                IList <User>       lstUser = dbr.Find <User>(t => t.EmailId.Equals(EmailId));
                if (lstUser != null && lstUser.Count() > 0)
                {
                    DateTime d1 = DateTime.UtcNow;
                    //User userTable = dbr.Single<User>(t => t.EmailId == EmailId);
                    //userTable.LastLoginTime = d1;
                    lstUser.First().LastLoginTime = d1;
                    dbr.Update <User>(lstUser.First());
                    _redisCache.Set <User>(lstUser.First().EmailId, lstUser.First());
                    return(Ok(lstUser.First()));
                }
                else
                {
                    Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr);
                    if (fbacc != null && fbacc.IsActive == true)
                    {
                        return(Ok("Facebook account added by other user."));
                    }

                    Domain.Socioboard.Models.User user = new Domain.Socioboard.Models.User();
                    if (accType == Domain.Socioboard.Enum.SBAccountType.Free)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Free;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Deluxe)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Deluxe;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Premium)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Premium;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Topaz)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Topaz;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Platinum)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Platinum;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Gold)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Gold;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Ruby)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Ruby;
                    }
                    else if (accType == Domain.Socioboard.Enum.SBAccountType.Standard)
                    {
                        user.AccountType = Domain.Socioboard.Enum.SBAccountType.Standard;
                    }

                    user.ActivationStatus   = Domain.Socioboard.Enum.SBUserActivationStatus.Active;
                    user.CreateDate         = DateTime.UtcNow;
                    user.EmailId            = EmailId;
                    user.ExpiryDate         = DateTime.UtcNow.AddDays(1);
                    user.PaymentType        = Domain.Socioboard.Enum.PaymentType.paypal;
                    user.UserName           = "******";
                    user.EmailValidateToken = "Facebook";
                    try
                    {
                        user.ProfilePicUrl = "https://graph.facebook.com/" + Convert.ToString(profile["id"]) + "/picture?type=small";
                    }
                    catch { }
                    user.PaymentStatus = Domain.Socioboard.Enum.SBPaymentStatus.UnPaid;
                    try
                    {
                        user.FirstName = (Convert.ToString(profile["name"]));
                    }
                    catch { }
                    user.RegistrationType = Domain.Socioboard.Enum.SBRegistrationType.Faceboook;

                    int  SavedStatus = dbr.Add <Domain.Socioboard.Models.User>(user);
                    User nuser       = dbr.Single <User>(t => t.EmailId.Equals(user.EmailId));
                    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 <Groups>(group);
                        if (SavedStatus == 1)
                        {
                            Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == nuser.Id && t.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName)).FirstOrDefault();
                            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);
                        }
                    }
                    return(Ok(nuser));
                }
            }
            catch
            {
                return(Ok("Invalid Access Token"));
            }
        }
Esempio n. 17
0
 public IActionResult SaveImageforPrivate(long userId, string imgName, IFormFile files)
 {
     try
     {
         DatabaseRepository dbr     = new DatabaseRepository(_logger, _env);
         double             imgsize = dbr.Find <Domain.Socioboard.Models.ImgLibrary>(t => t.UserId == userId).Sum(t => t.ImageSize);
         if (imgsize <= 20971520)
         {
             long   imglength  = 0;
             var    filename   = "";
             var    apiimgPath = "";
             var    uploads    = string.Empty;
             string imgPath    = string.Empty;
             string imagePath  = string.Empty;
             string localpath  = string.Empty;
             string extension  = string.Empty;
             if (files != null)
             {
                 if (files.Length > 0)
                 {
                     var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
                     // await file.s(Path.Combine(uploads, fileName));
                     filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue
                                .Parse(files.ContentDisposition)
                                .FileName
                                .Trim('"');
                     var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1];
                     filename  = _env.WebRootPath + "\\upload\\UserImages" + $@"\{tempName}";
                     localpath = filename;
                     imgPath   = filename;
                     uploads   = _appSettings.ApiDomain + "/api/Media/getUserImages?id=" + $@"{tempName}";
                     extension = Path.GetExtension(fileName).ToUpper();
                     if (extension != ".JFIF" && extension != ".JPG" && extension != ".JPEG" && extension != ".Exif" && extension != ".GIF" && extension != ".TIFF" && extension != ".PNG" && extension != ".PPM" && extension != ".BMP" && extension != ".PGM" && extension != ".PBM" && extension != ".PNM")
                     {
                         return(BadRequest("Please select only image file"));
                     }
                     //imglength = new System.IO.FileInfo(filenameforlength).Length;
                     // size += file.Length;
                     try
                     {
                         using (FileStream fs = System.IO.File.Create(filename))
                         {
                             files.CopyTo(fs);
                             fs.Flush();
                         }
                         imglength = new System.IO.FileInfo(filename).Length;
                         double totallength = imgsize + imglength;
                         if (totallength > 20971520)
                         {
                             return(BadRequest("You have reached maximum library sapce"));
                         }
                         filename = uploads;
                         // long imglength = new System.IO.FileInfo(imagelocalPath).Length;
                     }
                     catch (System.Exception ex)
                     {
                         if (!string.IsNullOrEmpty(imagePath))
                         {
                             uploads = imagePath;
                         }
                     }
                 }
             }
             else
             {
             }
             Domain.Socioboard.Models.ImgLibrary lstImglibrary = new ImgLibrary();
             //long len = (new System.IO.FileInfo(filename)).Length;
             lstImglibrary.UserId            = userId;
             lstImglibrary.ImageName         = imgName;
             lstImglibrary.ImagePath         = filename;
             lstImglibrary.ImageSize         = imglength;
             lstImglibrary.Imageuploadeddate = DateTime.UtcNow;
             lstImglibrary.Tags           = "";
             lstImglibrary.FolderType     = "Private";
             lstImglibrary.LocalImagePath = localpath;
             lstImglibrary.Fileextension  = extension;
             int SavedStatus = dbr.Add <Domain.Socioboard.Models.ImgLibrary>(lstImglibrary);
             if (SavedStatus == 1)
             {
                 return(Ok("Image saved successfully"));
             }
             else
             {
                 return(BadRequest("Something went wrong"));
             }
         }
         else
         {
             return(BadRequest("You have reached maximum library sapce"));
         }
     }
     catch (Exception ex)
     {
         return(BadRequest("Something went wrong"));
     }
 }
Esempio n. 18
0
        public IActionResult SaveImage(long userId, string imgName, IFormFile files)
        {
            var    filename   = "";
            var    apiimgPath = "";
            var    uploads    = string.Empty;
            string imgPath    = string.Empty;
            string imagePath  = string.Empty;

            if (files != null)
            {
                if (files.Length > 0)
                {
                    var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
                    // await file.s(Path.Combine(uploads, fileName));
                    filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue
                               .Parse(files.ContentDisposition)
                               .FileName
                               .Trim('"');
                    var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1];
                    //apiimgPath = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}";

                    filename = _env.WebRootPath + "\\upload\\UserImages" + $@"\{tempName}";
                    imgPath  = filename;
                    uploads  = _appSettings.ApiDomain + "/api/Media/getUserImages?id=" + $@"{tempName}";
                    // size += file.Length;
                    try
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            files.CopyTo(fs);
                            fs.Flush();
                        }
                        filename = uploads;
                        long length = new System.IO.FileInfo(fileName).Length;
                    }
                    catch (System.Exception ex)
                    {
                        if (!string.IsNullOrEmpty(imagePath))
                        {
                            uploads = imagePath;
                        }
                    }
                }
            }
            else
            {
            }
            Domain.Socioboard.Models.AssestLibrary Imglibrary = new AssestLibrary();
            DatabaseRepository dbr = new DatabaseRepository(_logger, _env);

            //long len = (new System.IO.FileInfo(filename)).Length;
            Imglibrary.UserId            = userId;
            Imglibrary.ImageName         = imgName;
            Imglibrary.ImagePath         = filename;
            Imglibrary.ImageSize         = 25;
            Imglibrary.Imageuploadeddate = DateTime.UtcNow;
            int SavedStatus = dbr.Add <Domain.Socioboard.Models.AssestLibrary>(Imglibrary);

            if (SavedStatus == 1)
            {
                return(Ok("Image saved successfully"));
            }
            else
            {
                return(BadRequest("Something went wrong"));
            }
        }
        public IActionResult AddProfileToGroup(string profileId, long groupId, long userId, Domain.Socioboard.Enum.SocialProfileType profileType)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);
            List <Domain.Socioboard.Models.Groupprofiles> lstGroupProfiles = GroupProfilesRepository.getGroupProfiles(groupId, _redisCache, dbr);

            if (lstGroupProfiles.Where(t => t.profileId.Equals(profileId)).Count() > 0)
            {
                return(BadRequest("profile already added"));
            }
            else
            {
                Domain.Socioboard.Models.Groups grp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.id == groupId).FirstOrDefault();
                if (grp == null)
                {
                    return(BadRequest("Invalid groupId"));
                }
                else
                {
                    Domain.Socioboard.Models.Groupprofiles grpProfile = new Domain.Socioboard.Models.Groupprofiles();
                    if (profileType == Domain.Socioboard.Enum.SocialProfileType.Facebook || profileType == Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage || profileType == Domain.Socioboard.Enum.SocialProfileType.FacebookPublicPage)
                    {
                        Domain.Socioboard.Models.Facebookaccounts fbAcc = Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr);
                        if (fbAcc == null)
                        {
                            return(BadRequest("Invalid profileId"));
                        }
                        if (fbAcc.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = fbAcc.FbUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = "http://graph.facebook.com/" + fbAcc.FbUserId + "/picture?type=small";
                        grpProfile.profileType    = profileType;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)
                    {
                        Domain.Socioboard.Models.TwitterAccount twtAcc = Repositories.TwitterRepository.getTwitterAccount(profileId, _redisCache, dbr);
                        if (twtAcc == null)
                        {
                            return(BadRequest("Invalid profileId"));
                        }
                        if (twtAcc.userId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = twtAcc.twitterScreenName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = twtAcc.profileImageUrl;
                        grpProfile.profileType    = Domain.Socioboard.Enum.SocialProfileType.Twitter;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.GPlus)
                    {
                        Domain.Socioboard.Models.Googleplusaccounts gplusAccount = Repositories.GplusRepository.getGPlusAccount(profileId, _redisCache, dbr);
                        if (gplusAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (gplusAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = gplusAccount.GpUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = gplusAccount.GpProfileImage;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.GoogleAnalytics)
                    {
                        Domain.Socioboard.Models.GoogleAnalyticsAccount gplusAccount = Repositories.GplusRepository.getGAAccount(profileId, _redisCache, dbr);
                        if (gplusAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (gplusAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = gplusAccount.GaProfileName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = gplusAccount.ProfilePicUrl;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.Instagram)
                    {
                        Domain.Socioboard.Models.Instagramaccounts _Instagramaccounts = Repositories.InstagramRepository.getInstagramAccount(profileId, _redisCache, dbr);
                        if (_Instagramaccounts == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_Instagramaccounts.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _Instagramaccounts.InsUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _Instagramaccounts.ProfileUrl;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.LinkedIn)
                    {
                        Domain.Socioboard.Models.LinkedInAccount _LinkedInAccount = Repositories.LinkedInAccountRepository.getLinkedInAccount(profileId, _redisCache, dbr);
                        if (_LinkedInAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_LinkedInAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _LinkedInAccount.LinkedinUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _LinkedInAccount.ProfileImageUrl;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.LinkedInComapanyPage)
                    {
                        Domain.Socioboard.Models.LinkedinCompanyPage _LinkedInAccount = Repositories.LinkedInAccountRepository.getLinkedinCompanyPage(profileId, _redisCache, dbr);
                        if (_LinkedInAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_LinkedInAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _LinkedInAccount.LinkedinPageName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _LinkedInAccount.LogoUrl;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.YouTube)
                    {
                        Domain.Socioboard.Models.YoutubeChannel _YoutubeChannel = Repositories.GplusRepository.getYTChannel(profileId, _redisCache, dbr);
                        if (_YoutubeChannel == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_YoutubeChannel.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _YoutubeChannel.YtubeChannelName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _YoutubeChannel.ChannelpicUrl;
                    }
                    if (profileType == Domain.Socioboard.Enum.SocialProfileType.Pinterest)
                    {
                        Domain.Socioboard.Models.PinterestAccount pinAcc = dbr.Find <Domain.Socioboard.Models.PinterestAccount>(t => t.username.Equals(profileId)).FirstOrDefault();
                        if (pinAcc == null)
                        {
                            return(BadRequest("Invalid profileId"));
                        }
                        if (pinAcc.userid != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = pinAcc.firstname + " " + pinAcc.lastname;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = pinAcc.profileimgaeurl;
                        grpProfile.profileType    = profileType;
                    }
                    grpProfile.entryDate   = DateTime.UtcNow;
                    grpProfile.groupId     = grp.id;
                    grpProfile.profileId   = profileId;
                    grpProfile.profileType = profileType;
                    dbr.Add <Domain.Socioboard.Models.Groupprofiles>(grpProfile);
                    //codes to clear cache
                    _redisCache.Delete(Domain.Socioboard.Consatants.SocioboardConsts.CacheGroupProfiles + groupId);
                    //end codes to clear cache
                    return(Ok("Added Successfully"));
                }
            }
        }
        public IActionResult ComposeMessage(string message, string profileId, long userId, string imagePath, string link)
        {
            if (profileId != null)
            {
                string[] lstProfileIds = profileId.Split(',');
                profileId = lstProfileIds[0];
            }
            else
            {
                return(Ok("profileId required"));
            }
            string             ret = "";
            DatabaseRepository dbr = new DatabaseRepository(_logger, _env);

            Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr);

            FacebookClient fb = new FacebookClient();

            fb.AccessToken = objFacebookAccount.AccessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);


            try
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    Uri    u         = new Uri(imagePath);
                    string filename  = string.Empty;
                    string extension = string.Empty;
                    extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                    var media = new FacebookMediaObject
                    {
                        FileName    = "filename",
                        ContentType = "image/" + extension
                    };
                    //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                    var    webClient = new WebClient();
                    byte[] img       = webClient.DownloadData(imagePath);
                    media.SetValue(img);
                    args["source"] = media;
                    ret            = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    ret = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
                }
                ScheduledMessage scheduledMessage = new ScheduledMessage();
                scheduledMessage.createTime   = DateTime.UtcNow;
                scheduledMessage.picUrl       = imagePath;
                scheduledMessage.profileId    = profileId;
                scheduledMessage.profileType  = Domain.Socioboard.Enum.SocialProfileType.Facebook;
                scheduledMessage.scheduleTime = DateTime.UtcNow;
                scheduledMessage.shareMessage = message;
                scheduledMessage.userId       = userId;
                scheduledMessage.status       = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                scheduledMessage.url          = ret;
                dbr.Add <ScheduledMessage>(scheduledMessage);

                ret = "success";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                ret = "failure";
            }

            return(Ok(ret));
        }
Esempio n. 21
0
        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)
        {
            string         ret = "";
            FacebookClient fb  = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            //if (!string.IsNullOrEmpty(message))
            //{
            //    args["message"] = message;
            //}
            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (string.IsNullOrEmpty(link))
                {
                    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"))
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                            var media = new FacebookMediaObject
                            {
                                FileName    = "filename",
                                ContentType = "image/" + extension
                            };
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["source"] = media;
                            ret            = fb.Post("v2.7/" + fbUserId + "/photos", args).ToString();
                        }
                        else
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            filename = imagePath.Substring(imagePath.IndexOf("get?id=") + 7);
                            if (!string.IsNullOrWhiteSpace(filename))
                            {
                                extension = filename.Substring(filename.IndexOf(".") + 1);
                            }
                            var media = new FacebookMediaObject
                            {
                                FileName    = filename,
                                ContentType = "video/" + extension
                            };
                            //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            // 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();
                    }
                }
                else
                {
                    //if (!string.IsNullOrEmpty(link))
                    //{
                    //    args["link"] = link;
                    //}
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        args["picture"] = imagePath.Replace("&amp;", "&");
                    }
                    try
                    {
                        ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();//v2.1
                    }
                    catch (Exception ex)
                    {
                    }
                }
                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      = link;
                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>(scheduledMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _logger.LogError(ex.StackTrace);
            }
            return(ret);
        }