-
-
Save sefacan/174639ac96f083fb3a20fb4baee45bef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json.Linq; | |
using RestSharp; | |
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Linq; | |
using System.Web.Mvc; | |
using System.Web.Script.Serialization; | |
namespace Admin.Controllers | |
{ | |
public class ActivityController : BaseController | |
{ | |
private string clientId = ConfigurationManager.AppSettings["AnalyticsClientId"]; | |
private string clientSecret = ConfigurationManager.AppSettings["AnalyticsClientSecret"]; | |
private string returnUri = ConfigurationManager.AppSettings["AnalyticsClientRedirect"]; | |
private Token token = new Token(); | |
public ActionResult Index() | |
{ | |
if (System.Web.HttpContext.Current.Cache["AnayticsCachedToken"] != null) | |
{ | |
return RedirectToAction("Authorization", new { token = (Token)System.Web.HttpContext.Current.Cache["AnayticsCachedToken"] }); | |
} | |
else | |
{ | |
var clientAuth = new RestClient(); | |
clientAuth.BaseUrl = new Uri("https://accounts.google.com/o/oauth2/auth"); | |
var request = new RestRequest(Method.GET); | |
request.RequestFormat = DataFormat.Json; | |
request.AddParameter("redirect_uri", returnUri); | |
request.AddParameter("scope", "https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.readonly"); | |
request.AddParameter("response_type", "code"); | |
request.AddParameter("client_id", clientId); | |
request.AddParameter("approval_prompt", "force"); | |
var response = clientAuth.Execute(request); | |
return Redirect(response.ResponseUri.ToString()); | |
} | |
} | |
public ActionResult Authorization(string code, Token token) | |
{ | |
if (!string.IsNullOrWhiteSpace(code)) | |
{ | |
var client = new RestClient(); | |
client.BaseUrl = new Uri("https://www.googleapis.com/oauth2/v3/token"); | |
var request = new RestRequest(Method.POST); | |
request.AddParameter("code", code); | |
request.AddParameter("redirect_uri", returnUri); | |
request.AddParameter("client_id", clientId); | |
request.AddParameter("client_secret", clientSecret); | |
request.AddParameter("scope", "https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.readonly"); | |
request.AddParameter("grant_type", "authorization_code"); | |
var response = client.Execute(request); | |
response.ContentType = "application/x-www-form-urlencoded"; | |
if (response.StatusCode == System.Net.HttpStatusCode.OK) | |
{ | |
try | |
{ | |
var json = new JavaScriptSerializer(); | |
var data = json.Deserialize<Dictionary<string, string>>(response.Content); | |
string access_token = data.FirstOrDefault(x => x.Key == "access_token").Value; | |
string token_type = data.FirstOrDefault(x => x.Key == "token_type").Value; | |
string expires_in = data.FirstOrDefault(x => x.Key == "expires_in").Value; | |
string refresh_token = data.FirstOrDefault(x => x.Key == "refresh_token").Value; | |
token = new Token | |
{ | |
access_token = access_token, | |
expires_in = expires_in, | |
refresh_token = refresh_token, | |
token_type = token_type | |
}; | |
System.Web.HttpContext.Current.Cache["AnayticsCachedToken"] = token; | |
return RedirectToAction("Result", new { token = token }); | |
} | |
catch (Exception ex) | |
{ | |
var error = ex.Message; | |
} | |
} | |
} | |
else if (System.Web.HttpContext.Current.Cache["AnayticsCachedToken"] != null) | |
{ | |
token = (Token)System.Web.HttpContext.Current.Cache["AnayticsCachedToken"]; | |
return RedirectToAction("Result", new { token = token }); | |
} | |
return View(); | |
} | |
public ActionResult Result() | |
{ | |
if (System.Web.HttpContext.Current.Cache["AnayticsCachedToken"] != null) | |
{ | |
token = (Token)System.Web.HttpContext.Current.Cache["AnayticsCachedToken"]; | |
var client = new RestClient(); | |
client.BaseUrl = new Uri("https://www.googleapis.com/analytics/v3/data/realtime"); | |
var request = new RestRequest(Method.GET); | |
request.AddParameter("access_token", token.access_token); | |
request.AddParameter("ids", "ga:104837543"); | |
request.AddParameter("metrics", "rt:activeUsers"); | |
request.AddParameter("dimensions", "rt:pagePath,rt:pageTitle"); | |
var response = client.Execute(request); | |
response.ContentType = "application/json"; | |
if (response.StatusCode == System.Net.HttpStatusCode.OK) | |
{ | |
//var json = new JavaScriptSerializer(); | |
var data = new RealTimeData(); | |
JObject o = JObject.Parse(response.Content); | |
foreach (var result in o.SelectToken("$..totalsForAllResults")) | |
{ | |
data.ActiveUserCount = Convert.ToInt32(result["rt:activeUsers"]); | |
} | |
if (o.SelectToken("$..rows") != null) | |
{ | |
foreach (var result in o.SelectToken("$..rows")) | |
{ | |
var pages = new RealTimePages | |
{ | |
Page = result[0].ToString(), | |
Heading = result[1].ToString(), | |
Count = Convert.ToInt32(result[2].ToString()) | |
}; | |
data.RealTimePages.Add(pages); | |
} | |
} | |
} | |
} | |
return View(); | |
} | |
} | |
public class RealTimeData | |
{ | |
public int ActiveUserCount { get; set; } | |
public List<RealTimePages> RealTimePages { get; set; } | |
} | |
public class RealTimePages | |
{ | |
public string Page { get; set; } | |
public string Heading { get; set; } | |
public int Count { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment