using System;
using System.IO;
using Uniject;
namespace UnityEngine.Purchasing
{
///
/// File Reference that can be created with a filename.
/// The path to the file is constructed via `Application.persistentDataPath` and `Application.cloudProjectId`.
/// Operations such as Save, Load, and Delete are available.
/// One use case for this class is to create a file reference to a locally cached store catalog.
///
///
internal class FileReference
{
private readonly string m_FilePath;
private readonly ILogger m_Logger;
///
/// Creates the instance of FileReference. Method allows dependency injection to ease testing
/// by using Interfaces for the logger and util.
///
/// The instance.
/// Filename.
/// Logger.
/// Util.
internal static FileReference CreateInstance(string filename, ILogger logger, IUtil util)
{
try
{
var persistentDataPath = Path.Combine(util.persistentDataPath, "Unity");
var uniquePathSuffix = Path.Combine(util.cloudProjectId, "IAP");
var cachePath = Path.Combine(persistentDataPath, uniquePathSuffix);
Directory.CreateDirectory(cachePath);
var filePath = Path.Combine(cachePath, filename);
return new FileReference(filePath, logger);
}
catch
{
// Not all platforms support writing to disk. E.g. tvOS throws exception: "System.UnauthorizedAccessException: Access to the path "/Unity" is denied."
return null;
}
}
///
/// Creates an instance of the Persist class
/// Please use use the `CreateInstance` method unless the filepath
/// cannot be created through UnityEngine.Application
///
/// File path.
/// Logger.
internal FileReference(string filePath, ILogger logger)
{
m_FilePath = filePath;
m_Logger = logger;
}
///
/// Save the specified payload on file.
///
/// Payload.
internal void Save(string payload)
{
try
{
File.WriteAllText(m_FilePath, payload);
}
catch (Exception e)
{
m_Logger.LogError("Failed persisting content", e);
}
}
///
/// Load the contents from the file as a string.
///
/// String from file
internal string Load()
{
try
{
return File.ReadAllText(m_FilePath);
}
catch
{
return null;
}
}
///
/// Deletes the file
///
internal void Delete()
{
try
{
File.Delete(m_FilePath);
}
catch (Exception e)
{
m_Logger.LogWarning("Failed deleting cached content", e);
}
}
}
}