-
Notifications
You must be signed in to change notification settings - Fork 556
/
IndexController.js
175 lines (142 loc) · 4.72 KB
/
IndexController.js
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
import PostsView from './views/Posts';
import ToastsView from './views/Toasts';
import idb from 'idb';
function openDatabase() {
// If the browser doesn't support service worker,
// we don't care about having a database
if (!navigator.serviceWorker) {
return Promise.resolve();
}
return idb.open('wittr', 1, function(upgradeDb) {
var store = upgradeDb.createObjectStore('wittrs', {
keyPath: 'id'
});
store.createIndex('by-date', 'time');
});
}
export default function IndexController(container) {
this._container = container;
this._postsView = new PostsView(this._container);
this._toastsView = new ToastsView(this._container);
this._lostConnectionToast = null;
this._dbPromise = openDatabase();
this._registerServiceWorker();
var indexController = this;
this._showCachedMessages().then(function() {
indexController._openSocket();
});
}
IndexController.prototype._registerServiceWorker = function() {
if (!navigator.serviceWorker) return;
var indexController = this;
navigator.serviceWorker.register('/sw.js').then(function(reg) {
if (!navigator.serviceWorker.controller) {
return;
}
if (reg.waiting) {
indexController._updateReady(reg.waiting);
return;
}
if (reg.installing) {
indexController._trackInstalling(reg.installing);
return;
}
reg.addEventListener('updatefound', function() {
indexController._trackInstalling(reg.installing);
});
});
// Ensure refresh is only called once.
// This works around a bug in "force update on reload".
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange', function() {
if (refreshing) return;
window.location.reload();
refreshing = true;
});
};
IndexController.prototype._showCachedMessages = function() {
var indexController = this;
return this._dbPromise.then(function(db) {
// if we're already showing posts, eg shift-refresh
// or the very first load, there's no point fetching
// posts from IDB
if (!db || indexController._postsView.showingPosts()) return;
var index = db.transaction('wittrs')
.objectStore('wittrs').index('by-date');
return index.getAll().then(function(messages) {
indexController._postsView.addPosts(messages.reverse());
});
});
};
IndexController.prototype._trackInstalling = function(worker) {
var indexController = this;
worker.addEventListener('statechange', function() {
if (worker.state == 'installed') {
indexController._updateReady(worker);
}
});
};
IndexController.prototype._updateReady = function(worker) {
var toast = this._toastsView.show("New version available", {
buttons: ['refresh', 'dismiss']
});
toast.answer.then(function(answer) {
if (answer != 'refresh') return;
worker.postMessage({action: 'skipWaiting'});
});
};
// open a connection to the server for live updates
IndexController.prototype._openSocket = function() {
var indexController = this;
var latestPostDate = this._postsView.getLatestPostDate();
// create a url pointing to /updates with the ws protocol
var socketUrl = new URL('/updates', window.location);
socketUrl.protocol = 'ws';
if (latestPostDate) {
socketUrl.search = 'since=' + latestPostDate.valueOf();
}
// this is a little hack for the settings page's tests,
// it isn't needed for Wittr
socketUrl.search += '&' + location.search.slice(1);
var ws = new WebSocket(socketUrl.href);
// add listeners
ws.addEventListener('open', function() {
if (indexController._lostConnectionToast) {
indexController._lostConnectionToast.hide();
}
});
ws.addEventListener('message', function(event) {
requestAnimationFrame(function() {
indexController._onSocketMessage(event.data);
});
});
ws.addEventListener('close', function() {
// tell the user
if (!indexController._lostConnectionToast) {
indexController._lostConnectionToast = indexController._toastsView.show("Unable to connect. Retrying…");
}
// try and reconnect in 5 seconds
setTimeout(function() {
indexController._openSocket();
}, 5000);
});
};
// called when the web socket sends message data
IndexController.prototype._onSocketMessage = function(data) {
var messages = JSON.parse(data);
this._dbPromise.then(function(db) {
if (!db) return;
var tx = db.transaction('wittrs', 'readwrite');
var store = tx.objectStore('wittrs');
messages.forEach(function(message) {
store.put(message);
});
// TODO: keep the newest 30 entries in 'wittrs',
// but delete the rest.
//
// Hint: you can use .openCursor(null, 'prev') to
// open a cursor that goes through an index/store
// backwards.
});
this._postsView.addPosts(messages);
};