Attribution.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Globalization;
  3. using SingularityGroup.HotReload.DTO;
  4. using UnityEditor;
  5. using UnityEditor.VSAttribution.HotReload;
  6. using UnityEngine;
  7. using UnityEngine.Analytics;
  8. namespace SingularityGroup.HotReload.Editor {
  9. internal static class Attribution {
  10. internal const string LastLoginKey = "HotReload.Attribution.LastAttributionEventAt";
  11. //Resend attribution event every 12 hours to be safe
  12. static readonly TimeSpan resendPeriod = TimeSpan.FromHours(12);
  13. //The last time the attribution event was sent.
  14. //Returns unix epoch in case it has never been sent before.
  15. static DateTime LastAttributionEventAt {
  16. get {
  17. if(EditorPrefs.HasKey(LastLoginKey)) {
  18. return DateTime.ParseExact(EditorPrefs.GetString(LastLoginKey), "o", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
  19. }
  20. return DateTimeOffset.FromUnixTimeSeconds(0).UtcDateTime;
  21. }
  22. set {
  23. EditorPrefs.SetString(LastLoginKey, value.ToUniversalTime().ToString("o"));
  24. }
  25. }
  26. const string actionName = "Login";
  27. const string partnerName = "The Naughty Cult Ltd.";
  28. public static void RegisterLogin(LoginStatusResponse response) {
  29. //Licensing might not be initialized yet.
  30. //The hwId should be set eventually.
  31. if(response?.hardwareId == null) {
  32. return;
  33. }
  34. //Only forward attribution if this is an asset store build.
  35. //We will still distribute this package outside of the asset store (i.e via our website).
  36. if (!PackageConst.IsAssetStoreBuild) {
  37. return;
  38. }
  39. var now = DateTime.UtcNow;
  40. //If we sent an attribution event in the last 12 hours we should already be good.
  41. if (now - LastAttributionEventAt < resendPeriod) {
  42. return;
  43. }
  44. var result = VSAttribution.SendAttributionEvent(actionName, partnerName, response.hardwareId);
  45. //Retry on transient errors
  46. if (result == AnalyticsResult.NotInitialized) {
  47. return;
  48. }
  49. LastAttributionEventAt = now;
  50. }
  51. }
  52. }