about summary refs log tree commit diff
path: root/app/javascript/mastodon/storage/modifier.js
blob: 4773d07a9533a9ca85e5945029d997b9649fff8b (plain) (blame)
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
import asyncDB from './db';
import { autoPlayGif } from '../initial_state';

const accountAssetKeys = ['avatar', 'avatar_static', 'header', 'header_static'];
const avatarKey = autoPlayGif ? 'avatar' : 'avatar_static';
const limit = 1024;

// ServiceWorker and Cache API is not available on iOS 11
// https://webkit.org/status/#specification-service-workers
const asyncCache = window.caches ? caches.open('mastodon-system') : Promise.reject();

function printErrorIfAvailable(error) {
  if (error) {
    console.warn(error);
  }
}

function put(name, objects, onupdate, oncreate) {
  return asyncDB.then(db => new Promise((resolve, reject) => {
    const putTransaction = db.transaction(name, 'readwrite');
    const putStore = putTransaction.objectStore(name);
    const putIndex = putStore.index('id');

    objects.forEach(object => {
      putIndex.getKey(object.id).onsuccess = retrieval => {
        function addObject() {
          putStore.add(object);
        }

        function deleteObject() {
          putStore.delete(retrieval.target.result).onsuccess = addObject;
        }

        if (retrieval.target.result) {
          if (onupdate) {
            onupdate(object, retrieval.target.result, putStore, deleteObject);
          } else {
            deleteObject();
          }
        } else {
          if (oncreate) {
            oncreate(object, addObject);
          } else {
            addObject();
          }
        }
      };
    });

    putTransaction.oncomplete = () => {
      const readTransaction = db.transaction(name, 'readonly');
      const readStore = readTransaction.objectStore(name);
      const count = readStore.count();

      count.onsuccess = () => {
        const excess = count.result - limit;

        if (excess > 0) {
          const retrieval = readStore.getAll(null, excess);

          retrieval.onsuccess = () => resolve(retrieval.result);
          retrieval.onerror = reject;
        } else {
          resolve([]);
        }
      };

      count.onerror = reject;
    };

    putTransaction.onerror = reject;
  }));
}

function evictAccountsByRecords(records) {
  asyncDB.then(db => {
    const transaction = db.transaction(['accounts', 'statuses'], 'readwrite');
    const accounts = transaction.objectStore('accounts');
    const accountsIdIndex = accounts.index('id');
    const accountsMovedIndex = accounts.index('moved');
    const statuses = transaction.objectStore('statuses');
    const statusesIndex = statuses.index('account');

    function evict(toEvict) {
      toEvict.forEach(record => {
        asyncCache
          .then(cache => accountAssetKeys.forEach(key => cache.delete(records[key])))
          .catch(printErrorIfAvailable);

        accountsMovedIndex.getAll(record.id).onsuccess = ({ target }) => evict(target.result);

        statusesIndex.getAll(record.id).onsuccess =
          ({ target }) => evictStatusesByRecords(target.result);

        accountsIdIndex.getKey(record.id).onsuccess =
          ({ target }) => target.result && accounts.delete(target.result);
      });
    }

    evict(records);
  }).catch(printErrorIfAvailable);
}

export function evictStatus(id) {
  evictStatuses([id]);
}

export function evictStatuses(ids) {
  asyncDB.then(db => {
    const store = db.transaction('statuses', 'readwrite').objectStore('statuses');
    const idIndex = store.index('id');
    const reblogIndex = store.index('reblog');

    ids.forEach(id => {
      reblogIndex.getAllKeys(id).onsuccess =
        ({ target }) => target.result.forEach(reblogKey => store.delete(reblogKey));

      idIndex.getKey(id).onsuccess =
        ({ target }) => target.result && store.delete(target.result);
    });
  }).catch(printErrorIfAvailable);
}

function evictStatusesByRecords(records) {
  evictStatuses(records.map(({ id }) => id));
}

export function putAccounts(records) {
  const newURLs = [];

  put('accounts', records, (newRecord, oldKey, store, oncomplete) => {
    store.get(oldKey).onsuccess = ({ target }) => {
      accountAssetKeys.forEach(key => {
        const newURL = newRecord[key];
        const oldURL = target.result[key];

        if (newURL !== oldURL) {
          asyncCache
            .then(cache => cache.delete(oldURL))
            .catch(printErrorIfAvailable);
        }
      });

      const newURL = newRecord[avatarKey];
      const oldURL = target.result[avatarKey];

      if (newURL !== oldURL) {
        newURLs.push(newURL);
      }

      oncomplete();
    };
  }, (newRecord, oncomplete) => {
    newURLs.push(newRecord[avatarKey]);
    oncomplete();
  }).then(records => {
    evictAccountsByRecords(records);
    asyncCache
      .then(cache => cache.addAll(newURLs))
      .catch(printErrorIfAvailable);
  }).catch(printErrorIfAvailable);
}

export function putStatuses(records) {
  put('statuses', records)
    .then(evictStatusesByRecords)
    .catch(printErrorIfAvailable);
}