summaryrefslogtreecommitdiffstats
path: root/mobile/android/base/java/org/mozilla/gecko/dlc/catalog/DownloadContentCatalog.java
blob: 43ba4e82e0280a36b258aeef4e423e1368bd7805 (plain)
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
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.dlc.catalog;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.AtomicFile;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Catalog of downloadable content (DLC).
 *
 * Changing elements returned by the catalog should be guarded by the catalog instance to guarantee visibility when
 * persisting changes.
 */
public class DownloadContentCatalog {
    private static final String LOGTAG = "GeckoDLCCatalog";
    private static final String FILE_NAME = "download_content_catalog";

    private static final String JSON_KEY_CONTENT = "content";

    private static final int MAX_FAILURES_UNTIL_PERMANENTLY_FAILED = 10;

    private final AtomicFile file; // Guarded by 'file'

    private ArrayMap<String, DownloadContent> content; // Guarded by 'this'
    private boolean hasLoadedCatalog; // Guarded by 'this
    private boolean hasCatalogChanged; // Guarded by 'this'

    public DownloadContentCatalog(Context context) {
        this(new AtomicFile(new File(context.getApplicationInfo().dataDir, FILE_NAME)));

        startLoadFromDisk();
    }

    // For injecting mocked AtomicFile objects during test
    protected DownloadContentCatalog(AtomicFile file) {
        this.content = new ArrayMap<>();
        this.file = file;
    }

    public List<DownloadContent> getContentToStudy() {
        return filterByState(DownloadContent.STATE_NONE, DownloadContent.STATE_UPDATED);
    }

    public List<DownloadContent> getContentToDelete() {
        return filterByState(DownloadContent.STATE_DELETED);
    }

    public List<DownloadContent> getDownloadedContent() {
        return filterByState(DownloadContent.STATE_DOWNLOADED);
    }

    public List<DownloadContent> getScheduledDownloads() {
        return filterByState(DownloadContent.STATE_SCHEDULED);
    }

    private synchronized List<DownloadContent> filterByState(@DownloadContent.State int... filterStates) {
        awaitLoadingCatalogLocked();

        List<DownloadContent> filteredContent = new ArrayList<>();

        for (DownloadContent currentContent : content.values()) {
            if (currentContent.isStateIn(filterStates)) {
                filteredContent.add(currentContent);
            }
        }

        return filteredContent;
    }

    public boolean hasScheduledDownloads() {
        return !filterByState(DownloadContent.STATE_SCHEDULED).isEmpty();
    }

    public synchronized void add(DownloadContent newContent) {
        awaitLoadingCatalogLocked();

        content.put(newContent.getId(), newContent);
        hasCatalogChanged = true;
    }

    public synchronized void update(DownloadContent changedContent) {
        awaitLoadingCatalogLocked();

        if (!content.containsKey(changedContent.getId())) {
            Log.w(LOGTAG, "Did not find content with matching id (" + changedContent.getId() + ") to update");
            return;
        }

        changedContent.setState(DownloadContent.STATE_UPDATED);
        changedContent.resetFailures();

        content.put(changedContent.getId(), changedContent);
        hasCatalogChanged = true;
    }

    public synchronized void remove(DownloadContent removedContent) {
        awaitLoadingCatalogLocked();

        if (!content.containsKey(removedContent.getId())) {
            Log.w(LOGTAG, "Did not find content with matching id (" + removedContent.getId() + ") to remove");
            return;
        }

        content.remove(removedContent.getId());
    }

    @Nullable
    public synchronized DownloadContent getContentById(String id) {
        return content.get(id);
    }

    public synchronized long getLastModified() {
        awaitLoadingCatalogLocked();

        long lastModified = 0;

        for (DownloadContent currentContent : content.values()) {
            if (currentContent.getLastModified() > lastModified) {
                lastModified = currentContent.getLastModified();
            }
        }

        return lastModified;
    }

    public synchronized void scheduleDownload(DownloadContent content) {
        content.setState(DownloadContent.STATE_SCHEDULED);
        hasCatalogChanged = true;
    }

    public synchronized void markAsDownloaded(DownloadContent content) {
        content.setState(DownloadContent.STATE_DOWNLOADED);
        content.resetFailures();
        hasCatalogChanged = true;
    }

    public synchronized void markAsPermanentlyFailed(DownloadContent content) {
        content.setState(DownloadContent.STATE_FAILED);
        hasCatalogChanged = true;
    }

    public synchronized void markAsDeleted(DownloadContent content) {
        content.setState(DownloadContent.STATE_DELETED);
        hasCatalogChanged = true;
    }

