Automatic translations update
[ArchiSteamFarm.git] / ArchiSteamFarm / Helpers / SerializableFile.cs
blobc180c4c1848fd3d772134e665cd85ce70aef2e6b
1 // ----------------------------------------------------------------------------------------------
2 // _ _ _ ____ _ _____
3 // / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
4 // / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
5 // / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
6 // /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
7 // ----------------------------------------------------------------------------------------------
8 // |
9 // Copyright 2015-2024 Ɓukasz "JustArchi" Domeradzki
10 // Contact: JustArchi@JustArchi.net
11 // |
12 // Licensed under the Apache License, Version 2.0 (the "License");
13 // you may not use this file except in compliance with the License.
14 // You may obtain a copy of the License at
15 // |
16 // http://www.apache.org/licenses/LICENSE-2.0
17 // |
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the License is distributed on an "AS IS" BASIS,
20 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 // See the License for the specific language governing permissions and
22 // limitations under the License.
24 using System;
25 using System.IO;
26 using System.Threading;
27 using System.Threading.Tasks;
28 using ArchiSteamFarm.Core;
29 using ArchiSteamFarm.Helpers.Json;
30 using JetBrains.Annotations;
32 namespace ArchiSteamFarm.Helpers;
34 public abstract class SerializableFile : IDisposable {
35 private static readonly SemaphoreSlim GlobalFileSemaphore = new(1, 1);
37 private readonly SemaphoreSlim FileSemaphore = new(1, 1);
39 protected string? FilePath { get; set; }
41 private bool ReadOnly;
42 private bool SavingScheduled;
44 public void Dispose() {
45 Dispose(true);
46 GC.SuppressFinalize(this);
49 protected virtual void Dispose(bool disposing) {
50 if (disposing) {
51 FileSemaphore.Dispose();
55 /// <summary>
56 /// Implementing this method in your target class is crucial for providing supported functionality.
57 /// In order to do so, it's enough to call static <see cref="Save" /> function from the parent class, providing <code>this</code> as input parameter.
58 /// Afterwards, simply call your <see cref="Save" /> function whenever you need to save changes.
59 /// This approach will allow JSON serializer used in the <see cref="SerializableFile" /> to properly discover all of the properties used in your class.
60 /// Unfortunately, due to STJ's limitations, called by some "security", it's not possible for base class to resolve your properties automatically otherwise.
61 /// </summary>
62 /// <example>protected override Task Save() => Save(this);</example>
63 [UsedImplicitly]
64 protected abstract Task Save();
66 protected static async Task Save<T>(T serializableFile) where T : SerializableFile {
67 ArgumentNullException.ThrowIfNull(serializableFile);
69 if (string.IsNullOrEmpty(serializableFile.FilePath)) {
70 throw new InvalidOperationException(nameof(serializableFile.FilePath));
73 if (serializableFile.ReadOnly) {
74 return;
77 // ReSharper disable once SuspiciousLockOverSynchronizationPrimitive - this is not a mistake, we need extra synchronization, and we can re-use the semaphore object for that
78 lock (serializableFile.FileSemaphore) {
79 if (serializableFile.SavingScheduled) {
80 return;
83 serializableFile.SavingScheduled = true;
86 await serializableFile.FileSemaphore.WaitAsync().ConfigureAwait(false);
88 try {
89 // ReSharper disable once SuspiciousLockOverSynchronizationPrimitive - this is not a mistake, we need extra synchronization, and we can re-use the semaphore object for that
90 lock (serializableFile.FileSemaphore) {
91 serializableFile.SavingScheduled = false;
94 if (serializableFile.ReadOnly) {
95 return;
98 string json = serializableFile.ToJsonText(Debugging.IsUserDebugging);
100 if (string.IsNullOrEmpty(json)) {
101 throw new InvalidOperationException(nameof(json));
104 // We always want to write entire content to temporary file first, in order to never load corrupted data, also when target file doesn't exist
105 string newFilePath = $"{serializableFile.FilePath}.new";
107 if (File.Exists(serializableFile.FilePath)) {
108 string currentJson = await File.ReadAllTextAsync(serializableFile.FilePath).ConfigureAwait(false);
110 if (json == currentJson) {
111 return;
114 await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
116 File.Replace(newFilePath, serializableFile.FilePath, null);
117 } else {
118 await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
120 File.Move(newFilePath, serializableFile.FilePath);
122 } catch (Exception e) {
123 ASF.ArchiLogger.LogGenericException(e);
124 } finally {
125 serializableFile.FileSemaphore.Release();
129 internal async Task MakeReadOnly() {
130 if (ReadOnly) {
131 return;
134 await FileSemaphore.WaitAsync().ConfigureAwait(false);
136 try {
137 if (ReadOnly) {
138 return;
141 ReadOnly = true;
142 } finally {
143 FileSemaphore.Release();
147 internal static async Task<bool> Write(string filePath, string json) {
148 ArgumentException.ThrowIfNullOrEmpty(filePath);
149 ArgumentException.ThrowIfNullOrEmpty(json);
151 string newFilePath = $"{filePath}.new";
153 await GlobalFileSemaphore.WaitAsync().ConfigureAwait(false);
155 try {
156 // We always want to write entire content to temporary file first, in order to never load corrupted data, also when target file doesn't exist
157 if (File.Exists(filePath)) {
158 string currentJson = await File.ReadAllTextAsync(filePath).ConfigureAwait(false);
160 if (json == currentJson) {
161 return true;
164 await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
166 File.Replace(newFilePath, filePath, null);
167 } else {
168 await File.WriteAllTextAsync(newFilePath, json).ConfigureAwait(false);
170 File.Move(newFilePath, filePath);
173 return true;
174 } catch (Exception e) {
175 ASF.ArchiLogger.LogGenericException(e);
177 return false;
178 } finally {
179 GlobalFileSemaphore.Release();