Permalink
Browse files

Add basic Analytics API

  • Loading branch information...
Cazzar committed Nov 8, 2018
1 parent a5e363c commit 0a05d26e1f7b6e2c108e657230cae727e09be826
@@ -231,6 +231,8 @@ public PlexWebhookAuthenticated() : base("/plex")
});
Get["/sync", true] = async (x, ct) => await Task.Factory.StartNew(() =>
{
Analytics.PostEvent("Plex", "SyncOne");

new CommandRequest_PlexSyncWatched((JMMUser) this.Context.CurrentUser).Save();
return APIStatus.OK();
});
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Shoko.Server.Extensions;

namespace Shoko.Server
{
internal static class Analytics
{
private const string AnalyticsId = "UA-128934547-1";

//#if !DEBUG
//private const string Endpoint = "https://www.google-analytics.com/debug";
//#else
private const string Endpoint = "https://www.google-analytics.com";
//#endif
/// <summary>
/// Send the event to Google.
/// </summary>
/// <param name="eventCategory">The category to store this under</param>
/// <param name="eventAction">The action of the event</param>
/// <param name="eventLabel">The label for the event</param>
/// <param name="extraData">as per: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ec </param>
/// <returns></returns>
internal static bool PostEvent(string eventCategory, string eventAction, string eventLabel = null, IDictionary<string, string> extraData = default)
{
if (ServerSettings.GA_OptOutPlzDont) return false;

using (var client = new HttpClient())
{
//
var data = new Dictionary<string, string>
{
{"an", "Shoko Server"},
{"t", "event"},
{"tid", AnalyticsId},
{"cid", ServerSettings.GA_ClientId.ToString()},
{"v", "1"},
{"av", Utils.GetApplicationVersion()},
{"ea", eventAction},
{"ec", eventCategory},
{"aip", "1"}
};
data.AddRange(extraData);

var resp = client.PostAsync($"{Endpoint}/collect", new FormUrlEncodedContent(data)).ConfigureAwait(false).GetAwaiter().GetResult();

return true;
}
}

public static void Startup()
{
PostEvent("Server", "Startup");
}
}
}
@@ -73,6 +73,7 @@ public bool IsHttpBanned
httpBanResetTimer.Stop(); //re-start implies stop
}
httpBanResetTimer.Start();
Analytics.PostEvent("AniDB", "Http Banned");
}
else
{
@@ -109,6 +110,7 @@ public bool IsUdpBanned
udpBanResetTimer.Stop(); // re-start implies stop
}
udpBanResetTimer.Start();
Analytics.PostEvent("AniDB", "Udp Banned");
}
else
{
@@ -29,7 +29,7 @@ public static void ShallowCopyTo(this object s, object d)
}
}

