Esempio n. 1
0
        public IActionResult RecGoogleAccount(string code, long userId)
        {
            string             ret          = string.Empty;
            string             objRefresh   = string.Empty;
            string             refreshToken = string.Empty;
            string             access_token = string.Empty;
            DatabaseRepository dbr          = new DatabaseRepository(_logger, _appEnv);

            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());
                string people = objToken.GetPeopleInfo("self", access_token.ToString(), Convert.ToString(userinfo["id"]));
                userinfo = JObject.Parse(JArray.Parse(people)[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));
            }
            Domain.Socioboard.Models.Googleplusaccounts gplusAcc = Api.Socioboard.Repositories.GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);

            if (gplusAcc != null && gplusAcc.IsActive == true)
            {
                if (gplusAcc.UserId == userId)
                {
                }
                //return BadRequest("GPlus account added by other user.");
            }

            // Adding GPlus Profile
            int x = Api.Socioboard.Repositories.GplusRepository.ReconnectGplusAccount(userinfo, dbr, userId, access_token, refreshToken, _redisCache, _appSettings, _logger);

            if (x == 1)
            {
                return(Ok("Gplus Account Reconnect Successfully"));
            }
            else
            {
                return(BadRequest("Issues while adding account"));
            }
        }
Esempio n. 2
0
        public string replyToComment(string refreshtoken, string parentid, string commentText)
        {
            oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl);
            oAuthToken        objoauth             = new oAuthToken(_clientId, _clientSecret, _redirectUrl);

            string  accesstoken_jdata = objoauth.GetAccessToken(refreshtoken);
            JObject JData             = JObject.Parse(accesstoken_jdata);
            string  accesstoken       = JData["access_token"].ToString();

            commentText = commentText.Replace("\\n", "######2525").Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("######2525", "\\n");;

            string RequestUrl = "https://www.googleapis.com/youtube/v3/comments?part=snippet&key=" + accesstoken + "&alt=json";

            string postdata = "{\"snippet\":{\"parentId\":\"" + parentid + "\",\"textOriginal\":\"" + commentText + "\"}}";

            Uri path = new Uri(RequestUrl);

            string[] header   = { "Authorization", "X-JavaScript-User-Agent" };
            string[] val      = { "Bearer " + accesstoken, "Google APIs Explorer" };
            string   response = string.Empty;


            try
            {
                response = objoAuthTokenYoutube.Post_WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.POST, RequestUrl, postdata, header, val);
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }



            return(response);
        }
Esempio n. 3
0
 public void getGplusData(object UserId)
 {
     try
     {
         Guid userId = (Guid)UserId;
         GooglePlusAccountRepository objgpRepo = new GooglePlusAccountRepository();
         oAuthToken objToken = new oAuthToken();
         ArrayList  arrGpAcc = objgpRepo.getAllGooglePlusAccountsOfUser(userId);
         foreach (GooglePlusAccount itemGp in arrGpAcc)
         {
             string objRefresh = objToken.GetRefreshToken(itemGp.RefreshToken);
             if (!objRefresh.StartsWith("["))
             {
                 objRefresh = "[" + objRefresh + "]";
             }
             JArray objArray = JArray.Parse(objRefresh);
             foreach (var item in objArray)
             {
                 GetUserActivities(itemGp.GpUserId, item["access_token"].ToString(), userId);
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.StackTrace);
     }
 }
Esempio n. 4
0
        public string RejectAComment(string refreshtoken, string commmentId)
        {
            oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl);
            oAuthToken        objoauth             = new oAuthToken(_clientId, _clientSecret, _redirectUrl);
            string            accesstoken_jdata    = objoauth.GetAccessToken(refreshtoken);
            JObject           JData       = JObject.Parse(accesstoken_jdata);
            string            accesstoken = JData["access_token"].ToString();
            string            RequestUrl  = "https://www.googleapis.com/youtube/v3/comments/setModerationStatus?id=" + commmentId + "&moderationStatus=rejected&key=" + accesstoken + "&alt=json";
            string            postdata    = "";
            Uri path = new Uri(RequestUrl);

            string[] header   = { "Authorization", "X-JavaScript-User-Agent" };
            string[] val      = { "Bearer " + accesstoken, "Google APIs Explorer" };
            string   response = string.Empty;

            try
            {
                response = objoAuthTokenYoutube.Post_WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.POST, RequestUrl, postdata, header, val);
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }
            return(response);
        }
Esempio n. 5
0
        /// <summary>
        /// List all of the activities in the specified collection for a particular user.
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="access"></param>
        /// <returns></returns>
        public JArray Get_Activities_List(string UserId, string access)
        {
            oAuthToken objToken   = new oAuthToken();
            string     RequestUrl = Globals.strGetActivitiesList + UserId + "/activities/public?access_token=" + access;
            Uri        path       = new Uri(RequestUrl);

            string[] header   = { "token_type", "expires_in" };
            string[] val      = { "Bearer", "3600" };
            string   response = string.Empty;

            try
            {
                response = objToken.WebRequestHeader(path, header, val);
                if (!response.StartsWith("["))
                {
                    response = "[" + response + "]";
                }
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }

            return(JArray.Parse(response));
        }
Esempio n. 6
0
        /// <summary>
        /// Search public activities.
        /// </summary>
        /// <param name="query">Full-text search query string. </param>
        /// <param name="access"></param>
        /// <returns></returns>
        public JArray Get_Activities_Search(string query, string access)
        {
            oAuthToken objToken   = new oAuthToken(_clientId, _clientSecret, _redirectUrl);
            string     RequestUrl = Globals.strGetSearchActivity + "?query=" + query + "access_token=" + access;
            Uri        path       = new Uri(RequestUrl);

            string[] header   = { "token_type", "expires_in" };
            string[] val      = { "Bearer", "3600" };
            string   response = string.Empty;

            try
            {
                response = objToken.WebRequestHeader(path, header, val);
                if (!response.StartsWith("["))
                {
                    response = "[" + response + "]";
                }
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }

            return(JArray.Parse(response));
        }
        public IActionResult AddGoogleAccountPhone(string refreshToken, string accessToken, long groupId, long userId)
        {
            var ret        = string.Empty;
            var objRefresh = string.Empty;
            var dbr        = new DatabaseRepository(_logger, _appEnv);

            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());
                var people = objToken.GetPeopleInfo("self", accessToken, Convert.ToString(userinfo["id"]));
                userinfo = JObject.Parse(JArray.Parse(people)[0].ToString());
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
                ret = "Access Token Not Found";
                return(Ok(ret));
            }

            var gplusAcc = GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);

            if (gplusAcc != null && gplusAcc.IsActive)
            {
                if (gplusAcc.UserId == userId)
                {
                    return(BadRequest("GPlus account already added by you."));
                }
                return(BadRequest("GPlus account added by other user."));
            }

            var ngrp = dbr.Find <Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault();

            if (ngrp == null)
            {
                return(Ok("group not exist"));
            }
            // Adding GPlus Profile
            var x = GplusRepository.AddGplusAccount(userinfo, dbr, userId, ngrp.id, accessToken, refreshToken,
                                                    _redisCache, _appSettings, _logger);

            if (x == 1)
            {
                return(Ok("Gplus Account Added Successfully"));
            }
            return(BadRequest("Issues while adding account"));
        }
        public string GetRealTimeUser(string strProfileId, string strToken)
        {
            var objToken = new oAuthToken(_clientId, _clientSecret, _redirectUrl);

            try
            {
                var strDataUrl = Globals.strGetGaRealAnalytics + strProfileId + "&metrics=rt:activeUsers&dimensions=rt:deviceCategory,rt:pagePath,rt:country,rt:trafficType&access_token=" + strToken;
                var strData    = objToken.WebRequest(oAuthToken.Method.GET, strDataUrl, "");
                var jData      = JObject.Parse(strData);
                var activeUser = jData["totalsForAllResults"]["rt:activeUsers"].ToString();

                var intActiveUser = int.Parse(activeUser);

                var googleAnalyticsActiveModel = new GoogleAnalyticsActiveModel()
                {
                    ActiveUserCount = activeUser
                };


                if (intActiveUser > 0)
                {
                    var rows = (JArray)jData["rows"];


                    foreach (var row in rows)
                    {
                        var device      = row[0].Value <string>();
                        var path        = row[1].ToString();
                        var country     = row[2].ToString();
                        var trafficType = row[3].ToString();
                        var count       = row[4].ToString();

                        var googleAnalyticsRealtimeModel = new GoogleAnalyticsRealtimeModel()
                        {
                            DeviceName  = row[0].Value <string>(),
                            Path        = row[1].ToString(),
                            Country     = row[2].ToString(),
                            TrafficType = row[3].ToString(),
                            Count       = row[4].ToString(),
                        };

                        googleAnalyticsActiveModel.GoogleAnalyticsRealtimeModels.Add(googleAnalyticsRealtimeModel);
                    }
                }

                return(activeUser);
            }
            catch (Exception ex)
            {
                return("0");
            }
        }
 public void GooglePlusRedirect(object sender, EventArgs e)
 {
     if (ddlGroup.SelectedItem.Text != "Select")
     {
         Session["UserAndGroupsForFacebook"] = "googleplus";
         oAuthToken objToken = new oAuthToken();
         Response.Redirect(objToken.GetAutherizationLink("https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.login"));
     }
     else
     {
         Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "<script type=\"text/javascript\">alert(\"Select the group to add profiles\")</script>", false);
     }
 }
Esempio n. 10
0
        /// <summary>
        /// List all of the people who this user has added to one or more circles.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="access"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        public JArray Get_People_List(string userId, string access, string collection)
        {
            oAuthToken objToken   = new oAuthToken();
            string     RequestUrl = Globals.strGetPeopleList + userId + "/people/" + collection + "?access_token=" + access;
            Uri        path       = new Uri(RequestUrl);

            string[] header   = { "token_type", "expires_in" };
            string[] val      = { "Bearer", "3600" };
            string   response = objToken.WebRequestHeader(path, header, val);

            if (!response.StartsWith("["))
            {
                response = "[" + response + "]";
            }
            return(JArray.Parse(response));
        }
Esempio n. 11
0
        /// <summary>
        /// Search all public profiles
        /// </summary>
        /// <param name="query"></param>
        /// <param name="access"></param>
        /// <returns></returns>
        public JArray Get_People_Search(string query, string access)
        {
            oAuthToken objToken   = new oAuthToken();
            string     RequestUrl = Globals.strGetSearchPeople + query + "&access_token=" + access;
            Uri        path       = new Uri(RequestUrl);

            string[] header   = { "token_type", "expires_in" };
            string[] val      = { "Bearer", "3600" };
            string   response = objToken.WebRequestHeader(path, header, val);

            if (!response.StartsWith("["))
            {
                response = "[" + response + "]";
            }
            return(JArray.Parse(response));
        }
Esempio n. 12
0
        private void UpdateYoutubeFeeds(YoutubeChannel youtubeChannel)
        {
            if (youtubeChannel.LastUpdate.AddHours(1) <= DateTime.UtcNow)
            {
                if (youtubeChannel.IsActive)
                {
                    var objoAuthTokenYtubes = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    var objToken            = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    var objVideo            = new Video(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    var databaseRepository  = new DatabaseRepository();

                    ParseAndUpdateAccountDetails(youtubeChannel, databaseRepository, objVideo);
                    YoutubeFeedsfetch.ParseAndUpdateFeeds(youtubeChannel.YtubeChannelId);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Get a person's profile.
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="access"></param>
        /// <returns></returns>
        public JArray Get_People_Profile(string UserId, string access)
        {
            oAuthToken objToken   = new oAuthToken(_clientId, _clientSecret, _redirectUrl);
            string     RequestUrl = Globals.strGetPeopleProfile + UserId + "?access_token=" + access;
            Uri        path       = new Uri(RequestUrl);

            string[] header   = { "token_type", "expires_in" };
            string[] val      = { "Bearer", "3600" };
            string   response = objToken.WebRequestHeader(path, header, val);

            if (!response.StartsWith("["))
            {
                response = "[" + response + "]";
            }
            return(JArray.Parse(response));
        }
Esempio n. 14
0
        public string getAnalyticsData(string strProfileId, string metricDimension, string strdtFrom, string strdtTo, string strToken)
        {
            string     strData  = string.Empty;
            oAuthToken objToken = new oAuthToken(_clientId, _clientSecret, _redirectUrl);

            try
            {
                string strDataUrl = Globals.strGetGaAnalytics + strProfileId + "&metrics=" + metricDimension + "&start-date=" + strdtFrom + "&end-date=" + strdtTo + "&access_token=" + strToken;
                strData = objToken.WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.GET, strDataUrl, "");
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }
            return(strData);
        }
Esempio n. 15
0
        public void GetUerProfile(GooglePlusAccount objgpAcc, string acces_token, string refresh_token, Guid UserId)
        {
            PeopleController            obj       = new PeopleController();
            oAuthToken                  objtoken  = new oAuthToken();
            GooglePlusAccountRepository objgpRepo = new GooglePlusAccountRepository();

            SocialProfilesRepository socioprofilerepo = new SocialProfilesRepository();
            SocialProfile            socioprofile     = new SocialProfile();

            socioprofile.Id          = Guid.NewGuid();
            socioprofile.ProfileDate = DateTime.Now;
            socioprofile.ProfileId   = objgpAcc.GpUserId;
            socioprofile.ProfileType = "googleplus";
            socioprofile.UserId      = UserId;


            JArray objPeopleList = obj.GetPeopleList(objgpAcc.GpUserId, acces_token, "visible");

            objgpAcc.PeopleCount = objPeopleList.Count();


            if (!objgpRepo.checkGooglePlusUserExists(objgpAcc.GpUserId, UserId))
            {
                objgpRepo.addGooglePlusUser(objgpAcc);
                if (!socioprofilerepo.checkUserProfileExist(socioprofile))
                {
                    socioprofilerepo.addNewProfileForUser(socioprofile);
                }
                else
                {
                    socioprofilerepo.updateSocialProfile(socioprofile);
                }
            }
            else
            {
                objgpRepo.updateGooglePlusUser(objgpAcc);
                if (!socioprofilerepo.checkUserProfileExist(socioprofile))
                {
                    socioprofilerepo.addNewProfileForUser(socioprofile);
                }
                else
                {
                    socioprofilerepo.updateSocialProfile(socioprofile);
                }
            }
            GetUserActivities(objgpAcc.GpUserId, acces_token, UserId);
        }
Esempio n. 16
0
        public string SheduleYoutubeMessage(string YoutubeId, string UserId, string sscheduledmsgguid)
        {
            string str = string.Empty;

            try
            {
                objScheduledMessage = objScheduledMessageRepository.GetScheduledMessageDetails(Guid.Parse(sscheduledmsgguid));
                Domain.Socioboard.Domain.YoutubeAccount ObjYoutubeAccount = objYoutubeAccountRepository.getYoutubeAccountDetailsById(YoutubeId, Guid.Parse(UserId));
                oAuthToken OAuthToken = new oAuthToken();
                OAuthToken.ConsumerKey    = ConfigurationManager.AppSettings["YtconsumerKey"];
                OAuthToken.ConsumerSecret = ConfigurationManager.AppSettings["YtconsumerSecret"];
            }
            catch (Exception ex)
            {
                throw;
            }
            return(str);
        }
Esempio n. 17
0
        public string getYoutubeData(string UserId, string youtubeId)
        {
            string ret = string.Empty;

            try
            {
                Guid       userId     = Guid.Parse(UserId);
                oAuthToken OAuthToken = new oAuthToken();
                OAuthToken.ConsumerKey    = ConfigurationManager.AppSettings["YtconsumerKey"];
                OAuthToken.ConsumerSecret = ConfigurationManager.AppSettings["YtconsumerSecret"];
                YoutubeAccountRepository ObjYoutubeAccountRepository      = new YoutubeAccountRepository();
                Domain.Socioboard.Domain.YoutubeAccount ObjYoutubeAccount = ObjYoutubeAccountRepository.getYoutubeAccountDetailsById(youtubeId, userId);
                AddYouTubeChannels(userId.ToString(), ObjYoutubeAccount.Accesstoken, youtubeId);
                return("Youtube Channel is added");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 18
0
        /// <summary>
        /// List all of the moments that your app has written for the authenticated user
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="access"></param>
        /// <returns></returns>
        public JArray Get_Moment_List(string UserId, string access)
        {
            oAuthToken objToken   = new oAuthToken();
            string     RequestUrl = Globals.strMoments + UserId + "/moments/vault?access_token=" + access;
            string     response   = string.Empty;

            try
            {
                response = objToken.WebRequest(GlobusGooglePlusLib.Authentication.oAuthToken.Method.GET, RequestUrl, "");
                if (!response.StartsWith("["))
                {
                    response = "[" + response + "]";
                }
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }

            return(JArray.Parse(response));
        }
Esempio n. 19
0
 public void AuthenticateGooglePlus(object sender, EventArgs e)
 {
     try
     {
         int profilecount = (int)Session["ProfileCount"];
         int totalaccount = (int)Session["TotalAccount"];
         if (profilecount < totalaccount)
         {
             oAuthToken objToken = new oAuthToken();
             Response.Redirect(objToken.GetAutherizationLink("https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.login"));
         }
         else
         {
             Response.Write("<script>SimpleMessageAlert('Change the Plan to Add More Accounts');</script>");
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
     }
 }
Esempio n. 20
0
        /// <summary>
        /// Delete a moment that your app has written for the authenticated user.
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="access"></param>
        /// <returns></returns>
        public JArray Remove_Moment(string UserId, string access)
        {
            oAuthToken objToken   = new oAuthToken(_clientId, _clientSecret, _redirectUrl);
            string     RequestUrl = Globals.strRemoveMoments + UserId + "?access_token=" + access;
            string     response   = string.Empty;

            try
            {
                response = objToken.WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.DELETE, RequestUrl, "");
                if (!response.StartsWith("["))
                {
                    response = "[" + response + "]";
                }
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }

            return(JArray.Parse(response));
        }
Esempio n. 21
0
        public void GetGoogleplusCircles(string UserId, string ProfileId)
        {
            try
            {
                Domain.Socioboard.Domain.GooglePlusAccount _GooglePlusAccount = objGooglePlusAccountRepository.GetGooglePlusAccount(Guid.Parse(UserId), ProfileId);
                oAuthTokenGPlus ObjoAuthTokenGPlus = new oAuthTokenGPlus();
                oAuthToken      objToken           = new oAuthToken();

                #region Get_InYourCircles
                try
                {
                    string  _InyourCircles  = ObjoAuthTokenGPlus.APIWebRequestToGetUserInfo(Globals.strGetPeopleList.Replace("[userId]", _GooglePlusAccount.GpUserId).Replace("[collection]", "visible") + "?key=" + ConfigurationManager.AppSettings["Api_Key"].ToString(), _GooglePlusAccount.AccessToken);
                    JObject J_InyourCircles = JObject.Parse(_InyourCircles);
                    _GooglePlusAccount.InYourCircles = Convert.ToInt32(J_InyourCircles["totalItems"].ToString());
                }
                catch (Exception ex)
                {
                    _GooglePlusAccount.InYourCircles = 0;
                }
                #endregion

                #region Get_HaveYouInCircles
                try
                {
                    string  _HaveYouInCircles  = ObjoAuthTokenGPlus.APIWebRequestToGetUserInfo(Globals.strGetPeopleProfile + _GooglePlusAccount.GpUserId + "?key=" + ConfigurationManager.AppSettings["Api_Key"].ToString(), _GooglePlusAccount.AccessToken);
                    JObject J_HaveYouInCircles = JObject.Parse(_HaveYouInCircles);
                    _GooglePlusAccount.HaveYouInCircles = Convert.ToInt32(J_HaveYouInCircles["circledByCount"].ToString());
                }
                catch (Exception ex)
                {
                    _GooglePlusAccount.HaveYouInCircles = 0;
                }
                #endregion
                objGooglePlusAccountRepository.UpdateGooglePlusAccount(_GooglePlusAccount);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }
Esempio n. 22
0
        private string RequestAuthToken()
        {
            HttpClient client = _clientFactory.CreateClient();

            ApiRequestContent content = new ApiRequestContent();

            content.Add("grant_type", "password");
            content.Add("username", _apiCredentials.username);
            content.Add("password", _apiCredentials.password);

            string clientId             = "hw8zbkPFGguiVQ";
            string clientSecret         = "dH9be6KM24Ki5PJ_xcg3agqksX9KsQ";
            string authenticationString = $"{clientId}:{clientSecret}";
            string base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));

            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://www.reddit.com/api/v1/access_token");

            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
            requestMessage.Content = content.Export();

            //make the request
            Task <HttpResponseMessage> task     = client.SendAsync(requestMessage);
            HttpResponseMessage        response = task.Result;

            response.EnsureSuccessStatusCode();
            HttpContent responseBody = response.Content;
            string      jsonContent  = responseBody.ReadAsStringAsync().Result;
            oAuthToken  token        = JsonConvert.DeserializeObject <oAuthToken>(jsonContent);

            System.Console.WriteLine(token.access_token);
            if (token.access_token != null)
            {
                return(token.access_token);
            }
            else
            {
                throw new System.Exception("Unexpected API behavior: " + jsonContent);
            }
        }
        public GoogleAnalyticsDetails GetSessionViewOfUser(string strProfileId, string strToken, int days)
        {
            var objToken = new oAuthToken(_clientId, _clientSecret, _redirectUrl);

            var dayStart = new DateTime(DateTime.UtcNow.AddDays(-1 * days).Year, DateTime.UtcNow.AddDays(-1 * days).Month, DateTime.UtcNow.AddDays(-1 * days).Day, 0, 0, 0, DateTimeKind.Utc);
            var dayEnd   = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59, DateTimeKind.Utc);

            var strStart = dayStart.ToString("yyyy-MM-dd");
            var strEnd   = dayEnd.ToString("yyyy-MM-dd");

            try
            {
                var strDataUrl = Globals.gaSessionViews + strProfileId + "&metrics=ga:sessions,ga:pageviews&start-date=" + strStart + "&end-date=" + strEnd + "&access_token=" + strToken;
                var strData    = objToken.WebRequest(oAuthToken.Method.GET, strDataUrl, "");
                var jData      = JObject.Parse(strData);
                var sessions   = jData["totalsForAllResults"]["ga:sessions"].ToString();

                var pageviews = jData["totalsForAllResults"]["ga:pageviews"].ToString();

                var googleAnalyticsDetails = new GoogleAnalyticsDetails
                {
                    PageView = pageviews,
                    Sessions = sessions
                };

                return(googleAnalyticsDetails);
            }
            catch (Exception ex)
            {
                var googleAnalyticsDetails = new GoogleAnalyticsDetails
                {
                    PageView = "0",
                    Sessions = "0"
                };

                return(googleAnalyticsDetails);
            }
        }
Esempio n. 24
0
        public string Post_Comments_toVideo(string refreshtoken, string VideoId, string commentText)
        {
            oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl);


            oAuthToken objoauth = new oAuthToken(_clientId, _clientSecret, _redirectUrl);

            string  accesstoken_jdata = objoauth.GetAccessToken(refreshtoken);
            JObject JData             = JObject.Parse(accesstoken_jdata);
            string  accesstoken       = JData["access_token"].ToString();


            string RequestUrl = "https://content.googleapis.com/youtube/v3/commentThreads?part=snippet&key=" + accesstoken + "&alt=json";

            string postdata = "{\"snippet\": {\"videoId\": \"" + VideoId + "\",\"topLevelComment\": {\"snippet\": {\"textOriginal\": \"" + commentText + "\"}}}}";

            Uri path = new Uri(RequestUrl);

            string[] header   = { "Authorization", "X-JavaScript-User-Agent", "Origin", "X-Origin" };
            string[] val      = { "Bearer " + accesstoken, "Google APIs Explorer", "https://content.googleapis.com", "https://developers.google.com" };
            string   response = string.Empty;


            try
            {
                response = objoAuthTokenYoutube.Post_WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.POST, RequestUrl, postdata, header, val);
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }



            return(response);
        }
        public void StartUpdateAccountDetails()
        {
            try
            {
                DataServicesBase.ActivityRunningStatus.AddOrUpdate(ServiceDetails.GooglePlusUpdateDetails, true, (enumType, runningStatus) => true);
                var googleAccounts = GetGooglePlusAccounts();

                var objoAuthTokenGPlus = new oAuthTokenGPlus(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                var objToken           = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);

                Parallel.ForEach(googleAccounts, new ParallelOptions {
                    MaxDegreeOfParallelism = 20
                }, gPlusAccount =>
                {
                    UpdateGooglePlusFeeds(gPlusAccount, objoAuthTokenGPlus, objToken);
                });

                DataServicesBase.ActivityRunningStatus.AddOrUpdate(ServiceDetails.GooglePlusUpdateDetails, true, (enumType, runningStatus) => false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void UpdateYAnalyticsReports()
        {
            while (true)
            {
                try
                {
                    var databaseRepository = new DatabaseRepository();

                    var objOauthTokenYoutube = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    var objToken             = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    var ObjYAnalytics        = new YAnalytics(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);

                    var lstYtChannels = databaseRepository.Find <YoutubeChannel>(t => t.IsActive).ToList();
                    var count         = 0;

                    Console.WriteLine("---------------- Youtube Analytics Dataservices Started ----------------");
                    foreach (var youtubeChannelItem in lstYtChannels)
                    {
                        #region count for mongo data
                        var mongoreposs = new MongoRepository("YoutubeReportsData");
                        var result      = mongoreposs.Find <YoutubeReports>(t => t.channelId.Equals(youtubeChannelItem.YtubeChannelId));
                        var task        = Task.Run(async() =>
                        {
                            return(await result);
                        });
                        var lstYanalytics           = task.Result;
                        var count90AnalyticsUpdated = lstYanalytics.Count();
                        #endregion

                        try
                        {
                            if (!youtubeChannelItem.Days90Update || count90AnalyticsUpdated < 90)
                            {
                                if (youtubeChannelItem.IsActive)
                                {
                                    try
                                    {
                                        ////////code of reports here///////////////////////

                                        var to_Date = DateTime.UtcNow;
                                        var to_dd   = ("0" + Convert.ToString(to_Date.Day));
                                        to_dd = to_dd.Substring(to_dd.Length - 2);
                                        var to_mm = "0" + Convert.ToString(to_Date.Month);
                                        to_mm = to_mm.Substring(to_mm.Length - 2);
                                        var to_yyyy   = Convert.ToString(to_Date.Year);
                                        var from_Date = DateTime.UtcNow.AddDays(-90);
                                        var from_dd   = "0" + Convert.ToString(from_Date.Day);
                                        from_dd = from_dd.Substring(from_dd.Length - 2);
                                        var from_mm = "0" + Convert.ToString(from_Date.Month);
                                        from_mm = from_mm.Substring(from_mm.Length - 2);
                                        var from_yyyy   = Convert.ToString(from_Date.Year);
                                        var YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd;
                                        var YaTo_Date   = to_yyyy + "-" + to_mm + "-" + to_dd;


                                        var mongorepo = new MongoRepository("YoutubeReportsData");


                                        var AnalyticData  = ObjYAnalytics.Get_YAnalytics_ChannelId(youtubeChannelItem.YtubeChannelId, youtubeChannelItem.RefreshToken, YaFrom_Date, YaTo_Date);
                                        var JAnalyticData = JObject.Parse(AnalyticData);

                                        var dataArray = (JArray)JAnalyticData["rows"];

                                        var datesJdata = new List <string>();
                                        if (dataArray != null)
                                        {
                                            foreach (var rows in dataArray)
                                            {
                                                datesJdata.Add(rows[0].ToString());
                                            }

                                            foreach (var items in dataArray)
                                            {
                                                var objYtReports = new YoutubeReports();

                                                objYtReports.Id                         = ObjectId.GenerateNewId();
                                                objYtReports.date                       = items[0].ToString();
                                                objYtReports.channelId                  = items[1].ToString();
                                                objYtReports.SubscribersGained          = Convert.ToInt32(items[2]);
                                                objYtReports.views                      = Convert.ToInt32(items[3]);
                                                objYtReports.likes                      = Convert.ToInt32(items[4]);
                                                objYtReports.comments                   = Convert.ToInt32(items[5]);
                                                objYtReports.dislikes                   = Convert.ToInt32(items[7]);
                                                objYtReports.subscribersLost            = Convert.ToInt32(items[8]);
                                                objYtReports.averageViewDuration        = Convert.ToInt64(items[9]);
                                                objYtReports.estimatedMinutesWatched    = Convert.ToInt64(items[10]);
                                                objYtReports.annotationClickThroughRate = Convert.ToInt64(items[11]);
                                                objYtReports.annotationCloseRate        = Convert.ToInt64(items[12]);
                                                objYtReports.uniqueIdentifier           = youtubeChannelItem.YtubeChannelId + "_" + objYtReports.date;
                                                objYtReports.datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(objYtReports.date)));

                                                mongorepo.Add(objYtReports);
                                            }
                                        }
                                        else
                                        {
                                            datesJdata.Add("Null");
                                        }

                                        for (var i = 1; i <= 90; i++)
                                        {
                                            YoutubeReports objYreports  = new YoutubeReports();
                                            DateTime       dateTimeTemp = DateTime.UtcNow.AddDays(-i);

                                            var now_dd = "0" + Convert.ToString(dateTimeTemp.Day);
                                            now_dd = now_dd.Substring(now_dd.Length - 2);
                                            var now_mm = "0" + Convert.ToString(dateTimeTemp.Month);
                                            now_mm = now_mm.Substring(now_mm.Length - 2);
                                            var now_yyyy  = Convert.ToString(dateTimeTemp.Year);
                                            var Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd;

                                            if (!(datesJdata.Contains(Ynow_Date)))
                                            {
                                                objYreports.Id                         = ObjectId.GenerateNewId();
                                                objYreports.date                       = Ynow_Date;
                                                objYreports.channelId                  = youtubeChannelItem.YtubeChannelId;
                                                objYreports.SubscribersGained          = 0;
                                                objYreports.views                      = 0;
                                                objYreports.likes                      = 0;
                                                objYreports.comments                   = 0;
                                                objYreports.dislikes                   = 0;
                                                objYreports.subscribersLost            = 0;
                                                objYreports.averageViewDuration        = 0;
                                                objYreports.estimatedMinutesWatched    = 0;
                                                objYreports.annotationClickThroughRate = 0;
                                                objYreports.annotationCloseRate        = 0;
                                                objYreports.uniqueIdentifier           = youtubeChannelItem.YtubeChannelId + "_" + Ynow_Date;
                                                objYreports.datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date)));

                                                mongorepo.Add(objYreports);
                                            }
                                        }

                                        youtubeChannelItem.Days90Update      = true;
                                        youtubeChannelItem.LastReport_Update = DateTime.UtcNow;
                                        databaseRepository.Update(youtubeChannelItem);
                                    }
                                    catch (Exception)
                                    {
                                        Thread.Sleep(600000);
                                    }
                                }
                            }
                            else
                            {
                                if (youtubeChannelItem.LastReport_Update.AddHours(24) < DateTime.UtcNow)
                                {
                                    //dailyReport Code here//

                                    if (youtubeChannelItem.IsActive)
                                    {
                                        try
                                        {
                                            //code of reports here//
                                            var to_Date = DateTime.UtcNow;
                                            var to_dd   = "0" + Convert.ToString(to_Date.Day);
                                            to_dd = to_dd.Substring(to_dd.Length - 2);
                                            var to_mm = "0" + Convert.ToString(to_Date.Month);
                                            to_mm = to_mm.Substring(to_mm.Length - 2);
                                            var to_yyyy   = Convert.ToString(to_Date.Year);
                                            var from_Date = DateTime.UtcNow.AddDays(-4);
                                            var from_dd   = "0" + Convert.ToString(from_Date.Day);
                                            from_dd = from_dd.Substring(from_dd.Length - 2);
                                            var from_mm = "0" + Convert.ToString(from_Date.Month);
                                            from_mm = from_mm.Substring(from_mm.Length - 2);
                                            var from_yyyy   = Convert.ToString(from_Date.Year);
                                            var YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd;
                                            var YaTo_Date   = to_yyyy + "-" + to_mm + "-" + to_dd;



                                            var AnalyticData  = ObjYAnalytics.Get_YAnalytics_ChannelId(youtubeChannelItem.YtubeChannelId, youtubeChannelItem.RefreshToken, YaFrom_Date, YaTo_Date);
                                            var JAnalyticData = JObject.Parse(AnalyticData);

                                            var dataArray = (JArray)JAnalyticData["rows"];

                                            var datesJdata = new List <string>();
                                            if (dataArray != null)
                                            {
                                                foreach (var rows in dataArray)
                                                {
                                                    datesJdata.Add(rows[0].ToString());
                                                }

                                                foreach (var items in dataArray)
                                                {
                                                    var objYReports = new YoutubeReports();

                                                    objYReports.Id                         = ObjectId.GenerateNewId();
                                                    objYReports.date                       = items[0].ToString();
                                                    objYReports.channelId                  = items[1].ToString();
                                                    objYReports.SubscribersGained          = Convert.ToInt32(items[2]);
                                                    objYReports.views                      = Convert.ToInt32(items[3]);
                                                    objYReports.likes                      = Convert.ToInt32(items[4]);
                                                    objYReports.comments                   = Convert.ToInt32(items[5]);
                                                    objYReports.shares                     = Convert.ToInt32(items[6]);
                                                    objYReports.dislikes                   = Convert.ToInt32(items[7]);
                                                    objYReports.subscribersLost            = Convert.ToInt32(items[8]);
                                                    objYReports.averageViewDuration        = Convert.ToInt64(items[9]);
                                                    objYReports.estimatedMinutesWatched    = Convert.ToInt64(items[10]);
                                                    objYReports.annotationClickThroughRate = Convert.ToInt64(items[11]);
                                                    objYReports.annotationCloseRate        = Convert.ToInt64(items[12]);
                                                    objYReports.uniqueIdentifier           = youtubeChannelItem.YtubeChannelId + "_" + objYReports.date;
                                                    objYReports.datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(objYReports.date)));


                                                    try
                                                    {
                                                        var mongoRepotsRepo = new MongoRepository("YoutubeReportsData");
                                                        var ret             = mongoRepotsRepo.Find <YoutubeReports>(t => t.uniqueIdentifier.Equals(objYReports.uniqueIdentifier));
                                                        var task_Reports    = Task.Run(async() =>
                                                        {
                                                            return(await ret);
                                                        });
                                                        var count_Reports = task_Reports.Result.Count;
                                                        if (count_Reports < 1)
                                                        {
                                                            try
                                                            {
                                                                mongoRepotsRepo.Add(objYReports);
                                                            }
                                                            catch { }
                                                        }
                                                        else
                                                        {
                                                            try
                                                            {
                                                                var filter = new BsonDocument("uniqueIdentifier", objYReports.uniqueIdentifier);
                                                                var update = Builders <BsonDocument> .Update.Set("SubscribersGained", objYReports.SubscribersGained).Set("views", objYReports.views).Set("likes", objYReports.likes).Set("comments", objYReports.comments).Set("dislikes", objYReports.dislikes).Set("subscribersLost", objYReports.subscribersLost).Set("averageViewDuration", objYReports.averageViewDuration).Set("estimatedMinutesWatched", objYReports.estimatedMinutesWatched).Set("annotationClickThroughRate", objYReports.annotationClickThroughRate).Set("annotationCloseRate", objYReports.annotationCloseRate);

                                                                mongoRepotsRepo.Update <YoutubeReports>(update, filter);
                                                            }
                                                            catch { }
                                                        }
                                                    }
                                                    catch { }
                                                }
                                            }
                                            else
                                            {
                                                datesJdata.Add("Null");
                                            }

                                            for (var i = 1; i <= 4; i++)
                                            {
                                                var _YReports    = new YoutubeReports();
                                                var dateTimeTemp = DateTime.UtcNow.AddDays(-i);

                                                var now_dd = "0" + Convert.ToString(dateTimeTemp.Day);
                                                now_dd = now_dd.Substring(now_dd.Length - 2);
                                                var now_mm = "0" + Convert.ToString(dateTimeTemp.Month);
                                                now_mm = now_mm.Substring(now_mm.Length - 2);
                                                var now_yyyy  = Convert.ToString(dateTimeTemp.Year);
                                                var Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd;

                                                if (!(datesJdata.Contains(Ynow_Date)))
                                                {
                                                    _YReports.Id                         = ObjectId.GenerateNewId();
                                                    _YReports.date                       = Ynow_Date;
                                                    _YReports.channelId                  = youtubeChannelItem.YtubeChannelId;
                                                    _YReports.SubscribersGained          = 0;
                                                    _YReports.views                      = 0;
                                                    _YReports.likes                      = 0;
                                                    _YReports.comments                   = 0;
                                                    _YReports.dislikes                   = 0;
                                                    _YReports.subscribersLost            = 0;
                                                    _YReports.averageViewDuration        = 0;
                                                    _YReports.estimatedMinutesWatched    = 0;
                                                    _YReports.annotationClickThroughRate = 0;
                                                    _YReports.annotationCloseRate        = 0;
                                                    _YReports.uniqueIdentifier           = youtubeChannelItem.YtubeChannelId + "_" + Ynow_Date;
                                                    _YReports.datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date)));

                                                    var mongoRepotsRepo = new MongoRepository("YoutubeReportsData");
                                                    mongoRepotsRepo.Add(_YReports);
                                                }
                                            }

                                            youtubeChannelItem.LastReport_Update = DateTime.UtcNow;
                                            databaseRepository.Update(youtubeChannelItem);
                                        }
                                        catch (Exception)
                                        {
                                            Thread.Sleep(600000);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Thread.Sleep(600000);
                        }


                        var oldcount = count;
                        count++;
                        var newcount      = count;
                        var totalcount    = lstYtChannels.Count();
                        var percentagenew = (newcount * 100) / totalcount;
                        var percentageold = (oldcount * 100) / totalcount;
                        if (percentagenew != percentageold)
                        {
                            Console.WriteLine("---------------- {0}% Completed ----------------", percentagenew);
                        }
                    }
                    Thread.Sleep(600000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("issue in web api calling" + ex.StackTrace);
                    Thread.Sleep(600000);
                }
            }
        }
