public string GetShortToken(string pageId)
        {
            var newToken = string.Empty;
            var url      = String.Format("{0}/{1}/accounts?access_token={2}", ConfigurationHandler.FacebookGraphAPI,
                                         ConfigurationHandler.FacebookPersonalId, ConfigurationHandler.FacebookPageToken);
            var content = WebHandler.DownloadContent(url);
            var jsonObj = (JObject)JsonConvert.DeserializeObject(content);

            if (jsonObj != null && jsonObj["data"] != null && jsonObj["data"].Children().Any())
            {
                foreach (var subresult in jsonObj["data"].Children())
                {
                    if (pageId.Equals((subresult.Value <string>("id"))))
                    {
                        var newCredential = new FacebookCredentialViewModel()
                        {
                            Category    = subresult.Value <string>("category"),
                            Name        = subresult.Value <string>("name"),
                            AccessToken = subresult.Value <string>("access_token"),
                            PageId      = Convert.ToInt64(subresult.Value <string>("id"))
                        };

                        newToken = newCredential.AccessToken;
                    }
                }
            }

            return(newToken);
        }
        //NOTE:
        //Log into Facebook with [email protected]/jeff1451
        //Go to Graph Explorer Tool https://developers.facebook.com/tools/explorer
        //Change Application to VINSocial
        //Then, get Access Token. It's Debug Token
        //Example URL to get long live token
        //https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=1412310822338075&client_secret=8840773be7acdda32558472f5c15bd56&fb_exchange_token={3}
        public string GetLongLiveToken(string debugToken)
        {
            var url =
                String.Format(
                    "{0}/oauth/access_token?grant_type=fb_exchange_token&client_id={1}&client_secret={2}&fb_exchange_token={3}",
                    ConfigurationHandler.FacebookGraphAPI, ConfigurationHandler.FacebookAppId,
                    ConfigurationHandler.FacebookAppSecret, debugToken);
            var content = WebHandler.DownloadContent(url);

            return(content.Split('&')[0].Split('=')[1]);
        }
 private int GetPostClicks(string pageId)
 {
     try
     {
         var url     = String.Format("{0}/{1}/insights/page_consumptions?access_token={2}", ConfigurationHandler.FacebookGraphAPI, pageId, ConfigurationHandler.FacebookPageToken);
         var content = WebHandler.DownloadContent(url);
         var jsonObj = (JObject)JsonConvert.DeserializeObject(content);
         return(Convert.ToInt32(jsonObj["data"].Children().Last()["values"].Children().Last().Value <string>("value")));
     }
     catch (Exception)
     {
         return(0);
     }
 }
 private int GetTotalPostLikes(string postId, string pageId)
 {
     try
     {
         var url     = String.Format("{0}/{1}_{2}/likes?summary=1&access_token={3}", ConfigurationHandler.FacebookGraphAPI, pageId, postId, ConfigurationHandler.FacebookPageToken);
         var content = WebHandler.DownloadContent(url);
         var jsonObj = (JObject)JsonConvert.DeserializeObject(content);
         return(Convert.ToInt32(jsonObj["summary"].Children().First().First().Value <string>()));
     }
     catch (Exception)
     {
         return(0);
     }
 }
 public int GetPostInsightValue(string postId, string pageId, string type)
 {
     try
     {
         var url     = String.Format("{0}/{1}_{2}/insights/{3}?access_token={4}", ConfigurationHandler.FacebookGraphAPI, pageId, postId, type, ConfigurationHandler.FacebookPageToken);
         var content = WebHandler.DownloadContent(url);
         var jsonObj = (JObject)JsonConvert.DeserializeObject(content);
         return(Convert.ToInt32(jsonObj["data"].Children().Last()["values"].Children().Last().Value <string>("value")));
     }
     catch (Exception)
     {
         return(0);
     }
 }
        public FacebokPersonalInfo GetPersonalInfo(string id)
        {
            var url     = String.Format("{0}/{1}", ConfigurationHandler.FacebookGraphAPI, id);
            var content = WebHandler.DownloadContent(url);
            var jsonObj = (JObject)JsonConvert.DeserializeObject(content);

            return(jsonObj != null ? new FacebokPersonalInfo()
            {
                Id = jsonObj["id"] != null?Convert.ToInt64(jsonObj.Value <string>("id")) : 0,
                         Name = jsonObj["name"] != null ? (jsonObj.Value <string>("name")) : string.Empty,
                         Likes = jsonObj["likes"] != null?Convert.ToInt32(jsonObj.Value <string>("likes")) : 0,
                                     TalkingAbout = jsonObj["talking_about_count"] != null?Convert.ToInt32(jsonObj.Value <string>("talking_about_count")) : 0,
                                                        Category = jsonObj["category"] != null ? (jsonObj.Value <string>("category")) : string.Empty,
                                                        About = jsonObj["about"] != null ? (jsonObj.Value <string>("about")) : string.Empty,
                                                        Phone = jsonObj["phone"] != null ? (jsonObj.Value <string>("phone")) : string.Empty,
                                                        Website = jsonObj["website"] != null ? (jsonObj.Value <string>("website")) : string.Empty,
                                                        Link = jsonObj["link"] != null ? (jsonObj.Value <string>("link")) : string.Empty,
            } : null);
        }
        public List <FacebookPostViewModel> GetTopPosts(string pageId, bool viewInsight = false, bool includeUserName = false)
        {
            //var accessToken = GetShortToken("118949304788934") /*GetShortToken(dealerId)*/;
            var url     = String.Format("{0}/{1}/posts?access_token={2}", ConfigurationHandler.FacebookGraphAPI, pageId, ConfigurationHandler.FacebookPageToken);
            var content = WebHandler.DownloadContent(url);
            var jsonObj = (JObject)JsonConvert.DeserializeObject(content);
            var list    = new List <FacebookPostViewModel>();

            foreach (var result in jsonObj["data"].Children())
            {
                var type    = result["type"] == null ? "" : result.Value <string>("type");
                var message = result["message"] == null ? (result["story"] == null ? (result["name"] == null ? type : result.Value <string>("name")) : result.Value <string>("story"))
                                                        : result.Value <string>("message");
                //if (((!type.Equals("video") && !type.Equals("photo") && !type.Equals("link")) || String.IsNullOrEmpty(message))) continue;

                var createdTime = result["created_time"] == null ? "" : result.Value <string>("created_time");
                var updatedTime = result["updated_time"] == null ? "" : result.Value <string>("updated_time");
                if (string.IsNullOrEmpty(createdTime))
                {
                    createdTime = updatedTime;
                }

                list.Add(new FacebookPostViewModel()
                {
                    RealPostId = Convert.ToInt64(result.Value <string>("id").Split('_')[1]),
                    //RealPostUrl = String.Format("https://www.facebook.com/{0}", (result.Value<string>("id"))),
                    RealPostUrl    = String.Format("https://www.facebook.com/{0}/posts/{1}", Convert.ToInt64(result.Value <string>("id").Split('_')[0]), Convert.ToInt64(result.Value <string>("id").Split('_')[1])),
                    TotalReach     = !viewInsight ? 0 : GetPostInsightValue(result.Value <string>("id").Split('_')[1], result.Value <string>("id").Split('_')[0], "post_impressions_unique"),
                    Like           = !viewInsight ? 0 : GetTotalPostLikes(result.Value <string>("id").Split('_')[1], result.Value <string>("id").Split('_')[0]),
                    Content        = message,
                    Icon           = result["icon"] == null ? "" : result.Value <string>("icon"),
                    Picture        = result["picture"] == null ? "" : result.Value <string>("picture"),
                    Type           = type,
                    PublishDate    = ParseDate(createdTime),
                    StrPublishDate = ParseDate(createdTime).ToString("MM/dd/yyyy hh:mm tt"),
                    UpdatedDate    = ParseDate(updatedTime),
                    UserName       = !includeUserName ? string.Empty : _facebookManagement.GetUserNameByRealPostId(Convert.ToInt64(result.Value <string>("id").Split('_')[1]))
                });
            }

            return(list);
        }
        public int GetPostClicksByWeek(string pageId, DateTime since, DateTime until)
        {
            try
            {
                var url     = String.Format("{0}/{1}/insights/page_consumptions?period=day&access_token={2}&since={3}&until={4}", ConfigurationHandler.FacebookGraphAPI, pageId, ConfigurationHandler.FacebookPageToken, ToUnixTimespan(since), ToUnixTimespan(until));
                var content = WebHandler.DownloadContent(url);
                var jsonObj = (JObject)JsonConvert.DeserializeObject(content);
                int clicks  = 0;
                foreach (var item in jsonObj["data"].Children().Last()["values"].Children())
                {
                    clicks += Convert.ToInt32(item.Value <string>("value"));
                }

                return(clicks);
            }
            catch (Exception)
            {
                return(0);
            }
        }
        public int GetPageInsightValueByWeek(string pageId, string type, DateTime since, DateTime until, string duration = "week")
        {
            try
            {
                var url = String.Format("{0}/{1}/insights/{2}?access_token={3}&since={4}&until={5}", ConfigurationHandler.FacebookGraphAPI, pageId, type, ConfigurationHandler.FacebookPageToken, ToUnixTimespan(since), ToUnixTimespan(until));
                switch (duration)
                {
                case "week":
                    url += "&period=week";
                    break;

                default:
                    break;
                }

                var content = WebHandler.DownloadContent(url);
                var jsonObj = (JObject)JsonConvert.DeserializeObject(content);
                return(Convert.ToInt32(jsonObj["data"].Children().Last()["values"].Children().Last().Value <string>("value")));
            }
            catch (Exception)
            {
                return(0);
            }
        }