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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
|
/*
* SPDX-FileCopyrightText: 2013 - 2026 Jolla Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
import QtQuick 2.0
import Sailfish.Silica 1.0
import Sailfish.Accounts 1.0
import com.jolla.settings.accounts 1.0
import com.jolla.settings.accounts.fediverse 1.0
AccountCreationAgent {
id: root
property Item _oauthPage
property Item _settingsDialog
property QtObject _accountSetup
property string _pendingApiHost
property var _pendingInstanceContext: ({})
property bool _registering
readonly property string callbackUri: "http://ipv4.jolla.com/online/status.html"
readonly property string defaultServerHost: "mastodon.social"
readonly property string defaultApiHost: normalizeApiHost(defaultServerHost)
readonly property string genericIconPath: "image://theme/icon-l-fediverse"
function normalizeApiHost(rawHost) {
var host = rawHost ? rawHost.trim() : ""
if (host.length === 0) {
return ""
}
host = host.replace(/^https?:\/\//i, "")
var pathSeparator = host.indexOf("/")
if (pathSeparator !== -1) {
host = host.substring(0, pathSeparator)
}
host = host.replace(/\/+$/, "")
if (host.length === 0) {
return ""
}
return "https://" + host.toLowerCase()
}
function oauthHost(apiHost) {
return apiHost.replace(/^https?:\/\//i, "")
}
function _trimmedString(value) {
return value ? value.toString().trim() : ""
}
function _normalizeResourceUrl(rawUrl, apiHost) {
var value = _trimmedString(rawUrl)
if (value.length === 0) {
return ""
}
if (/^https?:\/\//i.test(value)) {
return value
}
if (value.indexOf("//") === 0) {
return "https:" + value
}
if (value.charAt(0) === "/") {
return apiHost + value
}
return apiHost + "/" + value.replace(/^\/+/, "")
}
function _displayName(apiHost) {
return oauthHost(apiHost)
}
function _fallbackDisplayName(apiHost) {
var display = _displayName(apiHost)
if (display.length > 0) {
return display
}
return _displayName(defaultApiHost)
}
function _instanceContext(apiHost) {
var normalizedApiHost = normalizeApiHost(apiHost)
var title = _fallbackDisplayName(normalizedApiHost)
return {
"apiHost": normalizedApiHost,
"oauthHost": oauthHost(normalizedApiHost),
//% "Fediverse"
"instanceTitle": title.length > 0 ? title : qsTrId("settings-accounts-fediverse-la-provider_name"),
"instanceDescription": "",
"instanceIconUrl": "",
"instanceIconPath": instanceIconCache.cachedIconPath(normalizedApiHost)
}
}
function _extractInstanceTitle(responseData, apiHost) {
var candidates = [
responseData ? responseData.title : "",
responseData ? responseData.name : "",
responseData ? responseData.uri : ""
]
for (var i = 0; i < candidates.length; ++i) {
var value = _trimmedString(candidates[i])
if (value.length > 0) {
return value
}
}
return _fallbackDisplayName(apiHost)
}
function _extractInstanceDescription(responseData) {
var candidates = [
responseData ? responseData.short_description : "",
responseData ? responseData.description : "",
responseData ? responseData.shortDescription : ""
]
for (var i = 0; i < candidates.length; ++i) {
var value = _trimmedString(candidates[i])
if (value.length > 0) {
return value
}
}
return ""
}
function _extractInstanceIconUrl(responseData, apiHost) {
if (!responseData) {
return ""
}
function normalizedIconUrl(candidate) {
return _normalizeResourceUrl(_trimmedString(candidate), apiHost)
}
function iconScore(iconObject) {
var size = _trimmedString(iconObject && iconObject.size)
var match = size.match(/^(\d+)x(\d+)$/)
if (!match) {
return 1000000
}
var width = parseInt(match[1], 10)
var height = parseInt(match[2], 10)
if (!(width > 0) || !(height > 0)) {
return 1000000
}
var area = width * height
var squarenessPenalty = Math.abs(width - height) * 1000
var sizePenalty = Math.abs(Math.max(width, height) - 64)
return squarenessPenalty + sizePenalty + area
}
if (responseData.icon) {
if (typeof responseData.icon === "string") {
return normalizedIconUrl(responseData.icon)
}
if (responseData.icon.src) {
return normalizedIconUrl(responseData.icon.src)
}
if (responseData.icon.length > 0) {
var bestIndex = -1
var bestScore = Number.MAX_VALUE
for (var i = 0; i < responseData.icon.length; ++i) {
var candidate = responseData.icon[i]
var candidateUrl = normalizedIconUrl(candidate && candidate.src)
if (candidateUrl.length === 0) {
continue
}
var score = iconScore(candidate)
if (score < bestScore) {
bestScore = score
bestIndex = i
}
}
if (bestIndex >= 0) {
return normalizedIconUrl(responseData.icon[bestIndex].src)
}
}
}
if (responseData.thumbnail) {
if (typeof responseData.thumbnail === "string") {
return normalizedIconUrl(responseData.thumbnail)
}
if (responseData.thumbnail.url) {
return normalizedIconUrl(responseData.thumbnail.url)
}
if (responseData.thumbnail.static_url) {
return normalizedIconUrl(responseData.thumbnail.static_url)
}
}
return ""
}
function _showRegistrationError(message, busyPage) {
_registering = false
accountCreationError(message)
if (busyPage) {
busyPage.state = "info"
busyPage.infoDescription = message
busyPage.infoExtraDescription = ""
busyPage.infoButtonText = ""
}
}
function _showOAuthPage(context) {
_registering = false
if (_oauthPage != null) {
_oauthPage.cancelSignIn()
_oauthPage.destroy()
}
_oauthPage = oAuthComponent.createObject(root, { "context": context })
pageStack.replace(_oauthPage)
}
function _registerClientApplication(context, busyPage) {
if (_registering) {
return
}
_registering = true
if (context.instanceIconUrl.length > 0 && context.instanceIconPath.length === 0) {
instanceIconCache.cacheIcon(context.apiHost, context.instanceIconUrl)
}
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState !== XMLHttpRequest.DONE) {
return
}
if (xhr.status < 200 || xhr.status >= 300) {
//% "Failed to register the Fediverse application for %1"
_showRegistrationError(qsTrId("settings-accounts-fediverse-la-register_app_failed").arg(context.apiHost), busyPage)
return
}
var response
try {
response = JSON.parse(xhr.responseText)
} catch (err) {
//% "Invalid response while registering the Fediverse application"
_showRegistrationError(qsTrId("settings-accounts-fediverse-la-invalid_app_registration_response"), busyPage)
return
}
if (!response.client_id || !response.client_secret) {
//% "Fediverse application registration did not return client credentials"
_showRegistrationError(qsTrId("settings-accounts-fediverse-la-app_registration_missing_credentials"), busyPage)
return
}
context.clientId = response.client_id
context.clientSecret = response.client_secret
_showOAuthPage(context)
}
var postData = []
//% "SailfishOS Fediverse"
postData.push("client_name=" + encodeURIComponent(qsTrId("settings-accounts-fediverse-la-client_name")))
postData.push("redirect_uris=" + encodeURIComponent(callbackUri))
postData.push("scopes=" + encodeURIComponent("read write"))
postData.push("website=" + encodeURIComponent("https://sailfishos.org"))
xhr.open("POST", context.apiHost + "/api/v1/apps")
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(postData.join("&"))
}
function _discoverInstanceContext(apiHost, busyPage) {
var context = _instanceContext(apiHost)
_pendingInstanceContext = context
function continueWithContext() {
_pendingInstanceContext = context
_registerClientApplication(context, busyPage)
}
function loadEndpoint(paths, index) {
if (index >= paths.length) {
continueWithContext()
return
}
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState !== XMLHttpRequest.DONE) {
return
}
if (xhr.status >= 200 && xhr.status < 300) {
try {
var response = JSON.parse(xhr.responseText)
context.instanceTitle = _extractInstanceTitle(response, context.apiHost)
context.instanceDescription = _extractInstanceDescription(response)
context.instanceIconUrl = _extractInstanceIconUrl(response, context.apiHost)
if (context.instanceIconUrl.length > 0) {
var cachedPath = instanceIconCache.cachedIconPath(context.apiHost)
if (cachedPath.length > 0) {
context.instanceIconPath = cachedPath
}
}
} catch (err) {
}
continueWithContext()
return
}
loadEndpoint(paths, index + 1)
}
xhr.open("GET", context.apiHost + paths[index])
xhr.send()
}
loadEndpoint(["/api/v2/instance", "/api/v1/instance"], 0)
}
function _extractAccountName(responseData) {
if (!responseData) {
return ""
}
var candidates = [
"AccountUsername",
"UserName",
"user_name",
"acct",
"username",
"preferred_username",
"login",
"ScreenName"
]
for (var i = 0; i < candidates.length; ++i) {
var value = responseData[candidates[i]]
if (value) {
var userName = value.toString().trim()
if (userName.length > 0) {
return userName
}
}
}
return ""
}
function _formatFediverseAccountId(accountName, apiHost) {
var value = accountName ? accountName.toString().trim() : ""
if (value.length === 0) {
return ""
}
value = value.replace(/^@+/, "")
if (value.indexOf("@") !== -1) {
return "@" + value
}
var host = oauthHost(apiHost)
if (host.length === 0) {
return ""
}
return "@" + value + "@" + host
}
function _isFediverseAccountId(value) {
var text = value ? value.toString().trim() : ""
return /^@[^@]+@[^@]+$/.test(text)
}
function _extractAccessToken(responseData) {
if (!responseData) {
return ""
}
var token = responseData["AccessToken"]
if (!token || token.toString().trim().length === 0) {
token = responseData["access_token"]
}
return token ? token.toString().trim() : ""
}
function _handleAccountCreated(accountId, context, responseData) {
var props = {
"accountId": accountId,
"apiHost": context.apiHost,
"oauthHost": context.oauthHost,
"clientId": context.clientId,
"clientSecret": context.clientSecret,
"accessToken": _extractAccessToken(responseData),
"accountDescription": _formatFediverseAccountId(_extractAccountName(responseData), context.apiHost),
"instanceTitle": context.instanceTitle,
"instanceDescription": context.instanceDescription,
"instanceIconUrl": context.instanceIconUrl,
"instanceIconPath": context.instanceIconPath
}
_accountSetup = accountSetupComponent.createObject(root, props)
_accountSetup.done.connect(function() {
accountCreated(accountId)
_goToSettings(accountId)
})
_accountSetup.error.connect(function() {
//% "Failed to finish Fediverse account setup"
accountCreationError(qsTrId("settings-accounts-fediverse-la-account_setup_failed"))
})
}
function _goToSettings(accountId) {
if (_settingsDialog != null) {
_settingsDialog.destroy()
}
_settingsDialog = settingsComponent.createObject(root, {"accountId": accountId})
pageStack.replace(_settingsDialog)
}
FediverseInstanceIconCache {
id: instanceIconCache
onIconReady: {
var normalizedHost = root.normalizeApiHost(apiHost)
if (root._pendingInstanceContext.apiHost === normalizedHost) {
root._pendingInstanceContext.instanceIconPath = iconPath
}
if (root._accountSetup && root._accountSetup.apiHost === normalizedHost) {
root._accountSetup.updateInstanceIcon(iconPath)
}
}
}
initialPage: Dialog {
id: setupDialog
property string normalizedHost: root.normalizeApiHost(instanceField.text)
canAccept: !root._registering
acceptDestinationAction: PageStackAction.Push
acceptDestination: busyComponent
onAccepted: {
root._pendingApiHost = normalizedHost.length > 0 ? normalizedHost : root.defaultApiHost
}
DialogHeader {
id: header
acceptText: qsTrId("settings-accounts-common-bt-sign_in")
}
Column {
anchors.top: header.bottom
anchors.topMargin: Theme.paddingLarge
spacing: Theme.paddingLarge
width: parent.width
Row {
x: Theme.horizontalPageMargin
width: parent.width - x * 2
spacing: Theme.paddingMedium
Image {
id: promptIcon
width: Theme.iconSizeMedium
height: Theme.iconSizeMedium
source: root.genericIconPath
fillMode: Image.PreserveAspectFit
sourceSize.width: width
sourceSize.height: height
}
Label {
width: parent.width - promptIcon.width - parent.spacing
wrapMode: Text.Wrap
color: Theme.highlightColor
//% "Enter the server address, then sign in."
text: qsTrId("settings-accounts-fediverse-la-enter_server_then_sign_in")
}
}
TextField {
id: instanceField
x: Theme.horizontalPageMargin
width: parent.width - x * 2
//% "Server"
label: qsTrId("settings-accounts-fediverse-la-server")
placeholderText: root.defaultServerHost
inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhUrlCharactersOnly
EnterKey.iconSource: "image://theme/icon-m-enter-next"
EnterKey.onClicked: {
if (setupDialog.canAccept) {
setupDialog.accept()
}
}
}
}
}
Component {
id: busyComponent
AccountBusyPage {
//% "Preparing Fediverse sign-in..."
busyDescription: qsTrId("settings-accounts-fediverse-la-preparing_sign_in")
onStatusChanged: {
if (status === PageStatus.Active && root._pendingApiHost.length > 0) {
root._discoverInstanceContext(root._pendingApiHost, this)
}
}
}
}
Component {
id: oAuthComponent
OAuthAccountSetupPage {
property var context
Component.onCompleted: {
var sessionData = {
"ClientId": context.clientId,
"ClientSecret": context.clientSecret,
"Host": context.oauthHost,
"AuthPath": "oauth/authorize",
"TokenPath": "oauth/token",
"ResponseType": "code",
"Scope": ["read", "write"],
"RedirectUri": root.callbackUri
}
prepareAccountCreation(root.accountProvider, "fediverse-microblog", sessionData)
}
onAccountCreated: {
root._handleAccountCreated(accountId, context, responseData)
}
onAccountCreationError: {
root.accountCreationError(errorMessage)
}
}
}
Component {
id: accountSetupComponent
QtObject {
id: accountSetup
property int accountId
property string apiHost
property string oauthHost
property string clientId
property string clientSecret
property string accessToken
property string accountDescription
property string instanceTitle
property string instanceDescription
property string instanceIconUrl
property string instanceIconPath
property bool hasConfigured
signal done()
signal error()
property Account newAccount: Account {
identifier: accountSetup.accountId
onStatusChanged: {
if (status === Account.Initialized || status === Account.Synced) {
if (!accountSetup.hasConfigured) {
accountSetup.configure()
} else {
accountSetup.done()
}
} else if (status === Account.Invalid && accountSetup.hasConfigured) {
accountSetup.error()
}
}
}
function _serviceNames() {
return ["fediverse-microblog", "fediverse-notifications", "fediverse-sharing"]
}
function _effectiveInstanceTitle() {
var title = root._trimmedString(instanceTitle)
//% "Fediverse"
return title.length > 0 ? title : qsTrId("settings-accounts-fediverse-la-provider_name")
}
function _effectiveIconPath() {
return root._trimmedString(instanceIconPath).length > 0 ? instanceIconPath : root.genericIconPath
}
function _applyIconPath(iconPath) {
instanceIconPath = iconPath
newAccount.setConfigurationValue("", "iconPath", _effectiveIconPath())
if (hasConfigured) {
newAccount.sync()
}
}
function updateInstanceIcon(iconPath) {
if (root._trimmedString(iconPath).length === 0) {
return
}
_applyIconPath(iconPath)
}
function configure() {
hasConfigured = true
var services = _serviceNames()
var providerDisplayName = _effectiveInstanceTitle()
newAccount.displayName = providerDisplayName
newAccount.setConfigurationValue("", "api/Host", apiHost)
newAccount.setConfigurationValue("", "FeedViewAutoSync", true)
newAccount.setConfigurationValue("", "instance/Title", providerDisplayName)
newAccount.setConfigurationValue("", "instance/Description", root._trimmedString(instanceDescription))
newAccount.setConfigurationValue("", "instance/IconUrl", root._trimmedString(instanceIconUrl))
_applyIconPath(_effectiveIconPath())
if (accountDescription.length > 0) {
newAccount.setConfigurationValue("", "description", accountDescription)
if (root._isFediverseAccountId(accountDescription)) {
newAccount.setConfigurationValue("", "default_credentials_username", accountDescription)
}
}
for (var i = 0; i < services.length; ++i) {
newAccount.enableWithService(services[i])
}
for (var j = 0; j < services.length; ++j) {
var service = services[j]
newAccount.setConfigurationValue(service, "api/Host", apiHost)
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/Host", oauthHost)
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/AuthPath", "oauth/authorize")
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/TokenPath", "oauth/token")
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/ResponseType", "code")
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/RedirectUri", root.callbackUri)
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/Scope", ["read", "write"])
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/ClientId", clientId)
newAccount.setConfigurationValue(service, "auth/oauth2/web_server/ClientSecret", clientSecret)
}
if (instanceIconUrl.length > 0 && instanceIconPath.length === 0) {
instanceIconCache.cacheIcon(apiHost, instanceIconUrl)
}
if (accountDescription.length > 0 || accessToken.length === 0) {
newAccount.sync()
return
}
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState !== XMLHttpRequest.DONE) {
return
}
if (xhr.status >= 200 && xhr.status < 300) {
try {
var response = JSON.parse(xhr.responseText)
var fetchedDescription = root._formatFediverseAccountId(root._extractAccountName(response), apiHost)
if (fetchedDescription.length > 0) {
accountDescription = fetchedDescription
newAccount.setConfigurationValue("", "description", fetchedDescription)
if (root._isFediverseAccountId(fetchedDescription)) {
newAccount.setConfigurationValue("", "default_credentials_username", fetchedDescription)
}
}
} catch (err) {
}
}
newAccount.sync()
}
xhr.open("GET", apiHost + "/api/v1/accounts/verify_credentials")
xhr.setRequestHeader("Authorization", "Bearer " + accessToken)
xhr.send()
}
}
}
Component {
id: settingsComponent
Dialog {
property alias accountId: settingsDisplay.accountId
acceptDestination: root.endDestination
acceptDestinationAction: root.endDestinationAction
acceptDestinationProperties: root.endDestinationProperties
acceptDestinationReplaceTarget: root.endDestinationReplaceTarget
backNavigation: false
onAccepted: {
root.delayDeletion = true
settingsDisplay.saveAccountAndSync()
}
SilicaFlickable {
anchors.fill: parent
contentHeight: header.height + settingsDisplay.height
DialogHeader {
id: header
}
FediverseSettingsDisplay {
id: settingsDisplay
anchors.top: header.bottom
accountManager: root.accountManager
accountProvider: root.accountProvider
autoEnableAccount: true
onAccountSaveCompleted: {
root.delayDeletion = false
}
}
VerticalScrollDecorator {}
}
}
}
}
|