Facebook
From fd, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 279
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. using System.Threading;
  8. using Google.Apis.AnalyticsReporting.v4;
  9. using Google.Apis.AnalyticsReporting.v4.Data;
  10. using Google.Apis.Auth.OAuth2;
  11. using Google.Apis.Services;
  12. using Google.Apis.Util.Store;
  13. using Newtonsoft.Json;
  14.  
  15. namespace GoogleAnalyticsDataDownload
  16. {
  17.     public class Site
  18.     {
  19.         public string Name { get; set; }
  20.         public string ViewId { get; set; }
  21.     };
  22.  
  23.     public class Conditions
  24.     {
  25.         public int Interest { get; set; }
  26.         public int Category { get; set; }
  27.         public int Gender { get; set; }
  28.         public int Age { get; set; }
  29.     };
  30.  
  31.     class Program
  32.     {
  33.         public static object Session { get; private set; }
  34.  
  35.         static void Main(string[] args)
  36.         {
  37.  
  38.             try
  39.             {
  40.  
  41.                 var credential = GetCredential().Result;
  42.  
  43.                 //TextWriter dataFile = new StreamWriter(@"C:GaApiReaderHourGranulationGoogleAnalyticsData.txt", false);
  44.                 TextWriter dataFile = new StreamWriter(@"C:HourGranulationGoogleAnalyticsData.txt", false);
  45.  
  46.                 //TextWriter dataFile = new StreamWriter(@"C:Userskatarzyna.panasiukDesktopGoogleAnalyticsDataDownloadForReportGoogleAnalyticsData.txt", false);
  47.  
  48.                 using (var svc = new AnalyticsReportingService(
  49.                     new BaseClientService.Initializer
  50.                     {
  51.                         HttpClientInitializer = credential,
  52.                         ApplicationName = "Google Analytics API Console"
  53.                     }))
  54.                 {
  55.  
  56.                     //weekly
  57.                    
  58.                     DateTime StartDateRange = new DateTime(DateTime.Today.AddDays(-7).Year, DateTime.Today.AddDays(-7).Month, DateTime.Today.AddDays(-7).Day);
  59.                     string YearStartDate = StartDateRange.Year.ToString();
  60.                     string MonthStartDate = ("0" + StartDateRange.Month.ToString());
  61.                     MonthStartDate = MonthStartDate.Substring(MonthStartDate.Length - 2, 2);
  62.                     string DayStartDate = ("0" + StartDateRange.Day.ToString());
  63.                     DayStartDate = DayStartDate.Substring(DayStartDate.Length - 2, 2);
  64.  
  65.                     DateTime EndDateRange = new DateTime(DateTime.Today.AddDays(-1).Year, DateTime.Today.AddDays(-1).Month, DateTime.Today.AddDays(-1).Day);
  66.                     string YearEndDate = EndDateRange.Year.ToString();
  67.                     string MonthEndDate = ("0" + EndDateRange.Month.ToString());
  68.                     MonthEndDate = MonthEndDate.Substring(MonthEndDate.Length - 2, 2);
  69.                     string DayEndDate = ("0" + EndDateRange.Day.ToString());
  70.                     DayEndDate = DayEndDate.Substring(DayEndDate.Length - 2, 2);
  71.  
  72.  
  73.                     //ZAKRES DAT
  74.                     var dateRange = new DateRange
  75.                     {
  76.                         StartDate = YearStartDate + "-" + MonthStartDate + "-" + DayStartDate,
  77.                         EndDate = YearEndDate + "-" + MonthEndDate + "-" + DayEndDate
  78.                     };
  79.  
  80.                    
  81.                     Console.WriteLine("Start date: " + YearStartDate + "-" + MonthStartDate + "-" + DayStartDate);
  82.                     Console.WriteLine("End date: " + YearEndDate + "-" + MonthEndDate + "-" + DayEndDate);
  83.  
  84.                     //MIARY
  85.                     var sessions = new Metric
  86.                     {
  87.                         Expression = "ga:sessions",
  88.                         Alias = "Sessions"
  89.                     };
  90.  
  91.                     var pageviews = new Metric
  92.                     {
  93.                         Expression = "ga:pageviews",
  94.                         Alias = "PageViews"
  95.                     };
  96.  
  97.                     var users = new Metric
  98.                     {
  99.                         Expression = "ga:users",
  100.                         Alias = "Users"
  101.                     };
  102.                
  103.                     //WYMIARY
  104.                     var year = new Dimension { Name = "ga:year" };
  105.                     var month = new Dimension { Name = "ga:month" };
  106.                     var day = new Dimension { Name = "ga:day" };
  107.                     var hour = new Dimension { Name = "ga:hour" };
  108.                     var age = new Dimension { Name = "ga:userAgeBracket" };
  109.                     var gender = new Dimension { Name = "ga:userGender" };
  110.  
  111.                     //WYMIARY - INTEREST
  112.                     var interestOtherCategory = new Dimension { Name = "ga:interestOtherCategory" };
  113.                     var interestInMarketCategory = new Dimension { Name = "ga:interestInMarketCategory" };
  114.                     var interestAffinityCategory = new Dimension { Name = "ga:interestAffinityCategory" };
  115.  
  116.                     List<Site> sites = new List<Site>();
  117.                     sites.Add(new Site() { Name = "Glamour", ViewId = "4602634" });
  118.                     sites.Add(new Site() { Name = "Focus", ViewId = "4524300" });
  119.                     sites.Add(new Site() { Name = "Gala", ViewId = "4695680" });
  120.                     //sites.Add(new Site() { Name = "SlowlyVeggie", ViewId = "102281875" }); //problem z dostepem ?
  121.                     //sites.Add(new Site() { Name = "Kobieta", ViewId = "4865279" });
  122.                     //sites.Add(new Site() { Name = "Mój Piękny Ogród", ViewId = "47630724" });
  123.                     //sites.Add(new Site() { Name = "Burda", ViewId = "61966321" });
  124.                     //sites.Add(new Site() { Name = "Elle", ViewId = "61961573" });
  125.                     //sites.Add(new Site() { Name = "InStyle", ViewId = "64813361" });
  126.                     //sites.Add(new Site() { Name = "CRN", ViewId = "7264016" });
  127.                     //sites.Add(new Site() { Name = "Moje Gotowanie", ViewId = "4865333" });
  128.                     //sites.Add(new Site() { Name = "Przyślij Przepis", ViewId = "55337319" });
  129.                     //sites.Add(new Site() { Name = "National Geographic", ViewId = "4524316" });
  130.                     //sites.Add(new Site() { Name = "Claudia", ViewId = "119034446" });
  131.                    
  132.  
  133.                     List<String> lines = new List<string>();
  134.  
  135.  
  136.                     lines.Add("Site;Users;Sessions;PageViews;Year;Month;Day;Hour;Interest;Category;Gender;Age");
  137.  
  138.                     List<String> interests = new List<string>();
  139.                     interests.Add("OtherCategory");
  140.                     interests.Add("InMarketCategory");
  141.                     interests.Add("AffinityCategory");
  142.  
  143.                     var Filter = new DimensionFilter();
  144.                     var FilterClause = new DimensionFilterClause();
  145.  
  146.                     int requestCount = 0;
  147.  
  148.                     List<Conditions> conditions = new List<Conditions>();
  149.                     conditions.Add(new Conditions() { Interest = 0, Category = 0, Gender = 0, Age = 0 });
  150.                     conditions.Add(new Conditions() { Interest = 1, Category = 0, Gender = 0, Age = 0});
  151.                     //conditions.Add(new Conditions() { Interest = 1, Category = 1, Gender = 0, Age = 0});
  152.                     //conditions.Add(new Conditions() { Interest = 1, Category = 1, Gender = 1, Age = 0});
  153.                     //conditions.Add(new Conditions() { Interest = 1, Category = 1, Gender = 0, Age = 1});
  154.                     //conditions.Add(new Conditions() { Interest = 1, Category = 1, Gender = 1, Age = 1});
  155.  
  156.                     var interestDimension = new Dimension {};
  157.  
  158.                     foreach (var site in sites)
  159.                     {
  160.                         Console.WriteLine(site.Name);
  161.  
  162.                         var reportRequest = new ReportRequest
  163.                         {
  164.                             DateRanges = new List<DateRange> { dateRange },
  165.                             Dimensions = new List<Dimension> {},
  166.                             Metrics = new List<Metric> { users, sessions, pageviews},
  167.                             DimensionFilterClauses = new List<DimensionFilterClause> {},
  168.                             ViewId = site.ViewId,
  169.                             PageSize = 10000
  170.                            
  171.                         };
  172.  
  173.                      
  174.  
  175.                         foreach(string interest in interests)
  176.                         {
  177.  
  178.                             foreach (var condition in conditions)
  179.                             {
  180.                                 reportRequest.Dimensions.Add(year);
  181.                                 reportRequest.Dimensions.Add(month);
  182.                                 reportRequest.Dimensions.Add(day);
  183.                                 reportRequest.Dimensions.Add(hour);
  184.  
  185.                                 if ( condition.Interest == 1 && condition.Category == 0 )
  186.                                 {
  187.                                     Filter.DimensionName = "ga:interest" + interest;
  188.                                     Filter.Expressions = new List<string> { "" };
  189.                                     FilterClause.Filters = new List<DimensionFilter> { Filter };
  190.  
  191.                                     reportRequest.DimensionFilterClauses.Add(FilterClause);
  192.  
  193.                                 }
  194.                                
  195.                                 if( condition.Interest == 1 && condition.Category == 1 )
  196.                                 {
  197.                                     interestDimension = new Dimension { Name = "ga:interest" + interest };
  198.                                     reportRequest.Dimensions.Add(interestDimension);
  199.  
  200.                                     if( condition.Gender == 1 )
  201.                                     {
  202.                                         reportRequest.Dimensions.Add(gender);
  203.                                     }
  204.                                     if( condition.Age == 1 )
  205.                                     {
  206.                                         reportRequest.Dimensions.Add(age);
  207.                                     }
  208.                                 }
  209.  
  210.  
  211.                                
  212.  
  213.                                 try
  214.                                 {
  215.                                    
  216.  
  217.                                     if (requestCount == 100)
  218.                                     {
  219.                                         System.Threading.Thread.Sleep(100000);
  220.                                         requestCount = 0;
  221.                                     }
  222.  
  223.                                     var getReportsRequest = new GetReportsRequest
  224.                                     {
  225.                                         ReportRequests = new List<ReportRequest> { reportRequest }
  226.                                     };
  227.  
  228.                                     requestCount += 1;
  229.  
  230.                                     var batchRequest = svc.Reports.BatchGet(getReportsRequest);
  231.  
  232.                                     var response = batchRequest.Execute();
  233.                                     string responseLine = "";
  234.  
  235.  
  236.                                     int xcount = response.Reports.First().Data.Rows.Count;
  237.                                     foreach (var x in response.Reports.First().Data.Rows)
  238.                                     {
  239.  
  240.                                         responseLine = site.Name + ";" + string.Join(";", x.Metrics.First().Values) + ";";
  241.  
  242.                                         if (condition.Interest == 0)
  243.                                         {
  244.                                             lines.Add(responseLine + string.Join(";", x.Dimensions) + ";;;;");
  245.                                         }
  246.                                         else
  247.                                         {
  248.  
  249.                                             if (condition.Category == 0)
  250.                                             {
  251.                                                 lines.Add(responseLine + string.Join(";", x.Dimensions) + ";" + interest + ";;;");
  252.                                             }
  253.                                             else
  254.                                             {
  255.                                                 responseLine += x.Dimensions.ElementAt(0) + ";" + x.Dimensions.ElementAt(1) + ";" + interest + ";" + x.Dimensions.ElementAt(2) + ";";
  256.  
  257.                                                 if (condition.Age == 0 && condition.Gender == 0)
  258.                                                 {
  259.                                                     lines.Add(responseLine + ";");
  260.                                                 }
  261.                                                 else if (condition.Age == 0 && condition.Gender == 1)
  262.                                                 {
  263.                                                     lines.Add(responseLine + x.Dimensions.ElementAt(3) + ";");
  264.                                                 }
  265.                                                 else if (condition.Age == 1 && condition.Gender == 0)
  266.                                                 {
  267.                                                     lines.Add(responseLine + ";" + x.Dimensions.ElementAt(3));
  268.                                                 }
  269.                                                 else
  270.                                                 {
  271.                                                     lines.Add(responseLine + x.Dimensions.ElementAt(3) + ";" + x.Dimensions.ElementAt(4));
  272.                                                 }
  273.  
  274.                                             }
  275.  
  276.  
  277.                                         }
  278.  
  279.                                     }
  280.  
  281.                                 }
  282.                                 catch (Exception ex)
  283.                                 {
  284.                                     //TextWriter errorFile = new StreamWriter(@"C:GaApiReaderHourGranulationError.txt", true);
  285.                                     TextWriter errorFile = new StreamWriter(@"C:HourGranulationError.txt", true);
  286.                                    
  287.                                     //TextWriter errorFile = new StreamWriter(@"C:Userskatarzyna.panasiukDesktopGoogleAnalyticsDataDownloadForReportError.txt", true);
  288.                                     errorFile.WriteLine("--------------------------------------------------------------------------------------------");
  289.                                     errorFile.WriteLine("ERROR " + site.Name + "  " + DateTime.Now);
  290.                                     errorFile.WriteLine(ex.ToString());
  291.                                     errorFile.Close();
  292.                                 }
  293.  
  294.                                 reportRequest.DimensionFilterClauses.Clear();
  295.                                 reportRequest.Dimensions.Clear();
  296.  
  297.                             }
  298.                         }
  299.  
  300.                     }
  301.  
  302.                     string lines2 = string.Join("|", lines);
  303.                     dataFile.WriteLine(lines2);
  304.                     lines.Clear();
  305.  
  306.                 }
  307.  
  308.                 dataFile.Close();
  309.  
  310.  
  311.             }
  312.             catch (Exception ex)
  313.             {
  314.  
  315.                 //TextWriter errorFile = new StreamWriter(@"C:GaApiReaderHourGranulationError.txt", true);
  316.                 TextWriter errorFile = new StreamWriter(@"C:HourGranulationError.txt", true);
  317.  
  318.                 //TextWriter errorFile = new StreamWriter(@"C:Userskatarzyna.panasiukDesktopGoogleAnalyticsDataDownloadForReportError.txt", true);
  319.                 errorFile.WriteLine("n ERROR " + DateTime.Now);
  320.                 errorFile.WriteLine(ex.ToString());
  321.                 errorFile.Close();
  322.  
  323.                 Console.WriteLine("ERROR");
  324.                 Console.WriteLine(ex.ToString());
  325.                 Console.ReadKey();
  326.             }
  327.  
  328.         }
  329.  
  330.  
  331.  
  332.         static async Task<UserCredential> GetCredential()
  333.         {
  334.             //using (var stream = new FileStream(@"C:Userskatarzyna.panasiukDesktopGoogleAnalyticsDataDownloadclient_secret.json", FileMode.Open, FileAccess.Read))
  335.             //using (var stream = new FileStream(@"C:GaApiReaderHourGranulationclient_secret.json", FileMode.Open, FileAccess.Read))
  336.             using (var stream = new FileStream(@"C:HourGranulationclient_secret.json", FileMode.Open, FileAccess.Read))
  337.  
  338.             //using (var stream = new FileStream(@"C:Userskatarzyna.panasiukDesktopGoogleAnalyticsDataDownloadForReportclient_secret.json", FileMode.Open, FileAccess.Read))
  339.             {
  340.                 const string loginEmailAddress = "[email protected]";
  341.  
  342.                 return await GoogleWebAuthorizationBroker.AuthorizeAsync
  343.                 (
  344.                     GoogleClientSecrets.Load(stream).Secrets,
  345.                     new[] { AnalyticsReportingService.Scope.Analytics },
  346.                     loginEmailAddress, CancellationToken.None
  347.                 );
  348.             }
  349.         }
  350.     }
  351. }
  352.