-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathflutterflow_api_client.dart
More file actions
422 lines (391 loc) · 13.1 KB
/
flutterflow_api_client.dart
File metadata and controls
422 lines (391 loc) · 13.1 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
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
import 'dart:convert';
import 'dart:io';
import 'package:archive/archive_io.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path_util;
import 'flutterflow_ignore.dart';
const kDefaultEndpoint = 'https://api.flutterflow.io/v2';
/// The `FlutterFlowApi` class provides methods for exporting code from a
/// FlutterFlow project.
class FlutterFlowApi {
/// Exports the code from a FlutterFlow project.
///
/// * [token] is the FlutterFlow API token for accessing the project.
/// * [projectId] is the ID of the project to export.
/// * [destinationPath] is the path where the exported code will be saved.
/// * [includeAssets] flag indicates whether to include project assets
/// in the export.
/// * [endpoint] is the API endpoint to use for exporting the code.
/// * [branchName] is the name of the branch to export from (optional).
/// * [unzipToParentFolder] flag indicates whether to unzip the exported code
/// to the parent folder.
/// * [fix] flag indicates whether to fix any issues in the exported code.
/// * [exportAsModule] flag indicates whether to export the code as a module.
/// * [format] flag indicates whether to format the exported code.
/// * [exportAsDebug] flag indicates whether to export the code as debug for
/// local run.
/// * [environmentName] is the name of the environment to export the code for.
///
/// Returns a [Future] that completes with the path to the exported code, or
/// throws an error if the export fails.
static Future<String?> export({
required String token,
required String projectId,
required String destinationPath,
required bool includeAssets,
String endpoint = kDefaultEndpoint,
String? branchName,
String? environmentName,
String? commitHash,
bool unzipToParentFolder = false,
bool fix = false,
bool exportAsModule = false,
bool format = true,
bool exportAsDebug = false,
}) =>
exportCode(
token: token,
endpoint: endpoint,
projectId: projectId,
destinationPath: destinationPath,
includeAssets: includeAssets,
branchName: branchName,
commitHash: commitHash,
unzipToParentFolder: unzipToParentFolder,
fix: fix,
exportAsModule: exportAsModule,
format: format,
exportAsDebug: exportAsDebug,
);
}
Future<String?> exportCode({
required String token,
required String endpoint,
required String projectId,
required String destinationPath,
required bool includeAssets,
required bool unzipToParentFolder,
required bool fix,
required bool exportAsModule,
bool format = true,
String? branchName,
String? environmentName,
String? commitHash,
bool exportAsDebug = false,
}) async {
stderr.write('Downloading code with the FlutterFlow CLI...\n');
stderr.write('You are exporting project $projectId.\n');
stderr.write(
'${branchName != null ? 'Branch: $branchName ' : ''}${environmentName != null ? 'Environment: $environmentName ' : ''}${commitHash != null ? 'Commit: $commitHash' : ''}\n');
if (exportAsDebug && exportAsModule) {
throw 'Cannot export as module and debug at the same time.';
}
final endpointUrl = Uri.parse(endpoint);
final client = http.Client();
String? folderName;
try {
final result = await _callExport(
client: client,
token: token,
endpoint: endpointUrl,
projectId: projectId,
branchName: branchName,
environmentName: environmentName,
commitHash: commitHash,
exportAsModule: exportAsModule,
includeAssets: includeAssets,
format: format,
exportAsDebug: exportAsDebug,
);
// Download actual code
final List<int> projectZipBytes;
if (result['download_url'] != null) {
final response = await client.get(Uri.parse(result['download_url']));
if (response.statusCode != 200) {
throw 'Failed to download project zip from URL: ${response.statusCode}';
}
projectZipBytes = response.bodyBytes;
} else {
projectZipBytes = base64Decode(result['project_zip']);
}
final projectFolder = ZipDecoder().decodeBytes(projectZipBytes);
extractArchiveTo(projectFolder, destinationPath, unzipToParentFolder);
final postCodeGenerationFutures = <Future>[
if (fix)
_runFix(
destinationPath: destinationPath,
projectFolder: projectFolder,
unzipToParentFolder: unzipToParentFolder,
),
if (includeAssets)
_downloadAssets(
client: client,
destinationPath: destinationPath,
assetDescriptions: result['assets'],
unzipToParentFolder: unzipToParentFolder,
),
];
if (postCodeGenerationFutures.isNotEmpty) {
await Future.wait(postCodeGenerationFutures);
}
var fileName = projectFolder.first.name;
folderName = fileName.substring(0, fileName.indexOf('/'));
} finally {
client.close();
}
stderr.write('All done!\n');
return folderName;
}
// Extract files to the specified directory without a project-named
// parent folder.
void extractArchiveTo(
Archive projectFolder, String destinationPath, bool unzipToParentFolder) {
final ignore = FlutterFlowIgnore(path: destinationPath);
for (final file in projectFolder.files) {
if (file.isFile) {
final relativeFilename =
path_util.joinAll(path_util.split(file.name).sublist(1));
// Found on .flutterflowignore, move on.
if (ignore.matches(unzipToParentFolder ? file.name : relativeFilename)) {
stderr.write('Ignoring $relativeFilename, file remained unchanged.\n');
continue;
}
// Remove the `<project>` prefix from paths if needed.
final path = path_util.join(
destinationPath, unzipToParentFolder ? file.name : relativeFilename);
final fileOut = File(path);
fileOut.createSync(recursive: true);
fileOut.writeAsBytesSync(file.content as List<int>);
}
}
}
Future<dynamic> _callExport({
required final http.Client client,
required String token,
required Uri endpoint,
required String projectId,
String? branchName,
String? environmentName,
String? commitHash,
required bool exportAsModule,
required bool includeAssets,
required bool format,
required bool exportAsDebug,
}) async {
final body = jsonEncode({
'project_id': projectId,
if (branchName != null) 'branch_name': branchName,
if (environmentName != null) 'environment_name': environmentName,
if (commitHash != null) 'commit': {'path': 'commits/$commitHash'},
'export_as_module': exportAsModule,
'include_assets_map': includeAssets,
'format': format,
'export_as_debug': exportAsDebug,
});
return await _callEndpoint(
client: client,
token: token,
url: Uri.parse('$endpoint/exportCode'),
body: body,
);
}
Future<dynamic> _callEndpoint({
required final http.Client client,
required String token,
required Uri url,
required String body,
}) async {
final response = await client.post(
url,
body: body,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 429) {
throw 'Too many requests. Please try again later.';
}
if (response.statusCode != 200) {
stderr.write('Unexpected error from the server.\n');
stderr.write('Status: ${response.statusCode}\n');
stderr.write('Body: ${response.body}\n');
throw ('Unexpected error from the server.');
}
final parsedResponse = jsonDecode(response.body);
final success = parsedResponse['success'];
if (success == null || !success) {
if (parsedResponse['reason'] != null &&
parsedResponse['reason'].isNotEmpty) {
stderr.write('Error: ${parsedResponse['reason']}.\n');
throw 'Error: ${parsedResponse['reason']}.';
} else {
stderr.write('Unexpected server error.\n');
throw 'Unexpected server error.';
}
}
return parsedResponse['value'];
}
// TODO: limit the number of parallel downloads.
Future _downloadAssets({
required final http.Client client,
required String destinationPath,
required List<dynamic> assetDescriptions,
required unzipToParentFolder,
}) async {
final futures = assetDescriptions.map((assetDescription) async {
String path = assetDescription['path'];
if (!unzipToParentFolder) {
path = path_util.joinAll(
path_util.split(path).sublist(1),
);
}
final url = assetDescription['url'];
final fileDest = path_util.join(destinationPath, path);
try {
final response = await client.get(Uri.parse(url));
if (response.statusCode >= 200 && response.statusCode < 300) {
final file = File(fileDest);
await file.parent.create(recursive: true);
await file.writeAsBytes(response.bodyBytes);
} else {
stderr.write('Error downloading asset $path. This is probably fine.\n');
}
} catch (_) {
stderr.write('Error downloading asset $path. This is probably fine.\n');
}
});
stderr.write('Downloading assets...\n');
await Future.wait(futures);
}
Future _runFix({
required String destinationPath,
required Archive projectFolder,
required unzipToParentFolder,
}) async {
try {
if (projectFolder.isEmpty) {
return;
}
final firstFilePath = projectFolder.files.first.name;
final directory = path_util.split(firstFilePath).first;
final workingDirectory = unzipToParentFolder
? path_util.join(destinationPath, directory)
: destinationPath;
stderr.write('Running flutter pub get...\n');
final pubGetResult = await Process.run(
'flutter',
['pub', 'get'],
workingDirectory: workingDirectory,
runInShell: true,
stdoutEncoding: utf8,
stderrEncoding: utf8,
);
if (pubGetResult.exitCode != 0) {
stderr.write(
'"flutter pub get" failed with code ${pubGetResult.exitCode}, stderr:\n${pubGetResult.stderr}\n');
return;
}
stderr.write('Running dart fix...\n');
final fixDirectory = unzipToParentFolder ? directory : '';
final dartFixResult = await Process.run(
'dart',
['fix', '--apply', fixDirectory],
workingDirectory: destinationPath,
runInShell: true,
stdoutEncoding: utf8,
stderrEncoding: utf8,
);
if (dartFixResult.exitCode != 0) {
stderr.write(
'"dart fix" failed with code ${dartFixResult.exitCode}, stderr:\n${dartFixResult.stderr}\n');
}
} catch (e) {
stderr.write('Error running "dart fix": $e\n');
}
}
Future firebaseDeploy({
required String token,
required String projectId,
bool appendRules = false,
String endpoint = kDefaultEndpoint,
}) async {
final endpointUrl = Uri.parse(endpoint);
final body = jsonEncode({
'project_id': projectId,
'append_rules': appendRules,
});
final result = await _callEndpoint(
client: http.Client(),
token: token,
url: Uri.https(
endpointUrl.host, '${endpointUrl.path}/exportFirebaseDeployCode'),
body: body,
);
// Download actual code
final projectZipBytes = base64Decode(result['firebase_zip']);
final firebaseProjectId = result['firebase_project_id'];
final projectFolder = ZipDecoder().decodeBytes(projectZipBytes);
Directory? tmpFolder;
try {
tmpFolder =
Directory.systemTemp.createTempSync('${projectId}_$firebaseProjectId');
extractArchiveTo(projectFolder, tmpFolder.path, false);
final firebaseDir = '${tmpFolder.path}/firebase';
// Install required modules for deployment.
await Process.run(
'npm',
['install'],
workingDirectory: '$firebaseDir/functions',
runInShell: true,
stdoutEncoding: utf8,
stderrEncoding: utf8,
);
// This directory only exists if there were custom cloud functions.
if (Directory('$firebaseDir/custom_cloud_functions').existsSync()) {
await Process.run(
'npm',
['install'],
workingDirectory: '$firebaseDir/custom_cloud_functions',
runInShell: true,
stdoutEncoding: utf8,
stderrEncoding: utf8,
);
}
stderr.write('Initializing firebase...\n');
await Process.run(
'firebase',
['use', firebaseProjectId],
workingDirectory: firebaseDir,
runInShell: true,
);
final initHostingProcess = await Process.start(
'firebase',
['init', 'hosting'],
workingDirectory: firebaseDir,
runInShell: true,
);
final initHostingInputStream = Stream.periodic(
Duration(milliseconds: 100),
(count) => utf8.encode('\n'),
);
initHostingProcess.stdin.addStream(initHostingInputStream);
// Make sure hosting is initialized before deploying.
await initHostingProcess.exitCode;
final deployProcess = await Process.start(
'firebase',
['deploy', '--project', firebaseProjectId],
workingDirectory: firebaseDir,
runInShell: true,
);
// There may be a need for the user to interactively provide inputs.
deployProcess.stdout.transform(utf8.decoder).forEach(print);
deployProcess.stdin.addStream(stdin);
final exitCode = await deployProcess.exitCode;
if (exitCode != 0) {
stderr.write('Failed to deploy to Firebase.\n');
}
} finally {
tmpFolder?.deleteSync(recursive: true);
}
}