1 // ----------------------------------------------------------------------------------------------
3 // / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
4 // / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
5 // / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
6 // /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
7 // ----------------------------------------------------------------------------------------------
9 // Copyright 2015-2024 Ćukasz "JustArchi" Domeradzki
10 // Contact: JustArchi@JustArchi.net
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
16 // http://www.apache.org/licenses/LICENSE-2.0
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.
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() {
46 GC
.SuppressFinalize(this);
49 protected virtual void Dispose(bool disposing
) {
51 FileSemaphore
.Dispose();
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.
62 /// <example>protected override Task Save() => Save(this);</example>
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
) {
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
) {
83 serializableFile
.SavingScheduled
= true;
86 await serializableFile
.FileSemaphore
.WaitAsync().ConfigureAwait(false);
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
) {
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
) {
114 await File
.WriteAllTextAsync(newFilePath
, json
).ConfigureAwait(false);
116 File
.Replace(newFilePath
, serializableFile
.FilePath
, null);
118 await File
.WriteAllTextAsync(newFilePath
, json
).ConfigureAwait(false);
120 File
.Move(newFilePath
, serializableFile
.FilePath
);
122 } catch (Exception e
) {
123 ASF
.ArchiLogger
.LogGenericException(e
);
125 serializableFile
.FileSemaphore
.Release();
129 internal async Task
MakeReadOnly() {
134 await FileSemaphore
.WaitAsync().ConfigureAwait(false);
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);
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
) {
164 await File
.WriteAllTextAsync(newFilePath
, json
).ConfigureAwait(false);
166 File
.Replace(newFilePath
, filePath
, null);
168 await File
.WriteAllTextAsync(newFilePath
, json
).ConfigureAwait(false);
170 File
.Move(newFilePath
, filePath
);
174 } catch (Exception e
) {
175 ASF
.ArchiLogger
.LogGenericException(e
);
179 GlobalFileSemaphore
.Release();