-
Notifications
You must be signed in to change notification settings - Fork 215
/
Accounts.kt
382 lines (313 loc) · 13.1 KB
/
Accounts.kt
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; 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.vrbrowser.browser
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.ProcessLifecycleOwner
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.future.future
import kotlinx.coroutines.launch
import mozilla.components.concept.sync.*
import mozilla.components.service.fxa.FirefoxAccount
import mozilla.components.service.fxa.SyncEngine
import mozilla.components.service.fxa.manager.SyncEnginesStorage
import mozilla.components.service.fxa.sync.SyncReason
import mozilla.components.service.fxa.sync.SyncStatusObserver
import mozilla.components.service.fxa.sync.getLastSynced
import org.mozilla.vrbrowser.R
import org.mozilla.vrbrowser.VRBrowserApplication
import org.mozilla.vrbrowser.utils.BitmapCache
import org.mozilla.vrbrowser.telemetry.GleanMetricsService
import org.mozilla.vrbrowser.utils.SystemUtils
import org.mozilla.vrbrowser.utils.ViewUtils
import java.net.URL
import java.util.concurrent.CompletableFuture
const val PROFILE_PICTURE_TAG = "fxa_profile_picture"
class Accounts constructor(val context: Context) {
private val LOGTAG = SystemUtils.createLogtag(Accounts::class.java)
enum class AccountStatus {
SIGNED_IN,
SIGNED_OUT,
NEEDS_RECONNECT
}
enum class LoginOrigin {
BOOKMARKS,
HISTORY,
SETTINGS,
SEND_TABS,
NONE
}
var profilePicture: BitmapDrawable? = loadDefaultProfilePicture()
var loginOrigin: LoginOrigin = LoginOrigin.NONE
var accountStatus = AccountStatus.SIGNED_OUT
private val accountListeners = ArrayList<AccountObserver>()
private val syncListeners = ArrayList<SyncStatusObserver>()
private val deviceConstellationListeners = ArrayList<DeviceConstellationObserver>()
private val services = (context.applicationContext as VRBrowserApplication).services
private var otherDevices = emptyList<Device>()
private val syncStorage = SyncEnginesStorage(context)
var isSyncing = false
private val syncStatusObserver = object : SyncStatusObserver {
override fun onStarted() {
Log.d(LOGTAG, "Account syncing has started")
isSyncing = true
syncListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onStarted()
}
}
}
override fun onIdle() {
Log.d(LOGTAG, "Account syncing has finished")
isSyncing = false
services.accountManager.accountProfile()?.email?.let {
SettingsStore.getInstance(context).setFxALastSync(it, getLastSynced(context))
}
syncListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onIdle()
}
}
}
override fun onError(error: Exception?) {
Log.d(LOGTAG, "There was an error while syncing the account: " + error?.localizedMessage)
isSyncing = false
syncListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onError(error)
}
}
}
}
private val deviceConstellationObserver = object : DeviceConstellationObserver {
override fun onDevicesUpdate(constellation: ConstellationState) {
Log.d(LOGTAG, "Device constellation has been updated: " + constellation.otherDevices.toString())
otherDevices = constellation.otherDevices
deviceConstellationListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onDevicesUpdate(constellation)
}
}
}
}
private val accountObserver = object : AccountObserver {
override fun onAuthenticated(account: OAuthAccount, authType: AuthType) {
Log.d(LOGTAG, "The user has been successfully logged in")
if (authType !== AuthType.Existing) {
GleanMetricsService.FxA.signInResult(true)
}
accountStatus = AccountStatus.SIGNED_IN
// Enable syncing after signing in
syncStorage.setStatus(SyncEngine.Bookmarks, SettingsStore.getInstance(context).isBookmarksSyncEnabled)
syncStorage.setStatus(SyncEngine.History, SettingsStore.getInstance(context).isHistorySyncEnabled)
services.accountManager.syncNowAsync(SyncReason.EngineChange, true)
// Update device list
account.deviceConstellation().registerDeviceObserver(
deviceConstellationObserver,
ProcessLifecycleOwner.get(),
true
)
account.deviceConstellation().refreshDevicesAsync()
accountListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onAuthenticated(account, authType)
}
}
}
override fun onAuthenticationProblems() {
Log.d(LOGTAG, "There was a problem authenticating the user")
GleanMetricsService.FxA.signInResult(false)
accountStatus = AccountStatus.NEEDS_RECONNECT
accountListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onAuthenticationProblems()
}
}
}
override fun onLoggedOut() {
Log.d(LOGTAG, "The user has been logged out")
accountStatus = AccountStatus.SIGNED_OUT
accountListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onLoggedOut()
}
}
loadDefaultProfilePicture()
}
override fun onProfileUpdated(profile: Profile) {
Log.d(LOGTAG, "The user profile has been updated")
accountListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onProfileUpdated(profile)
}
}
loadProfilePicture(profile)
}
}
init {
services.accountManager.registerForSyncEvents(
syncStatusObserver, ProcessLifecycleOwner.get(), false
)
services.accountManager.register(accountObserver)
accountStatus = if (services.accountManager.authenticatedAccount() != null) {
if (services.accountManager.accountNeedsReauth()) {
AccountStatus.NEEDS_RECONNECT
} else {
AccountStatus.SIGNED_IN
}
} else {
AccountStatus.SIGNED_OUT
}
}
private fun loadProfilePicture(profile: Profile) {
CoroutineScope(Dispatchers.IO).launch {
try {
val url = URL(profile.avatar!!.url)
BitmapFactory.decodeStream(url.openStream())?.let {
val bitmap = ViewUtils.getRoundedCroppedBitmap(it)
profilePicture = BitmapDrawable(context.resources, bitmap)
BitmapCache.getInstance(context).addBitmap(PROFILE_PICTURE_TAG, bitmap)
} ?: throw IllegalArgumentException()
} catch (e: Exception) {
loadDefaultProfilePicture()
} finally {
accountListeners.toMutableList().forEach {
Handler(Looper.getMainLooper()).post {
it.onProfileUpdated(profile)
}
}
}
}
}
private fun loadDefaultProfilePicture(): BitmapDrawable? {
BitmapFactory.decodeResource(context.resources, R.drawable.ic_icon_settings_account)?.let {
BitmapCache.getInstance(context).addBitmap(PROFILE_PICTURE_TAG, it)
profilePicture = BitmapDrawable(context.resources, ViewUtils.getRoundedCroppedBitmap(it))
}
return profilePicture
}
fun addAccountListener(aListener: AccountObserver) {
if (!accountListeners.contains(aListener)) {
accountListeners.add(aListener)
}
}
fun removeAccountListener(aListener: AccountObserver) {
accountListeners.remove(aListener)
}
fun removeAllAccountListeners() {
accountListeners.clear()
}
fun addSyncListener(aListener: SyncStatusObserver) {
if (!syncListeners.contains(aListener)) {
syncListeners.add(aListener)
}
}
fun removeSyncListener(aListener: SyncStatusObserver) {
syncListeners.remove(aListener)
}
fun removeAllSyncListeners() {
syncListeners.clear()
}
fun addDeviceConstellationListener(aListener: DeviceConstellationObserver) {
if (!deviceConstellationListeners.contains(aListener)) {
deviceConstellationListeners.add(aListener)
}
}
fun removeDeviceConstellationListener(aListener: DeviceConstellationObserver) {
deviceConstellationListeners.remove(aListener)
}
fun removeAllDeviceConstellationListeners() {
deviceConstellationListeners.clear()
}
fun authUrlAsync(): CompletableFuture<String?>? {
GleanMetricsService.FxA.signIn()
return CoroutineScope(Dispatchers.Main).future {
services.accountManager.beginAuthenticationAsync().await()
}
}
fun refreshDevicesAsync(): CompletableFuture<Boolean?>? {
return CoroutineScope(Dispatchers.Main).future {
services.accountManager.authenticatedAccount()?.deviceConstellation()?.refreshDevicesAsync()?.await()
}
}
fun pollForEventsAsync(): CompletableFuture<Boolean?>? {
return CoroutineScope(Dispatchers.Main).future {
services.accountManager.authenticatedAccount()?.deviceConstellation()?.pollForEventsAsync()?.await()
}
}
fun updateProfileAsync(): CompletableFuture<Unit?>? {
return CoroutineScope(Dispatchers.Main).future {
services.accountManager.updateProfileAsync().await()
}
}
fun syncNowAsync(reason: SyncReason = SyncReason.User,
debounce: Boolean = false): CompletableFuture<Unit?>?{
return CoroutineScope(Dispatchers.Main).future {
services.accountManager.syncNowAsync(reason, debounce).await()
}
}
fun setSyncStatus(engine: SyncEngine, value: Boolean) {
when(engine) {
SyncEngine.Bookmarks -> {
GleanMetricsService.FxA.bookmarksSyncStatus(value)
SettingsStore.getInstance(context).isBookmarksSyncEnabled = value
}
SyncEngine.History -> {
GleanMetricsService.FxA.historySyncStatus(value)
SettingsStore.getInstance(context).isHistorySyncEnabled = value
}
}
syncStorage.setStatus(engine, value)
}
fun accountProfile(): Profile? {
return services.accountManager.accountProfile()
}
fun logoutAsync(): CompletableFuture<Unit?>? {
GleanMetricsService.FxA.signOut()
otherDevices = emptyList()
return CoroutineScope(Dispatchers.Main).future {
services.accountManager.logoutAsync().await()
}
}
fun isEngineEnabled(engine: SyncEngine): Boolean {
return syncStorage.getStatus()[engine]?: false
}
fun isSignedIn(): Boolean {
return (accountStatus == AccountStatus.SIGNED_IN)
}
fun lastSync(): Long {
services.accountManager.accountProfile()?.email?.let {
return SettingsStore.getInstance(context).getFxALastSync(it)
}
return 0
}
fun devicesByCapability(capabilities: List<DeviceCapability>): List<Device> {
return otherDevices.filter { it.capabilities.containsAll(capabilities) }
}
fun sendTabs(targetDevices: List<Device>, url: String, title: String) {
CoroutineScope(Dispatchers.Main).launch {
services.accountManager.authenticatedAccount()?.deviceConstellation()?.let { constellation ->
// Ignore devices that can't receive tabs or are not in the received list
val targets = constellation.state()?.otherDevices?.filter {
it.capabilities.contains(DeviceCapability.SEND_TAB)
targetDevices.contains(it)
}
targets?.forEach { it ->
constellation.sendEventToDeviceAsync(
it.id, DeviceEventOutgoing.SendTab(title, url)
).await().also { if (it) GleanMetricsService.FxA.sentTab() }
}
}
}
}
fun getConnectionSuccessURL(): String {
return (services.accountManager.authenticatedAccount() as FirefoxAccount).getConnectionSuccessURL()
}
}