Skip to content

Commit

Permalink
Update autoUpdate process
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmfinol committed Dec 17, 2018
1 parent dc768d4 commit 5305b34
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 73 deletions.
77 changes: 59 additions & 18 deletions Assets/Scripts/CGS/CardGameManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,17 @@ namespace CGS
{
public class CardGameManager : MonoBehaviour
{
public const bool VerboseLogMessenger = false;
public const bool IsMessengerDebugLogVerbose = false;
public const string GameId = "GameId";
public const string PlayerPrefDefaultGame = "DefaultGame";
public const string SelectorPrefabName = "Game Selection Menu";
public const string MessengerPrefabName = "Popup";
public const string SpinnerPrefabName = "Spinner";
public const string InvalidGameSelectionMessage = "Could not select the card game because it is not recognized! Try selecting a different card game?";
public const string BranchLinkErrorMessage = "Link Broken! Unable to select card game!";
public const string BranchLinkErrorMessage = "Link Broken! Unable to select the desired card game! ";
public const string GameDownLoadErrorMessage = "Error downloading game!: ";
public const string GameLoadErrorMessage = "Error loading game!: ";
public const string GameLoadErrorPrompt = "Error loading game! The game may be corrupted. Delete (note that any decks would also be deleted)?";
public const string GameDeleteErrorMessage = "Error deleting game!: ";
public const string CardsLoadedMessage = "{0} cards loaded!";
public const string CardsLoadingMessage = "{0} cards loading...";
Expand Down Expand Up @@ -61,7 +63,7 @@ public static CardGameManager Instance
public SortedDictionary<string, CardGame> AllCardGames { get; } = new SortedDictionary<string, CardGame>();
public List<UnityAction> OnSceneActions { get; } = new List<UnityAction>();

public SortedList<string, string> GamesListing => new SortedList<string, string>(AllCardGames.ToDictionary( game => game.Key, game => game.Value.Name));
public SortedList<string, string> GamesListing => new SortedList<string, string>(AllCardGames.ToDictionary(game => game.Key, game => game.Value.Name));

public LobbyDiscovery Discovery => _discovery ?? (_discovery = gameObject.GetOrAddComponent<LobbyDiscovery>());
private LobbyDiscovery _discovery;
Expand Down Expand Up @@ -191,13 +193,13 @@ private void LookupCardGames()

void ShowLogToUser(string logString, string stackTrace, LogType type)
{
if (VerboseLogMessenger || !LogType.Log.Equals(type))
if (IsMessengerDebugLogVerbose || !LogType.Log.Equals(type))
Messenger.Show(logString);
}

void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
DoGameSceneActions();
SetupGameScene();
}

void OnSceneUnloaded(Scene scene)
Expand All @@ -209,7 +211,8 @@ public void BranchCallbackWithParams(Dictionary<string, object> parameters, stri
{
if (error != null)
{
Debug.LogError(error);
Debug.LogError(BranchLinkErrorMessage + error);
Messenger.Show(BranchLinkErrorMessage);
return;
}

Expand All @@ -226,21 +229,29 @@ public void BranchCallbackWithParams(Dictionary<string, object> parameters, stri
public void ResetToPreferredCardGame()
{
CardGame currentGame;
Current = AllCardGames.TryGetValue(PlayerPrefs.GetString(PlayerPrefDefaultGame), out currentGame)
? currentGame : AllCardGames.First().Value;
Current = AllCardGames.TryGetValue(PlayerPrefs.GetString(PlayerPrefDefaultGame), out currentGame) && string.IsNullOrEmpty(currentGame.Error)
? currentGame : (AllCardGames.FirstOrDefault().Value ?? CardGame.Invalid);
}

public IEnumerator DownloadCardGame(string gameUrl)
{
Spinner.Show();
CardGame newGame = new CardGame(this, CardGame.DefaultName, gameUrl) { AutoUpdate = true };
Current = newGame;

CardGame newGame = new CardGame(this, CardGame.DefaultName, gameUrl);
yield return newGame.Download();
newGame.Load();

if (string.IsNullOrEmpty(newGame.Error))
{
AllCardGames[newGame.Id] = newGame;
SelectCardGame(newGame.Id);
}
else
Debug.LogError(GameLoadErrorMessage + newGame.Error);
SelectCardGame(newGame.Id);
{
Debug.LogError(GameDownLoadErrorMessage + Current.Error);
Messenger.Show(GameDownLoadErrorMessage + Current.Error);
}

Spinner.Hide();
}

Expand Down Expand Up @@ -292,22 +303,26 @@ public void SelectCardGame(string gameId)
}

Current = AllCardGames[gameId];
DoGameSceneActions();
SetupGameScene();
}

public void DoGameSceneActions()
public void SetupGameScene()
{
if (!Current.HasLoaded)
{
Current.Load();
if (Current.IsDownloading)
return;
}

if (!string.IsNullOrEmpty(Current.Error))
{
Debug.LogError(GameLoadErrorMessage + Current.Error);
ResetToPreferredCardGame();
Selector.Show();
Messenger.Ask(GameLoadErrorPrompt, IgnoreErroredGame, DeleteGame);
return;
}

// Now is the safest time to set this game as the default preferred game for the player
PlayerPrefs.SetString(PlayerPrefDefaultGame, Current.Id);

if (BackgroundImage != null)
Expand All @@ -321,20 +336,46 @@ public void DoGameSceneActions()
action();
}

public IEnumerator UpdateCardGame()
{
Spinner.Show();

yield return Current.Download();

Spinner.Hide();

// Notify about the failed update, but otherwise ignore errors
if (!string.IsNullOrEmpty(Current.Error))
{
Debug.LogError(GameDownLoadErrorMessage + Current.Error);
Messenger.Show(GameDownLoadErrorMessage + Current.Error);
Current.ClearError();
}

Current.Load();
SetupGameScene();
}

public IEnumerator LoadCards()
{
yield return Current.LoadAllCards();
if (!string.IsNullOrEmpty(Current.Error))
Debug.LogError(GameLoadErrorMessage + Current.Error);
}

public void IgnoreErroredGame()
{
ResetToPreferredCardGame();
Selector.Show();
}

public void DeleteGame()
{
try
{
Directory.Delete(Current.GameDirectoryPath, true);
AllCardGames.Remove(Current.Name);
SelectCardGame(AllCardGames.Keys.First());
AllCardGames.Remove(Current.Id);
ResetToPreferredCardGame();
Selector.Show();
}
catch (Exception ex)
Expand Down
4 changes: 2 additions & 2 deletions Assets/Scripts/CGS/Menus/CardSearchMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ public GameObject CreateEnumPropertyFilterPanel(PropertyDef property)
foreach (KeyValuePair<string, string> enumValue in enumDef.Values)
{
int lookupKey;
if (!enumDef.Lookup.TryGetValue(enumValue.Key, out lookupKey))
if (!enumDef.Lookups.TryGetValue(enumValue.Key, out lookupKey))
lookupKey = enumDef.CreateLookup(enumValue.Key);
toggle = Instantiate(config.toggle.gameObject, config.toggleGroupContainer).GetOrAddComponent<Toggle>();
toggle.isOn = (storedFilter & lookupKey) != 0;
Expand All @@ -395,7 +395,7 @@ public GameObject CreateEnumPropertyFilterPanel(PropertyDef property)
if (!string.IsNullOrEmpty(property.Empty))
{
int lookupKey;
if (!enumDef.Lookup.TryGetValue(property.Empty, out lookupKey))
if (!enumDef.Lookups.TryGetValue(property.Empty, out lookupKey))
lookupKey = enumDef.CreateLookup(property.Empty);
toggle = Instantiate(config.toggle.gameObject, config.toggleGroupContainer).GetOrAddComponent<Toggle>();
toggle.isOn = (storedFilter & lookupKey) != 0;
Expand Down
78 changes: 43 additions & 35 deletions Assets/Scripts/CardGameDef/CardGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public class CardGame
public IReadOnlyDictionary<string, Card> Cards => LoadedCards;
public IReadOnlyDictionary<string, Set> Sets => LoadedSets;

// Note: this property can throw an exception
public int DaysSinceUpdate => (int)DateTime.Today.Subtract(File.GetLastWriteTime(GameFilePath).Date).TotalDays;

// *Game:Id* = *Game:Name*@<base64(*Game:AutoUpdateUrl*)>
// Since urls must be unique, this id will also be unique and human-recognizable
Expand Down Expand Up @@ -85,7 +87,7 @@ public class CardGame
public bool AllSetsUrlZipped { get; set; }

[JsonProperty]
public bool AutoUpdate { get; set; }
public int AutoUpdate { get; set; } = 30;

[JsonProperty]
public string AutoUpdateUrl { get; set; }
Expand Down Expand Up @@ -255,6 +257,11 @@ public CardGame(UnityEngine.MonoBehaviour coroutineRunner, string name = Default
Error = string.Empty;
}

public bool IsEnumProperty(string propertyName)
{
return Enums.Where(def => def.Property.Equals(propertyName)).ToList().Count > 0;
}

public void ReadProperties()
{
try
Expand Down Expand Up @@ -287,16 +294,13 @@ public IEnumerator Download()

// First get the *Game:Name*.json file and read it if we need to determine where to pull the rest of the data from
yield return UnityExtensionMethods.SaveUrlToFile(AutoUpdateUrl, GameFilePath);
ReadProperties();
if (!HasReadProperties)
{
ReadProperties();
if (!HasReadProperties)
{
// ReadProperties() should have already populated the Error
IsDownloading = false;
HasDownloaded = false;
yield break;
}
// ReadProperties() should have already populated the Error
IsDownloading = false;
HasDownloaded = false;
yield break;
}

for (int page = AllCardsUrlPageCountStartIndex; page < AllCardsUrlPageCountStartIndex + AllCardsUrlPageCount; page++)
Expand Down Expand Up @@ -326,8 +330,11 @@ public IEnumerator Download()
if (!string.IsNullOrEmpty(AllSetsUrl))
yield return UnityExtensionMethods.SaveUrlToFile(AllSetsUrl, setsFilePath);

yield return UnityExtensionMethods.SaveUrlToFile(BackgroundImageUrl, BackgroundImageFilePath);
yield return UnityExtensionMethods.SaveUrlToFile(CardBackImageUrl, CardBackImageFilePath);
if (!string.IsNullOrEmpty(BackgroundImageUrl))
yield return UnityExtensionMethods.SaveUrlToFile(BackgroundImageUrl, BackgroundImageFilePath);

if (!string.IsNullOrEmpty(CardBackImageUrl))
yield return UnityExtensionMethods.SaveUrlToFile(CardBackImageUrl, CardBackImageFilePath);

foreach (GameBoardUrl boardUrl in GameBoardUrls)
yield return UnityExtensionMethods.SaveUrlToFile(boardUrl.Url, GameBoardsFilePath + "/" + boardUrl.Id + "." + GameBoardFileType);
Expand All @@ -337,32 +344,37 @@ public IEnumerator Download()

IsDownloading = false;
HasDownloaded = true;
if (!HasLoaded)
Load();
HasLoaded = false;
}

public void Load()
{
// We should have already read the *Game:Name*.json, but we need to be sure
if (!HasReadProperties)
try
{
ReadProperties();
// We should have already read the *Game:Name*.json, but we need to be sure
if (!HasReadProperties)
{
// ReadProperties() should have already populated the Error
HasLoaded = false;
ReadProperties();
if (!HasReadProperties)
{
// ReadProperties() should have already populated the Error
HasLoaded = false;
return;
}
}

// Don't waste time loading if we need to update first
if (AutoUpdate >= 0 && DaysSinceUpdate >= AutoUpdate && CoroutineRunner != null)
{
CoroutineRunner.StartCoroutine(CGS.CardGameManager.Instance.UpdateCardGame());
return;
}
}

// These enum lookups need to be set up before we load cards and sets
foreach (EnumDef enumDef in Enums)
foreach (string key in enumDef.Values.Keys)
enumDef.CreateLookup(key);
// These enum lookups need to be initialized before we load cards and sets
foreach (EnumDef enumDef in Enums)
enumDef.InitializeLookups();

// The main load action is to load cards and sets, but we should also load the background and cardback images now
try
{
// The main load action is to load cards and sets, but we should also load the background and cardback images now
if (CoroutineRunner != null)
CoroutineRunner.StartCoroutine(CGS.CardGameManager.Instance.LoadCards());
LoadSets();
Expand All @@ -377,15 +389,6 @@ public void Load()
Error += e.Message + e.StackTrace + Environment.NewLine;
HasLoaded = false;
}

// Kick off auto-update in the background, even though it won't load until next time the app restarts
if (AutoUpdate && !HasDownloaded && CoroutineRunner != null)
CoroutineRunner.StartCoroutine(Download());
}

public bool IsEnumProperty(string propertyName)
{
return Enums.Where(def => def.Property.Equals(propertyName)).ToList().Count > 0;
}

public IEnumerator LoadAllCards()
Expand Down Expand Up @@ -635,5 +638,10 @@ public IEnumerable<Card> FilterCards(CardSearchFilters filters)
yield return card;
}
}

public void ClearError()
{
Error = string.Empty;
}
}
}
21 changes: 14 additions & 7 deletions Assets/Scripts/CardGameDef/EnumDef.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,31 @@ public class EnumDef
[JsonProperty]
public Dictionary<string, string> Values { get; private set; }

public Dictionary<string, int> Lookup { get; } = new Dictionary<string, int>();
public Dictionary<string, int> Lookups { get; } = new Dictionary<string, int>();

public static bool TryParseInt(string number, out int intValue)
{
bool isHex = number.StartsWith(Hex);
return int.TryParse(isHex ? number.Substring(Hex.Length) : number, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, CultureInfo.InvariantCulture, out intValue);
}

public void InitializeLookups()
{
Lookups.Clear();
foreach (string key in Values.Keys)
CreateLookup(key);
}

public int CreateLookup(string key)
{
if (string.IsNullOrEmpty(key) || Lookup.ContainsKey(key))
if (string.IsNullOrEmpty(key) || Lookups.ContainsKey(key))
return 0;

int intValue;
if (!key.StartsWith(Hex) || !TryParseInt(key, out intValue))
intValue = 1 << Lookup.Count;
intValue = 1 << Lookups.Count;

Lookup[key] = intValue;
Lookups[key] = intValue;
return intValue;
}

Expand All @@ -49,7 +56,7 @@ public string GetStringFromLookupFlags(int flags)
foreach (KeyValuePair<string, string> enumValue in Values)
{
int lookupValue;
if (!Lookup.TryGetValue(enumValue.Key, out lookupValue) || (lookupValue & flags) == 0)
if (!Lookups.TryGetValue(enumValue.Key, out lookupValue) || (lookupValue & flags) == 0)
continue;
if (!string.IsNullOrEmpty(stringValue))
stringValue += Delimiter;
Expand All @@ -70,7 +77,7 @@ public string GetStringFromPropertyValue(string propertyValue)
stringValue += Delimiter;
int lookupFlags;
string mappedValue;
if (Lookup.TryGetValue(splitValue, out lookupFlags) || TryParseInt(splitValue, out lookupFlags))
if (Lookups.TryGetValue(splitValue, out lookupFlags) || TryParseInt(splitValue, out lookupFlags))
stringValue += GetStringFromLookupFlags(lookupFlags);
else
stringValue += Values.TryGetValue(splitValue, out mappedValue) ? mappedValue : splitValue;
Expand All @@ -87,7 +94,7 @@ public int GetEnumFromPropertyValue(string propertyValue)
foreach (string stringValue in propertyValue.Split(new[] { Delimiter }, StringSplitOptions.RemoveEmptyEntries))
{
int intValue;
if (Lookup.TryGetValue(stringValue, out intValue) || TryParseInt(stringValue, out intValue))
if (Lookups.TryGetValue(stringValue, out intValue) || TryParseInt(stringValue, out intValue))
enumValue |= intValue;
}
return enumValue;
Expand Down
Loading

0 comments on commit 5305b34

Please sign in to comment.