    public synchronized void rememberFailure(DownloadContent content, int failureType) {
        if (content.getFailures() >= MAX_FAILURES_UNTIL_PERMANENTLY_FAILED) {
            Log.d(LOGTAG, "Maximum number of failures reached. Marking content has permanently failed.");

            markAsPermanentlyFailed(content);
        } else {
            content.rememberFailure(failureType);
            hasCatalogChanged = true;
        }
    }

    public void persistChanges() {
        new Thread(LOGTAG + "-Persist") {
            public void run() {
                writeToDisk();
            }
        }.start();
    }

    private void startLoadFromDisk() {
        new Thread(LOGTAG + "-Load") {
            public void run() {
                loadFromDisk();
            }
        }.start();
    }

    private void awaitLoadingCatalogLocked() {
        while (!hasLoadedCatalog) {
            try {
                Log.v(LOGTAG, "Waiting for catalog to be loaded");

                wait();
            } catch (InterruptedException e) {
                // Ignore
            }
        }
    }

    protected synchronized boolean hasCatalogChanged() {
        return hasCatalogChanged;
    }

    protected synchronized void loadFromDisk() {
        Log.d(LOGTAG, "Loading from disk");

        if (hasLoadedCatalog) {
            return;
        }

        ArrayMap<String, DownloadContent> loadedContent = new ArrayMap<>();

        try {
            JSONObject catalog;

            synchronized (file) {
                catalog = new JSONObject(new String(file.readFully(), "UTF-8"));
            }

            JSONArray array = catalog.getJSONArray(JSON_KEY_CONTENT);
            for (int i = 0; i < array.length(); i++) {
                DownloadContent currentContent = DownloadContentBuilder.fromJSON(array.getJSONObject(i));
                loadedContent.put(currentContent.getId(), currentContent);
            }
        } catch (FileNotFoundException e) {
            Log.d(LOGTAG, "Catalog file does not exist: Bootstrapping initial catalog");
            loadedContent = DownloadContentBootstrap.createInitialDownloadContentList();
        } catch (JSONException e) {
            Log.w(LOGTAG, "Unable to parse catalog JSON. Re-creating catalog.", e);
            // Catalog seems to be broken. Re-create catalog:
            loadedContent = DownloadContentBootstrap.createInitialDownloadContentList();
            hasCatalogChanged = true; // Indicate that we want to persist the new catalog
        } catch (NullPointerException e) {
            // Bad content can produce an NPE in JSON code -- bug 1300139
            Log.w(LOGTAG, "Unable to parse catalog JSON. Re-creating catalog.", e);
            // Catalog seems to be broken. Re-create catalog:
            loadedContent = DownloadContentBootstrap.createInitialDownloadContentList();
            hasCatalogChanged = true; // Indicate that we want to persist the new catalog
        } catch (UnsupportedEncodingException e) {
            AssertionError error = new AssertionError("Should not happen: This device does not speak UTF-8");
            error.initCause(e);
            throw error;
        } catch (IOException e) {
            Log.d(LOGTAG, "Can't read catalog due to IOException", e);
        }

        onCatalogLoaded(loadedContent);

        notifyAll();

        Log.d(LOGTAG, "Loaded " + content.size() + " elements");
    }

    protected void onCatalogLoaded(ArrayMap<String, DownloadContent> content) {
        this.content = content;
        this.hasLoadedCatalog = true;
    }

    protected synchronized void writeToDisk() {
        if (!hasCatalogChanged) {
            Log.v(LOGTAG, "Not persisting: Catalog has not changed");
            return;
        }

        Log.d(LOGTAG, "Writing to disk");

        FileOutputStream outputStream = null;

        synchronized (file) {
            try {
                outputStream = file.startWrite();

                JSONArray array = new JSONArray();
                for (DownloadContent currentContent : content.values()) {
                    array.put(DownloadContentBuilder.toJSON(currentContent));
                }

                JSONObject catalog = new JSONObject();
                catalog.put(JSON_KEY_CONTENT, array);

                outputStream.write(catalog.toString().getBytes("UTF-8"));

                file.finishWrite(outputStream);

                hasCatalogChanged = false;
            } catch (UnsupportedEncodingException e) {
                AssertionError error = new AssertionError("Should not happen: This device does not speak UTF-8");
                error.initCause(e);
                throw error;
            } catch (IOException | JSONException e) {
                Log.e(LOGTAG, "IOException during writing catalog", e);

                if (outputStream != null) {
                    file.failWrite(outputStream);
                }
            }
        }
    }
}