-
Notifications
You must be signed in to change notification settings - Fork 374
/
services.tsx
198 lines (174 loc) · 4.7 KB
/
services.tsx
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
import InAppBrowser from 'react-native-inappbrowser-reborn'
import { MsgrState } from './context'
import { Alert } from 'react-native'
import { useAccount } from './hooks'
import * as middleware from '@berty-tech/grpc-bridge/middleware'
import { EOF, Service } from '@berty-tech/grpc-bridge'
import { bridge as rpcBridge } from '@berty-tech/grpc-bridge/rpc'
import RNFS from 'react-native-fs'
import RNFetchBlob from 'rn-fetch-blob'
import beapi from '@berty-tech/api'
import Share from 'react-native-share'
import { Buffer } from 'buffer'
export enum serviceTypes {
Replication = 'rpl',
}
export const serviceNames: { [key: string]: string } = {
[serviceTypes.Replication]: 'Replication service', // TODO: i18n
}
export const bertyOperatedServer = 'https://services.berty.tech/'
export const useAccountServices = (): Array<beapi.messenger.IServiceToken> => {
const account = useAccount()
if (!account?.serviceTokens) {
return []
}
return Object.values(
account.serviceTokens.reduce(
(tokens, t) => ({ ...tokens, [`${t.authenticationUrl}-${t.serviceType}`]: t }),
{},
),
)
}
export const servicesAuthViaDefault = async (ctx: MsgrState): Promise<void> => {
return servicesAuthViaURL(ctx, bertyOperatedServer)
}
export const servicesAuthViaURL = async (ctx: MsgrState, url: string): Promise<void> => {
if (!ctx.protocolClient) {
return
}
let authURL = ''
try {
// PKCE OAuth flow
const resp = await ctx.protocolClient?.authServiceInitFlow({
authUrl: url,
})
authURL = resp.url
if (!resp.secureUrl) {
let allowNonSecure = false
await new Promise((resolve) => {
Alert.alert(
'Security warning',
'The provided URL is using a non secure connection, do you want to continue?',
[
{
text: 'Access page',
onPress: () => {
allowNonSecure = true
resolve()
},
},
{ text: 'Go back', onPress: resolve },
],
)
})
if (!allowNonSecure) {
return
}
}
} catch {
Alert.alert('The provided URL is not supported')
return
}
if (await InAppBrowser.isAvailable()) {
try {
const response: any = await InAppBrowser.openAuth(authURL, 'berty://', {
dismissButtonStyle: 'cancel',
readerMode: false,
modalPresentationStyle: 'pageSheet',
modalEnabled: true,
showTitle: true,
enableDefaultShare: false,
ephemeralWebSession: true,
// forceCloseOnRedirection: false,
})
if (!response.url) {
return
}
const responseURL = response.url
await ctx.protocolClient?.authServiceCompleteFlow({
callbackUrl: responseURL,
})
} catch (e) {
console.warn(e)
}
}
}
export const replicateGroup = async (
ctx: MsgrState,
conversationPublicKey: string,
tokenID: string,
): Promise<void> => {
if (
!(await new Promise((resolve) => {
Alert.alert(
'Privacy warning',
"The data for this conversation will be replicated on the selected server, while the messages and their metadata won't be readable by anyone outside the conversation this will lead to a decreased privacy protection for all the members' activity, do you want to proceed?",
[
{
text: 'Replicate conversation contents',
onPress: () => {
resolve(true)
},
},
{ text: 'Cancel', onPress: () => resolve(false) },
],
)
}))
) {
return
}
if (!ctx.client) {
return
}
try {
await ctx.client?.replicationServiceRegisterGroup({
tokenId: tokenID,
conversationPublicKey: conversationPublicKey,
})
Alert.alert(
'Conversation registered on server',
'The conversation contents will be replicated from now on',
)
} catch (e) {
console.warn(e)
Alert.alert(
'Conversation not registered',
'An error occurred while registering the conversation on the server',
)
}
}
export const exportAccountToFile = async () => {
const messengerMiddlewares = middleware.chain(
__DEV__ ? middleware.logger.create('MESSENGER') : null,
)
const messengerClient = Service(beapi.messenger.MessengerService, rpcBridge, messengerMiddlewares)
const outFile = RNFS.TemporaryDirectoryPath + 'berty-' + String(Date.now()).slice(-4) + '.tar'
const outputStream = await RNFetchBlob.fs.writeStream(outFile, 'base64')
await messengerClient
.instanceExportData({})
.then((stream) => {
stream.onMessage(async (res) => {
if (!res || !res.exportedData) {
return
}
await outputStream.write(Buffer.from(res.exportedData).toString('base64'))
})
return stream.start()
})
.then(async () => {
await outputStream.close()
await Share.open({
url: `file://${outFile}`,
type: 'application/x-tar',
})
})
.catch(async (err) => {
if (err === EOF) {
} else {
console.warn(err)
}
})
.finally(async () => {
await RNFS.unlink(outFile)
})
}