TransactionLog.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace UnityEngine.Purchasing
  5. {
  6. /// <summary>
  7. /// Records processed transactions on the file system
  8. /// for de duplication purposes.
  9. /// </summary>
  10. internal class TransactionLog
  11. {
  12. private readonly ILogger logger;
  13. private readonly string persistentDataPath;
  14. public TransactionLog(ILogger logger, string persistentDataPath)
  15. {
  16. this.logger = logger;
  17. if (!string.IsNullOrEmpty(persistentDataPath))
  18. {
  19. this.persistentDataPath = Path.Combine(Path.Combine(persistentDataPath, "Unity"), "UnityPurchasing");
  20. }
  21. }
  22. /// <summary>
  23. /// Removes all transactions from the log.
  24. /// </summary>
  25. public void Clear()
  26. {
  27. Directory.Delete(persistentDataPath, true);
  28. }
  29. public bool HasRecordOf(string transactionID)
  30. {
  31. if (string.IsNullOrEmpty(transactionID) || string.IsNullOrEmpty(persistentDataPath))
  32. return false;
  33. return Directory.Exists(GetRecordPath(transactionID));
  34. }
  35. public void Record(string transactionID)
  36. {
  37. // Consumables have additional de-duplication logic.
  38. if (!(string.IsNullOrEmpty(transactionID) || string.IsNullOrEmpty(persistentDataPath)))
  39. {
  40. var path = GetRecordPath(transactionID);
  41. try
  42. {
  43. Directory.CreateDirectory(path);
  44. }
  45. catch (Exception recordPathException)
  46. {
  47. // A wide variety of exceptions can occur, for all of which
  48. // nothing is the best course of action.
  49. logger.LogException(recordPathException);
  50. }
  51. }
  52. }
  53. private string GetRecordPath(string transactionID)
  54. {
  55. return Path.Combine(persistentDataPath, ComputeHash(transactionID));
  56. }
  57. /// <summary>
  58. /// Compute a 64 bit Knuth hash of a transaction ID.
  59. /// This should be more than sufficient for the few thousand maximum
  60. /// products expected in an App.
  61. /// </summary>
  62. internal static string ComputeHash(string transactionID)
  63. {
  64. UInt64 hash = 3074457345618258791ul;
  65. for (int i = 0; i < transactionID.Length; i++)
  66. {
  67. hash += transactionID[i];
  68. hash *= 3074457345618258799ul;
  69. }
  70. StringBuilder builder = new StringBuilder(16);
  71. foreach (byte b in BitConverter.GetBytes(hash))
  72. {
  73. builder.AppendFormat("{0:X2}", b);
  74. }
  75. return builder.ToString();
  76. }
  77. }
  78. }