-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathclient_browser.dart
More file actions
275 lines (243 loc) Β· 7.35 KB
/
client_browser.dart
File metadata and controls
275 lines (243 loc) Β· 7.35 KB
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
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
import 'package:http/http.dart' as http;
import 'package:http/browser_client.dart';
import 'package:web/web.dart' as web;
import 'client_mixin.dart';
import 'enums.dart';
import 'exception.dart';
import 'client_base.dart';
import 'input_file.dart';
import 'upload_progress.dart';
import 'response.dart';
ClientBase createClient({required String endPoint, required bool selfSigned}) =>
ClientBrowser(endPoint: endPoint, selfSigned: selfSigned);
class ClientBrowser extends ClientBase with ClientMixin {
static const int CHUNK_SIZE = 5 * 1024 * 1024;
String _endPoint;
Map<String, String>? _headers;
@override
late Map<String, String> config;
late BrowserClient _httpClient;
String? _endPointRealtime;
@override
String? get endPointRealtime => _endPointRealtime;
ClientBrowser({
String endPoint = 'https://cloud.appwrite.io/v1',
bool selfSigned = false,
}) : _endPoint = endPoint {
_httpClient = BrowserClient();
_endPointRealtime = endPoint
.replaceFirst('https://', 'wss://')
.replaceFirst('http://', 'ws://');
_headers = {
'content-type': 'application/json',
'x-sdk-name': 'Flutter',
'x-sdk-platform': 'client',
'x-sdk-language': 'flutter',
'x-sdk-version': '20.2.1',
'X-Appwrite-Response-Format': '1.8.0',
};
config = {};
assert(
_endPoint.startsWith(RegExp("http://|https://")),
"endPoint $_endPoint must start with 'http'",
);
init();
}
@override
String get endPoint => _endPoint;
/// Your project ID
@override
ClientBrowser setProject(value) {
config['project'] = value;
addHeader('X-Appwrite-Project', value);
return this;
}
/// Your secret JSON Web Token
@override
ClientBrowser setJWT(value) {
config['jWT'] = value;
addHeader('X-Appwrite-JWT', value);
return this;
}
@override
ClientBrowser setLocale(value) {
config['locale'] = value;
addHeader('X-Appwrite-Locale', value);
return this;
}
/// The user session to authenticate with
@override
ClientBrowser setSession(value) {
config['session'] = value;
addHeader('X-Appwrite-Session', value);
return this;
}
/// Your secret dev API key
@override
ClientBrowser setDevKey(value) {
config['devKey'] = value;
addHeader('X-Appwrite-Dev-Key', value);
return this;
}
@override
ClientBrowser setSelfSigned({bool status = true}) {
return this;
}
@override
ClientBrowser setEndpoint(String endPoint) {
if (!endPoint.startsWith('http://') && !endPoint.startsWith('https://')) {
throw AppwriteException('Invalid endpoint URL: $endPoint');
}
_endPoint = endPoint;
_endPointRealtime = endPoint
.replaceFirst('https://', 'wss://')
.replaceFirst('http://', 'ws://');
return this;
}
@override
ClientBrowser setEndPointRealtime(String endPoint) {
if (!endPoint.startsWith('ws://') && !endPoint.startsWith('wss://')) {
throw AppwriteException('Invalid realtime endpoint URL: $endPoint');
}
_endPointRealtime = endPoint;
return this;
}
@override
ClientBrowser addHeader(String key, String value) {
_headers![key] = value;
return this;
}
Future init() async {
final cookieFallback = web.window.localStorage.getItem('cookieFallback');
if (cookieFallback != null) {
addHeader('x-fallback-cookies', cookieFallback);
}
}
@override
Future<Response> chunkedUpload({
required String path,
required Map<String, dynamic> params,
required String paramName,
required String idParamName,
required Map<String, String> headers,
Function(UploadProgress)? onProgress,
}) async {
InputFile file = params[paramName];
if (file.bytes == null) {
throw AppwriteException("File bytes must be provided for Flutter web");
}
int size = file.bytes!.length;
late Response res;
if (size <= CHUNK_SIZE) {
params[paramName] = http.MultipartFile.fromBytes(
paramName,
file.bytes!,
filename: file.filename,
);
return call(
HttpMethod.post,
path: path,
params: params,
headers: headers,
);
}
var offset = 0;
if (idParamName.isNotEmpty) {
//make a request to check if a file already exists
try {
res = await call(
HttpMethod.get,
path: path + '/' + params[idParamName],
headers: headers,
);
final int chunksUploaded = res.data['chunksUploaded'] as int;
offset = chunksUploaded * CHUNK_SIZE;
} on AppwriteException catch (_) {}
}
while (offset < size) {
List<int> chunk = [];
final end = min(offset + CHUNK_SIZE, size);
chunk = file.bytes!.getRange(offset, end).toList();
params[paramName] = http.MultipartFile.fromBytes(
paramName,
chunk,
filename: file.filename,
);
headers['content-range'] =
'bytes $offset-${min<int>((offset + CHUNK_SIZE - 1), size - 1)}/$size';
res = await call(
HttpMethod.post,
path: path,
headers: headers,
params: params,
);
offset += CHUNK_SIZE;
if (offset < size) {
headers['x-appwrite-id'] = res.data['\$id'];
}
final progress = UploadProgress(
$id: res.data['\$id'] ?? '',
progress: min(offset, size) / size * 100,
sizeUploaded: min(offset, size),
chunksTotal: res.data['chunksTotal'] ?? 0,
chunksUploaded: res.data['chunksUploaded'] ?? 0,
);
onProgress?.call(progress);
}
return res;
}
@override
Future<Response> call(
HttpMethod method, {
String path = '',
Map<String, String> headers = const {},
Map<String, dynamic> params = const {},
ResponseType? responseType,
}) async {
await init();
// Combine headers to check for dev key
final combinedHeaders = {..._headers!, ...headers};
// Only include credentials when dev key is not set
if (combinedHeaders['X-Appwrite-Dev-Key'] == null) {
_httpClient.withCredentials = true;
} else {
_httpClient.withCredentials = false;
}
late http.Response res;
http.BaseRequest request = prepareRequest(
method,
uri: Uri.parse(_endPoint + path),
headers: combinedHeaders,
params: params,
);
try {
final streamedResponse = await _httpClient.send(request);
res = await toResponse(streamedResponse);
final cookieFallback = res.headers['x-fallback-cookies'];
if (cookieFallback != null) {
debugPrint(
'Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.',
);
addHeader('X-Fallback-Cookies', cookieFallback);
web.window.localStorage.setItem('cookieFallback', cookieFallback);
}
return prepareResponse(res, responseType: responseType);
} catch (e) {
if (e is AppwriteException) {
rethrow;
}
throw AppwriteException(e.toString());
}
}
@override
Future webAuth(Uri url, {String? callbackUrlScheme}) {
return FlutterWebAuth2.authenticate(
url: url.toString(),
callbackUrlScheme: "appwrite-callback-" + config['project']!,
options: const FlutterWebAuth2Options(useWebview: false),
);
}
}