/// <summary> /// Unlike <see cref="ProtoBinaryManager.ProtoFromFile{PROTO}(byte[], string, string)">, it has some recovery options when the /// file is hacked or corrupted. (but the file must exist, otherwise it will throw `FileNotFoundException` as usual) /// </summary> private PROTO FromFile(string loadFolderAbsolute, string fileNameWithExtension) { string path = $"{loadFolderAbsolute}/{fileNameWithExtension}"; try { return(ProtoBinaryManager.ProtoFromFile <PROTO>(key, loadFolderAbsolute, fileNameWithExtension)); } catch (Exception ex) when(ex is CryptographicException || ex is ArgumentException) { //Migration only available when found the file but not readable. #if UNITY_EDITOR Debug.LogWarning(ex); Debug.LogWarning("Possible old save data or corrupt save data found, trying to migrate."); #endif try { var migrated = Migration(path); #if UNITY_EDITOR Debug.Log("Migration complete"); #endif return(Validation(migrated)); } catch (Exception ex2) when(ex2 is CryptographicException || ex2 is ArgumentException) { #if UNITY_EDITOR Debug.LogWarning(ex2); Debug.LogWarning("Could not migrate. Creating a new save file."); #endif return(new PROTO()); //you get an empty save if migration also throws crypto } } }
/// <summary> /// The default implementation picks up 16 bytes IV from the front of cipher text, /// use it together with a key derived from <see cref="EncryptionPassword"> and <see cref="EncryptionSalt"> to AES decode the protobuf stream. /// /// You could override to something more sophisticated if you want. /// </summary> public virtual PROTO FromStream(Stream stream) { var loadedData = ProtoBinaryManager.ProtoFromStream <PROTO>(stream, key); var validated = Validation(loadedData); return(validated); }
/// <summary> /// The default implementation applies basic AES encryption with a key derived from <see cref="EncryptionPassword"> and <see cref="EncryptionSalt">, /// with generated IV pasted in front of cipher text, before writing to the disk. /// /// You could override to something more sophisticated if you want. /// </summary> public virtual MemoryStream ToStream(PROTO save) => ProtoBinaryManager.ProtoToStream(save, key);
private void SaveAs(PROTO save, string fileNameWithExtension) => ProtoBinaryManager.StreamToFile(ToStream(save), SaveFolderAbsolute, fileNameWithExtension);
/// <summary> /// Useful in unit testing. You could have a sample of old version saves from player and test your compatibility with them. /// Or just a way to setup the test for specific scenario you want to check out. /// /// Do not include `Assets` or leading slash in the <paramref name="path">. /// File name don't need extension, it uses <see cref="SaveFileExtension">. /// </summary> public PROTO LoadFromProject(string path, string name) => ProtoBinaryManager.ProtoFromProject <PROTO>(key, path, $"{name}{SaveFileExtension}");