-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathStateSaver.java
More file actions
368 lines (329 loc) · 13 KB
/
StateSaver.java
File metadata and controls
368 lines (329 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
* Copyright 2017 Mauricio Colli <[email protected]>
* StateSaver.java is part of NewPipe
*
* License: GPL-3.0+
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.schabi.newpipe.util;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.os.BundleCompat;
import org.schabi.newpipe.BuildConfig;
import org.schabi.newpipe.MainActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
/**
* A way to save state to disk or in a in-memory map
* if it's just changing configurations (i.e. rotating the phone).
*/
public final class StateSaver {
public static final String KEY_SAVED_STATE = "key_saved_state";
private static final ConcurrentHashMap<String, Queue<Object>> STATE_OBJECTS_HOLDER =
new ConcurrentHashMap<>();
private static final String TAG = "StateSaver";
private static final String CACHE_DIR_NAME = "state_cache";
private static String cacheDirPath;
private StateSaver() {
//no instance
}
/**
* Initialize the StateSaver, usually you want to call this in the Application class.
*
* @param context used to get the available cache dir
*/
public static void init(final Context context) {
// Use internal cache directory to prevent other apps from accessing/modifying the state
cacheDirPath = context.getCacheDir().getAbsolutePath();
}
/**
* @param outState
* @param writeRead
* @return the saved state
* @see #tryToRestore(SavedState, WriteRead)
*/
public static SavedState tryToRestore(final Bundle outState, final WriteRead writeRead) {
if (outState == null || writeRead == null) {
return null;
}
final SavedState savedState = BundleCompat.getParcelable(
outState, KEY_SAVED_STATE, SavedState.class);
if (savedState == null) {
return null;
}
return tryToRestore(savedState, writeRead);
}
/**
* Try to restore the state from memory and disk,
* using the {@link StateSaver.WriteRead#readFrom(Queue)} from the writeRead.
*
* @param savedState
* @param writeRead
* @return the saved state
*/
@Nullable
private static SavedState tryToRestore(@NonNull final SavedState savedState,
@NonNull final WriteRead writeRead) {
if (MainActivity.DEBUG) {
Log.d(TAG, "tryToRestore() called with: savedState = [" + savedState + "], "
+ "writeRead = [" + writeRead + "]");
}
try {
Queue<Object> savedObjects =
STATE_OBJECTS_HOLDER.remove(savedState.getPrefixFileSaved());
if (savedObjects != null) {
writeRead.readFrom(savedObjects);
if (MainActivity.DEBUG) {
Log.d(TAG, "tryToSave: reading objects from holder > " + savedObjects
+ ", stateObjectsHolder > " + STATE_OBJECTS_HOLDER);
}
return savedState;
}
final File file = new File(savedState.getPathFileSaved());
if (!file.exists()) {
if (MainActivity.DEBUG) {
Log.d(TAG, "Cache file doesn't exist: " + file.getAbsolutePath());
}
return null;
}
try (FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream inputStream = new ValidatingObjectInputStream(fileInputStream)) {
//noinspection unchecked
savedObjects = (Queue<Object>) inputStream.readObject();
}
if (savedObjects != null) {
writeRead.readFrom(savedObjects);
}
return savedState;
} catch (final Exception e) {
Log.e(TAG, "Failed to restore state", e);
}
return null;
}
/**
* @param isChangingConfig
* @param savedState
* @param outState
* @param writeRead
* @return the saved state or {@code null}
* @see #tryToSave(boolean, String, String, WriteRead)
*/
@Nullable
public static SavedState tryToSave(final boolean isChangingConfig,
@Nullable final SavedState savedState, final Bundle outState,
final WriteRead writeRead) {
@NonNull final String currentSavedPrefix;
if (savedState == null || TextUtils.isEmpty(savedState.getPrefixFileSaved())) {
// Generate unique prefix
currentSavedPrefix = System.nanoTime() - writeRead.hashCode() + "";
} else {
// Reuse prefix
currentSavedPrefix = savedState.getPrefixFileSaved();
}
final SavedState newSavedState = tryToSave(isChangingConfig, currentSavedPrefix,
writeRead.generateSuffix(), writeRead);
if (newSavedState != null) {
outState.putParcelable(StateSaver.KEY_SAVED_STATE, newSavedState);
return newSavedState;
}
return null;
}
/**
* If it's not changing configuration (i.e. rotating screen),
* try to write the state from {@link StateSaver.WriteRead#writeTo(Queue)}
* to the file with the name of prefixFileName + suffixFileName,
* in a cache folder got from the {@link #init(Context)}.
* <p>
* It checks if the file already exists and if it does, just return the path,
* so a good way to save is:
* </p>
* <ul>
* <li>A fixed prefix for the file</li>
* <li>A changing suffix</li>
* </ul>
*
* @param isChangingConfig
* @param prefixFileName
* @param suffixFileName
* @param writeRead
* @return the saved state or {@code null}
*/
@Nullable
private static SavedState tryToSave(final boolean isChangingConfig, final String prefixFileName,
final String suffixFileName, final WriteRead writeRead) {
if (MainActivity.DEBUG) {
Log.d(TAG, "tryToSave() called with: "
+ "isChangingConfig = [" + isChangingConfig + "], "
+ "prefixFileName = [" + prefixFileName + "], "
+ "suffixFileName = [" + suffixFileName + "], "
+ "writeRead = [" + writeRead + "]");
}
final LinkedList<Object> savedObjects = new LinkedList<>();
writeRead.writeTo(savedObjects);
if (isChangingConfig) {
if (savedObjects.size() > 0) {
STATE_OBJECTS_HOLDER.put(prefixFileName, savedObjects);
return new SavedState(prefixFileName, "");
} else {
if (MainActivity.DEBUG) {
Log.d(TAG, "Nothing to save");
}
return null;
}
}
try {
File cacheDir = new File(cacheDirPath);
if (!cacheDir.exists()) {
throw new RuntimeException("Cache dir does not exist > " + cacheDirPath);
}
cacheDir = new File(cacheDir, CACHE_DIR_NAME);
if (!cacheDir.exists()) {
if (!cacheDir.mkdir()) {
if (BuildConfig.DEBUG) {
Log.e(TAG,
"Failed to create cache directory " + cacheDir.getAbsolutePath());
}
return null;
}
}
final File file = new File(cacheDir, prefixFileName
+ (TextUtils.isEmpty(suffixFileName) ? ".cache" : suffixFileName));
if (file.exists() && file.length() > 0) {
// If the file already exists, just return it
return new SavedState(prefixFileName, file.getAbsolutePath());
} else {
// Delete any file that contains the prefix
final File[] files = cacheDir.listFiles((dir, name) ->
name.contains(prefixFileName));
for (final File fileToDelete : files) {
fileToDelete.delete();
}
}
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream)) {
outputStream.writeObject(savedObjects);
}
return new SavedState(prefixFileName, file.getAbsolutePath());
} catch (final Exception e) {
Log.e(TAG, "Failed to save state", e);
}
return null;
}
/**
* Delete the cache file contained in the savedState.
* Also remove any possible-existing value in the memory-cache.
*
* @param savedState the saved state to delete
*/
public static void onDestroy(final SavedState savedState) {
if (MainActivity.DEBUG) {
Log.d(TAG, "onDestroy() called with: savedState = [" + savedState + "]");
}
if (savedState != null && !savedState.getPathFileSaved().isEmpty()) {
STATE_OBJECTS_HOLDER.remove(savedState.getPrefixFileSaved());
try {
//noinspection ResultOfMethodCallIgnored
new File(savedState.getPathFileSaved()).delete();
} catch (final Exception ignored) {
}
}
}
/**
* Clear all the files in cache (in memory and disk).
*/
public static void clearStateFiles() {
if (MainActivity.DEBUG) {
Log.d(TAG, "clearStateFiles() called");
}
STATE_OBJECTS_HOLDER.clear();
File cacheDir = new File(cacheDirPath);
if (!cacheDir.exists()) {
return;
}
cacheDir = new File(cacheDir, CACHE_DIR_NAME);
if (cacheDir.exists()) {
final File[] list = cacheDir.listFiles();
if (list != null) {
for (final File file : list) {
file.delete();
}
}
}
}
private static final class ValidatingObjectInputStream extends ObjectInputStream {
ValidatingObjectInputStream(final InputStream in) throws IOException {
super(in);
}
@Override
protected Class<?> resolveClass(final ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
final String name = desc.getName();
if (!isSafe(name)) {
throw new InvalidClassException("Unauthorized deserialization attempt", name);
}
return super.resolveClass(desc);
}
private boolean isSafe(final String name) {
return name.startsWith("java.lang.")
|| name.startsWith("java.util.")
|| name.startsWith("org.schabi.newpipe.")
|| name.startsWith("[Ljava.lang.")
|| name.startsWith("[Ljava.util.")
|| name.startsWith("[Lorg.schabi.newpipe.")
|| name.equals("[Z") || name.equals("[B") || name.equals("[C")
|| name.equals("[S") || name.equals("[I") || name.equals("[J")
|| name.equals("[F") || name.equals("[D");
}
}
/**
* Used for describing how to save/read the objects.
* <p>
* Queue was chosen by its FIFO property.
*/
public interface WriteRead {
/**
* Generate a changing suffix that will name the cache file,
* and be used to identify if it changed (thus reducing useless reading/saving).
*
* @return a unique value
*/
String generateSuffix();
/**
* Add to this queue objects that you want to save.
*
* @param objectsToSave the objects to save
*/
void writeTo(Queue<Object> objectsToSave);
/**
* Poll saved objects from the queue in the order they were written.
*
* @param savedObjects queue of objects returned by {@link #writeTo(Queue)}
*/
void readFrom(@NonNull Queue<Object> savedObjects) throws Exception;
}
}