public static void AddRange<K, V>(this Dictionary<K, V> dict, Dictionary<K, V> otherdict)
public static void AddRange<K, V>(this IDictionary<K, V> dict, IDictionary<K, V> otherdict)
{
if (dict == null || otherdict == null) return;
otherdict.ForEach(a =>
@@ -734,12 +734,16 @@ public static void RunImport_GetImages()

public static void ValidateAllImages()
{
Analytics.PostEvent("Management", nameof(ValidateAllImages));

CommandRequest_ValidateAllImages cmd = new CommandRequest_ValidateAllImages();
cmd.Save();
}

public static void RunImport_ScanTvDB()
{
Analytics.PostEvent("Management", nameof(RunImport_ScanTvDB));

TvDBApiHelper.ScanForMatches();
}

@@ -751,16 +755,21 @@ public static void RunImport_ScanTrakt()

public static void RunImport_ScanMovieDB()
{
Analytics.PostEvent("Management", nameof(RunImport_ScanMovieDB));
MovieDBHelper.ScanForMatches();
}

public static void RunImport_UpdateTvDB(bool forced)
{
Analytics.PostEvent("Management", nameof(RunImport_UpdateTvDB));

TvDBApiHelper.UpdateAllInfo(forced);
}

public static void RunImport_UpdateAllAniDB()
{
Analytics.PostEvent("Management", nameof(RunImport_UpdateAllAniDB));

foreach (SVR_AniDB_Anime anime in RepoFactory.AniDB_Anime.GetAll())
{
CommandRequest_GetAnimeHTTP cmd = new CommandRequest_GetAnimeHTTP(anime.AnimeID, true, false);
@@ -1029,6 +1038,7 @@ public static string DeleteImportFolder(int importFolderID)

public static void UpdateAllStats()
{
Analytics.PostEvent("Management", "Update All Stats");
foreach (SVR_AnimeSeries ser in RepoFactory.AnimeSeries.GetAll())
{
ser.QueueUpdateStats();
@@ -194,6 +194,8 @@ private string GetPlexToken()
var (_, content) = RequestAsync($"https://plex.tv/api/v2/pins/{_key.Id}", HttpMethod.Get).Result;
try
{
Analytics.PostEvent("Plex", "Start Token");

_key = JsonConvert.DeserializeObject<PlexKey>(content);
}
catch
@@ -498,6 +498,8 @@ public static void ScanForMatches()
{
if (!ServerSettings.Trakt_IsEnabled) return;

Analytics.PostEvent("TraktTV", nameof(ScanForMatches));

IReadOnlyList<SVR_AnimeSeries> allSeries = RepoFactory.AnimeSeries.GetAll();

IReadOnlyList<CrossRef_AniDB_TraktV2> allCrossRefs = RepoFactory.CrossRef_AniDB_TraktV2.GetAll();
@@ -1885,6 +1885,24 @@ public static int AniDB_MaxRelationDepth
set { Set(nameof(AniDB_MaxRelationDepth), value.ToString()); }
}

public static Guid GA_ClientId
{
get
{
if (Guid.TryParse(Get(nameof(GA_ClientId)), out var val)) return val;
val = Guid.NewGuid();
Set(nameof(GA_ClientId), val.ToString());
return val;
}
set => Set(nameof(GA_ClientId), value.ToString());
}

public static bool GA_OptOutPlzDont
{
get => bool.TryParse(Get(nameof(GA_OptOutPlzDont)), out var val) && val;
set => Set(nameof(GA_OptOutPlzDont), value.ToString());
}

public static CL_ServerSettings ToContract()
{
CL_ServerSettings contract = new CL_ServerSettings
@@ -247,6 +247,7 @@
<Compile Include="..\SharedAssemblyInfo.cs">
<Link>Properties\SharedAssemblyInfo.cs</Link>
</Compile>
<Compile Include="Analytics.cs" />
<Compile Include="AniDBHelper.cs" />
<Compile Include="AniDB_API\AniDBHTTPHelper.cs" />
<Compile Include="AniDB_API\AniDBLib.cs" />
@@ -113,6 +113,10 @@ public string[] GetSupportedDatabases()

public bool StartUpServer()
{
Analytics.PostEvent("Server", "Startup");
if (Utils.IsLinux)
Analytics.PostEvent("Server", "Linux Startup");

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture);

// Check if any of the DLL are blocked, common issue with daily builds
@@ -244,6 +248,7 @@ public bool StartUpServer()

SetupNetHosts();

Analytics.PostEvent("Server", "StartupFinished");
return true;
}

@@ -1247,6 +1252,7 @@ private void ShutDown()
AniDBDispose();
StopHost();
ServerShutdown?.Invoke(this, null);
Analytics.PostEvent("Server", "Shutdown");
}

#endregion
@@ -1377,12 +1383,16 @@ public static void ScanFolder(int importFolderID)

public static void RunImport()
{
Analytics.PostEvent("Importer", "Run");

if (!workerImport.IsBusy)
workerImport.RunWorkerAsync();
}

public static void RemoveMissingFiles()
{
Analytics.PostEvent("Importer", "RemoveMissing");

if (!workerRemoveMissing.IsBusy)
workerRemoveMissing.RunWorkerAsync();
}
@@ -1623,6 +1633,8 @@ public static int OnHashProgress(string fileName, int percentComplete)
/// <returns>true if there was any commands added to the queue, flase otherwise</returns>
public bool SyncPlex()
{
Analytics.PostEvent("Plex", "SyncAll");

bool flag = false;
foreach (SVR_JMMUser user in RepoFactory.JMMUser.GetAll())
{

0 comments on commit 0a05d26

Please sign in to comment.