Esempio n. 27
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));

            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.Googleplusaccounts gplusAcc = Api.Socioboard.Repositories.GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);
                if (gplusAcc != null && gplusAcc.IsActive == true)
                {
                    return(Ok("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.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));
            }
        }
Esempio n. 28
0
        public string GetUserDropBoxData(string UserId)
        {
            List <string> _Images = new List <string>();

            Api.Socioboard.Services.DropboxAccount _DropboxAccount = new DropboxAccount();

            Domain.Socioboard.Domain.DropboxAccount _DropboxUserAccount = new Domain.Socioboard.Domain.DropboxAccount();

            _DropboxUserAccount = Newtonsoft.Json.JsonConvert.DeserializeObject <Domain.Socioboard.Domain.DropboxAccount>(_DropboxAccount.GetDropboxAccountDetailsByUserId(UserId));

            //string _Images = string.Empty;
            oAuthToken _oAuthToken = new oAuthToken();

            _oAuthToken.ConsumerKey    = ConfigurationManager.AppSettings["DBX_Appkey"];
            _oAuthToken.ConsumerSecret = ConfigurationManager.AppSettings["DBX_Appsecret"];
            _oAuthToken.Token          = _DropboxUserAccount.OauthToken;
            _oAuthToken.TokenSecret    = _DropboxUserAccount.OauthTokenSecret;
            //GET USER DASHBOARD
            string _User_DBX_Home = GlobussDropboxLib.Dropbox.Core.Metadata.Metadata.GetDropBoxFolder(ref _oAuthToken, _DropboxUserAccount.AccessToken);

            //CONVERT IN JSON OBJECT
            var _OBJ_HOME = Newtonsoft.Json.Linq.JObject.Parse(_User_DBX_Home);

            //GET FOLDER AND FILES FROM USER HOME
            foreach (var _OBJ_HOME_item in _OBJ_HOME["contents"])
            {//GET DROPBOX DASHBOARD DATA.
                string is_dir = string.Empty;

                if (_OBJ_HOME_item["is_dir"].ToString() == "true")
                {
                    is_dir = _OBJ_HOME_item["is_dir"].ToString();
                }
                else
                {
                    is_dir = "false";
                }

                string rev  = _OBJ_HOME_item["rev"].ToString();
                string path = _OBJ_HOME_item["path"].ToString();
                string icon = _OBJ_HOME_item["icon"].ToString();


                //GET FILES FROM FOLDER
                if (!string.IsNullOrEmpty(path) && !path.Contains(".pdf") && !path.Contains(".jpg")) //GET FOLDER FROM DROPBOX DASHBOARD.
                {                                                                                    //WHEN FOLDER
                    string _User_DBX_Folder_File = GlobussDropboxLib.Dropbox.Core.Metadata.Metadata.GetDropBoxFiles(ref _oAuthToken, _DropboxUserAccount.AccessToken, "dropbox", path.Replace("/", string.Empty));
                    //CONVERT IN JSON OBJECT
                    var _OBJ_HOME_FOLDER = Newtonsoft.Json.Linq.JObject.Parse(_User_DBX_Folder_File);

                    //GET FOLDER AND FILES FROM USER HOME
                    foreach (var _OBJ_HOME_FOLDER_item in _OBJ_HOME_FOLDER["contents"])
                    {//GET IMAGE FROM FOLDER.
                        string Filepath             = _OBJ_HOME_FOLDER_item["path"].ToString();
                        string _User_DBX_File_Media = GlobussDropboxLib.Dropbox.Core.Media.Media.GetDropBoxDirectlink(ref _oAuthToken, _DropboxUserAccount.AccessToken, Filepath);
                        string _LinkUrl             = Newtonsoft.Json.Linq.JObject.Parse(_User_DBX_File_Media)["url"].ToString();

                        if (_LinkUrl.Contains(".jpg") || _LinkUrl.Contains(".png"))
                        {
                            //_Images += "<div class=\"span2\"><div class=\"checkbox check\">"
                            //        + "<input type=\"checkbox\"></div><img id=\"Img1\" src=\"" + _LinkUrl + "\" alt=\"\" style=\"height: 50px;\"></div>";

                            _Images.Add(_LinkUrl);
                        }
                    } //END FOREACH
                }     //END IF
                else if (!string.IsNullOrEmpty(path) && !path.Contains(".pdf") && path.Contains(".jpg")) //GET PIC FILE WHEN ITS ADDED ON HOME NOT IN FOLDER.
                { //WHEN PHOTO ON DROPBOX DASHBOARD.
                    string _User_DBX_File_Media = GlobussDropboxLib.Dropbox.Core.Media.Media.GetDropBoxDirectlink(ref _oAuthToken, _DropboxUserAccount.AccessToken, path);
                    string _LinkUrl             = Newtonsoft.Json.Linq.JObject.Parse(_User_DBX_File_Media)["url"].ToString();
                    //_Images += "<div class=\"span2\"><div class=\"checkbox check\">"
                    //        + "<input type=\"checkbox\">  </div><img id=\"Img1\" src=\"" + _LinkUrl + "\" alt=\"\" style=\"height: 50px;\"></div>";

                    _Images.Add(_LinkUrl);
                }//END ELSE IF
                else
                {
                } //END ELSE
            }     //END FOREACH

            //Response.Write(_Images);
            //return _User_DBX_Home;
            return(Newtonsoft.Json.JsonConvert.SerializeObject(_Images));
        }
Esempio n. 29
0
        public string AddGPlusAccount(string client_id, string client_secret, string redirect_uri, string UserId, string GroupId, string code)
        {
            string ret          = string.Empty;
            string objRefresh   = string.Empty;
            string refreshToken = string.Empty;
            string access_token = string.Empty;

            try
            {
                oAuthTokenGPlus ObjoAuthTokenGPlus = new oAuthTokenGPlus();
                oAuthToken      objToken           = new oAuthToken();
                objToken.ConsumerKey    = client_id;
                objToken.ConsumerSecret = client_secret;

                try
                {
                    objRefresh = ObjoAuthTokenGPlus.GetRefreshToken(code, client_id, client_secret, redirect_uri);
                    logger.Error("vikash: ObjoAuthTokenGPlus()");
                }
                catch (Exception ex) { }
                JObject objaccesstoken = JObject.Parse(objRefresh);

                try
                {
                    refreshToken = objaccesstoken["refresh_token"].ToString();
                }
                catch (Exception ex)
                {
                    access_token = objaccesstoken["access_token"].ToString();
                    ObjoAuthTokenGPlus.RevokeToken(access_token);
                    Console.WriteLine(ex.StackTrace);
                    ret = "Refresh Token Not Found";
                    return(ret);
                }

                try
                {
                    access_token = objaccesstoken["access_token"].ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }

                JArray userinfo = new JArray();
                try
                {
                    userinfo = objToken.GetUserInfo("self", access_token.ToString());
                }
                catch (Exception ex)
                {
                }
                Domain.Socioboard.Domain.GooglePlusAccount _GooglePlusAccount = new Domain.Socioboard.Domain.GooglePlusAccount();
                foreach (var itemuserinfo in userinfo)
                {
                    try
                    {
                        _GooglePlusAccount.Id             = Guid.NewGuid();
                        _GooglePlusAccount.GpUserId       = itemuserinfo["id"].ToString();
                        _GooglePlusAccount.GpUserName     = itemuserinfo["name"].ToString();
                        _GooglePlusAccount.GpProfileImage = itemuserinfo["picture"].ToString();
                        _GooglePlusAccount.IsActive       = 1;
                        _GooglePlusAccount.ProfileType    = "gplus";
                        _GooglePlusAccount.AccessToken    = access_token;
                        _GooglePlusAccount.RefreshToken   = refreshToken;
                        _GooglePlusAccount.EmailId        = itemuserinfo["email"].ToString();
                        _GooglePlusAccount.UserId         = Guid.Parse(UserId);
                        _GooglePlusAccount.EntryDate      = DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        logger.Error("AddGPlusAccount => GooglePlusAccount =>" + ex.Message);
                    }
                }
                #region Get_InYourCircles
                try
                {
                    string  _InyourCircles  = ObjoAuthTokenGPlus.APIWebRequestToGetUserInfo(Globals.strGetPeopleList.Replace("[userId]", _GooglePlusAccount.GpUserId).Replace("[collection]", "visible") + "?key=" + ConfigurationManager.AppSettings["Api_Key"].ToString(), access_token);
                    JObject J_InyourCircles = JObject.Parse(_InyourCircles);
                    _GooglePlusAccount.InYourCircles = Convert.ToInt32(J_InyourCircles["totalItems"].ToString());
                }
                catch (Exception ex)
                {
                    _GooglePlusAccount.InYourCircles = 0;
                }
                #endregion

                #region Get_HaveYouInCircles
                try
                {
                    string  _HaveYouInCircles  = ObjoAuthTokenGPlus.APIWebRequestToGetUserInfo(Globals.strGetPeopleProfile + _GooglePlusAccount.GpUserId + "?key=" + ConfigurationManager.AppSettings["Api_Key"].ToString(), access_token);
                    JObject J_HaveYouInCircles = JObject.Parse(_HaveYouInCircles);
                    _GooglePlusAccount.HaveYouInCircles = Convert.ToInt32(J_HaveYouInCircles["circledByCount"].ToString());
                }
                catch (Exception ex)
                {
                    _GooglePlusAccount.HaveYouInCircles = 0;
                }
                #endregion

                #region Add GPlusAccount
                if (!objGooglePlusAccountRepository.checkGooglePlusUserExists(_GooglePlusAccount.GpUserId, _GooglePlusAccount.UserId))
                {
                    objGooglePlusAccountRepository.addGooglePlusUser(_GooglePlusAccount);
                    #region Add TeamMemberProfile
                    Domain.Socioboard.Domain.Team objTeam = objTeamRepository.GetTeamByGroupId(Guid.Parse(GroupId));
                    Domain.Socioboard.Domain.TeamMemberProfile objTeamMemberProfile = new Domain.Socioboard.Domain.TeamMemberProfile();
                    objTeamMemberProfile.Id               = Guid.NewGuid();
                    objTeamMemberProfile.TeamId           = objTeam.Id;
                    objTeamMemberProfile.Status           = 1;
                    objTeamMemberProfile.ProfileType      = "gplus";
                    objTeamMemberProfile.StatusUpdateDate = DateTime.Now;
                    objTeamMemberProfile.ProfileId        = _GooglePlusAccount.GpUserId;
                    objTeamMemberProfile.ProfilePicUrl    = _GooglePlusAccount.GpProfileImage;
                    objTeamMemberProfile.ProfileName      = _GooglePlusAccount.GpUserName;
                    objTeamMemberProfileRepository.addNewTeamMember(objTeamMemberProfile);
                    #endregion
                    #region SocialProfile
                    Domain.Socioboard.Domain.SocialProfile objSocialProfile = new Domain.Socioboard.Domain.SocialProfile();
                    objSocialProfile.Id            = Guid.NewGuid();
                    objSocialProfile.ProfileType   = "gplus";
                    objSocialProfile.ProfileId     = _GooglePlusAccount.GpUserId;
                    objSocialProfile.UserId        = Guid.Parse(UserId);
                    objSocialProfile.ProfileDate   = DateTime.Now;
                    objSocialProfile.ProfileStatus = 1;
                    if (!objSocialProfilesRepository.checkUserProfileExist(objSocialProfile))
                    {
                        objSocialProfilesRepository.addNewProfileForUser(objSocialProfile);
                    }
                    #endregion

                    ret = "Account Added Successfully";
                }
                else
                {
                    ret = "Account already Exist !";
                }

                #endregion
                GetUserActivities(UserId, _GooglePlusAccount.GpUserId, access_token);
                return(new JavaScriptSerializer().Serialize(_GooglePlusAccount));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return("");
            }
        }
Esempio n. 30
0
 public Accounts()
 {
     objToken = new oAuthToken();
 }