forked from CCExtractor/taskwarrior-flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_service.dart
More file actions
530 lines (472 loc) · 14.1 KB
/
api_service.dart
File metadata and controls
530 lines (472 loc) · 14.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
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
// ignore_for_file: depend_on_referenced_packages, unnecessary_null_in_if_null_operators
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:taskwarrior/app/utils/taskchampion/credentials_storage.dart';
class Tasks {
final int id;
final String description;
final String? project;
final String status;
final String? uuid;
final double? urgency;
final String? priority;
final String? due;
final String? end;
final String entry;
final String? modified;
Tasks({
required this.id,
required this.description,
required this.project,
required this.status,
required this.uuid,
required this.urgency,
required this.priority,
required this.due,
required this.end,
required this.entry,
required this.modified,
});
factory Tasks.fromJson(Map<String, dynamic> json) {
return Tasks(
id: json['id'],
description: json['description'],
project: json['project'],
status: json['status'],
uuid: json['uuid'],
urgency: json['urgency'].toDouble(),
priority: json['priority'],
due: json['due'],
end: json['end'],
entry: json['entry'],
modified: json['modified'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'description': description,
'project': project,
'status': status,
'uuid': uuid,
'urgency': urgency,
'priority': priority,
'due': due,
'end': end,
'entry': entry,
'modified': modified,
};
}
}
String origin = 'http://localhost:8080';
Future<List<Tasks>> fetchTasks(String uuid, String encryptionSecret) async {
var baseUrl = await CredentialsStorage.getApiUrl();
try {
String url =
'$baseUrl/tasks?email=email&origin=$origin&UUID=$uuid&encryptionSecret=$encryptionSecret';
var response = await http.get(Uri.parse(url), headers: {
"Content-Type": "application/json",
}).timeout(const Duration(seconds: 10000));
if (response.statusCode == 200) {
List<dynamic> allTasks = jsonDecode(response.body);
debugPrint(allTasks.toString());
return allTasks.map((task) => Tasks.fromJson(task)).toList();
} else {
throw Exception('Failed to load tasks');
}
} catch (e) {
debugPrint('Error fetching tasks: $e');
return [];
}
}
Future<void> updateTasksInDatabase(List<Tasks> tasks) async {
var taskDatabase = TaskDatabase();
await taskDatabase.open();
// find tasks without UUID
List<Tasks> tasksWithoutUUID = await taskDatabase.findTasksWithoutUUIDs();
//add tasks without UUID to the server and delete them from database
for (var task in tasksWithoutUUID) {
try {
await addTaskAndDeleteFromDatabase(
task.description, task.project!, task.due!, task.priority!);
} catch (e) {
debugPrint('Failed to add task without UUID to server: $e');
}
}
// update existing tasks in db
for (var task in tasks) {
var existingTask = await taskDatabase.getTaskByUuid(task.uuid!);
if (existingTask != null) {
if (task.modified!.compareTo(existingTask.modified!) > 0) {
await taskDatabase.updateTask(task);
}
} else {
// add new tasks to db
await taskDatabase.insertTask(task);
}
}
var localTasks = await taskDatabase.fetchTasksFromDatabase();
var localTasksMap = {for (var task in localTasks) task.uuid: task};
for (var serverTask in tasks) {
var localTask = localTasksMap[serverTask.uuid];
if (localTask == null) {
// Task doesn't exist in the local database, insert it
await taskDatabase.insertTask(serverTask);
} else {
var serverTaskModifiedDate = DateTime.parse(serverTask.modified!);
var localTaskModifiedDate = DateTime.parse(localTask.modified!);
if (serverTaskModifiedDate.isAfter(localTaskModifiedDate)) {
// Server task is newer, update local database
await taskDatabase.updateTask(serverTask);
} else if (serverTaskModifiedDate.isBefore(localTaskModifiedDate)) {
// local task is newer, update server
await modifyTaskOnTaskwarrior(
localTask.description,
localTask.project!,
localTask.due!,
localTask.priority!,
localTask.status,
localTask.uuid!,
);
if (localTask.status == 'completed') {
completeTask('email', localTask.uuid!);
} else if (localTask.status == 'deleted') {
deleteTask('email', localTask.uuid!);
}
}
}
}
}
Future<void> deleteTask(String email, String taskUuid) async {
var baseUrl = await CredentialsStorage.getApiUrl();
var c = await CredentialsStorage.getClientId();
var e = await CredentialsStorage.getEncryptionSecret();
final url = Uri.parse('$baseUrl/delete-task');
final body = jsonEncode({
'email': email,
'encryptionSecret': e,
'UUID': c,
'taskuuid': taskUuid,
});
try {
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
},
body: body,
);
if (response.statusCode == 200) {
debugPrint('Task deleted successfully on server');
} else {
debugPrint('Failed to delete task: ${response.statusCode}');
}
} catch (e) {
debugPrint('Error deleting task: $e');
}
}
Future<void> completeTask(String email, String taskUuid) async {
var c = await CredentialsStorage.getClientId();
var e = await CredentialsStorage.getEncryptionSecret();
var baseUrl = await CredentialsStorage.getApiUrl();
final url = Uri.parse('$baseUrl/complete-task');
final body = jsonEncode({
'email': email,
'encryptionSecret': e,
'UUID': c,
'taskuuid': taskUuid,
});
try {
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
},
body: body,
);
if (response.statusCode == 200) {
debugPrint('Task completed successfully on server');
} else {
debugPrint('Failed to complete task: ${response.statusCode}');
ScaffoldMessenger.of(context as BuildContext).showSnackBar(const SnackBar(
content: Text(
"Failed to complete task!",
style: TextStyle(color: Colors.red),
)));
}
} catch (e) {
debugPrint('Error completing task: $e');
}
}
Future<void> addTaskAndDeleteFromDatabase(
String description, String project, String due, String priority) async {
var baseUrl = await CredentialsStorage.getApiUrl();
String apiUrl = '$baseUrl/add-task';
var c = await CredentialsStorage.getClientId();
var e = await CredentialsStorage.getEncryptionSecret();
debugPrint(c);
debugPrint(e);
await http.post(
Uri.parse(apiUrl),
headers: {
'Content-Type': 'text/plain',
},
body: jsonEncode({
'email': 'email',
'encryptionSecret': e,
'UUID': c,
'description': description,
'project': project,
'due': due,
'priority': priority,
}),
);
var taskDatabase = TaskDatabase();
await taskDatabase.open();
await taskDatabase._database!.delete(
'Tasks',
where: 'description = ? AND due = ? AND project = ? AND priority = ?',
whereArgs: [description, due, project, priority],
);
}
Future<void> modifyTaskOnTaskwarrior(String description, String project,
String due, String priority, String status, String taskuuid) async {
var baseUrl = await CredentialsStorage.getApiUrl();
var c = await CredentialsStorage.getClientId();
var e = await CredentialsStorage.getEncryptionSecret();
String apiUrl = '$baseUrl/modify-task';
debugPrint(c);
debugPrint(e);
final response = await http.post(
Uri.parse(apiUrl),
headers: {
'Content-Type': 'text/plain',
},
body: jsonEncode({
"email": "e",
"encryptionSecret": e,
"UUID": c,
"description": description,
"priority": priority,
"project": project,
"due": due,
"status": status,
"taskuuid": taskuuid,
}),
);
if (response.statusCode != 200) {
ScaffoldMessenger.of(context as BuildContext).showSnackBar(const SnackBar(
content: Text(
"Failed to update task!",
style: TextStyle(color: Colors.red),
)));
}
var taskDatabase = TaskDatabase();
await taskDatabase.open();
await taskDatabase._database!.delete(
'Tasks',
where: 'description = ? AND due = ? AND project = ? AND priority = ?',
whereArgs: [description, due, project, priority],
);
}
class TaskDatabase {
Database? _database;
Future<void> open() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'tasks.db');
_database = await openDatabase(path, version: 1,
onCreate: (Database db, version) async {
await db.execute('''
CREATE TABLE Tasks (
uuid TEXT PRIMARY KEY,
id INTEGER,
description TEXT,
project TEXT,
status TEXT,
urgency REAL,
priority TEXT,
due TEXT,
end TEXT,
entry TEXT,
modified TEXT
)
''');
});
}
Future<void> ensureDatabaseIsOpen() async {
if (_database == null) {
await open();
}
}
Future<List<Tasks>> fetchTasksFromDatabase() async {
await ensureDatabaseIsOpen();
final List<Map<String, dynamic>> maps = await _database!.query('Tasks');
var a = List.generate(maps.length, (i) {
return Tasks(
id: maps[i]['id'],
description: maps[i]['description'],
project: maps[i]['project'],
status: maps[i]['status'],
uuid: maps[i]['uuid'],
urgency: maps[i]['urgency'],
priority: maps[i]['priority'],
due: maps[i]['due'],
end: maps[i]['end'],
entry: maps[i]['entry'],
modified: maps[i]['modified'],
);
});
// debugPrint('Tasks from db');
// debugPrint(a.toString());
return a;
}
Future<void> deleteAllTasksInDB() async {
await ensureDatabaseIsOpen();
await _database!.delete('Tasks');
debugPrint('Deleted all tasks');
await open();
debugPrint('Created new task table');
}
Future<void> printDatabaseContents() async {
await ensureDatabaseIsOpen();
List<Map<String, dynamic>> maps = await _database!.query('Tasks');
for (var map in maps) {
map.forEach((key, value) {
debugPrint('Key: $key, Value: $value, Type: ${value.runtimeType}');
});
}
}
Future<void> insertTask(Tasks task) async {
await ensureDatabaseIsOpen();
await _database!.insert(
'Tasks',
task.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<void> updateTask(Tasks task) async {
await ensureDatabaseIsOpen();
await _database!.update(
'Tasks',
task.toJson(),
where: 'uuid = ?',
whereArgs: [task.uuid],
);
}
Future<Tasks?> getTaskByUuid(String uuid) async {
await ensureDatabaseIsOpen();
List<Map<String, dynamic>> maps = await _database!.query(
'Tasks',
where: 'uuid = ?',
whereArgs: [uuid],
);
if (maps.isNotEmpty) {
return Tasks.fromJson(maps.first);
} else {
return null;
}
}
Future<void> markTaskAsCompleted(String uuid) async {
await ensureDatabaseIsOpen();
await _database!.update(
'Tasks',
{'modified': (DateTime.now()).toIso8601String(), 'status': 'completed'},
where: 'uuid = ?',
whereArgs: [uuid],
);
debugPrint('task${uuid}completed');
debugPrint({DateTime.now().toIso8601String()}.toString());
}
Future<void> markTaskAsDeleted(String uuid) async {
await ensureDatabaseIsOpen();
await _database!.update(
'Tasks',
{'status': 'deleted'},
where: 'uuid = ?',
whereArgs: [uuid],
);
debugPrint('task${uuid}deleted');
}
Future<void> saveEditedTaskInDB(
String uuid,
String newDescription,
String newProject,
String newStatus,
String newPriority,
String newDue,
) async {
await ensureDatabaseIsOpen();
debugPrint('task${uuid}deleted');
await _database!.update(
'Tasks',
{
'description': newDescription,
'project': newProject,
'status': newStatus,
'priority': newPriority,
'due': newDue,
},
where: 'uuid = ?',
whereArgs: [uuid],
);
debugPrint('task${uuid}edited');
}
Future<List<Tasks>> findTasksWithoutUUIDs() async {
await ensureDatabaseIsOpen();
List<Map<String, dynamic>> maps = await _database!.query(
'Tasks',
where: 'uuid IS NULL OR uuid = ?',
whereArgs: [''],
);
return List.generate(maps.length, (i) {
return Tasks.fromJson(maps[i]);
});
}
Future<List<Tasks>> getTasksByProject(String project) async {
List<Map<String, dynamic>> maps = await _database!.query(
'Tasks',
where: 'project = ?',
whereArgs: [project],
);
return List.generate(maps.length, (i) {
return Tasks(
uuid: maps[i]['uuid'],
id: maps[i]['id'],
description: maps[i]['description'],
project: maps[i]['project'],
status: maps[i]['status'],
urgency: maps[i]['urgency'],
priority: maps[i]['priority'],
due: maps[i]['due'],
end: maps[i]['end'],
entry: maps[i]['entry'],
modified: maps[i]['modified'],
);
});
}
Future<List<String>> fetchUniqueProjects() async {
var taskDatabase = TaskDatabase();
await taskDatabase.open();
await taskDatabase.ensureDatabaseIsOpen();
final List<Map<String, dynamic>> result = await taskDatabase._database!
.rawQuery(
'SELECT DISTINCT project FROM Tasks WHERE project IS NOT NULL');
return result.map((row) => row['project'] as String).toList();
}
Future<List<Tasks>> searchTasks(String query) async {
final List<Map<String, dynamic>> maps = await _database!.query(
'tasks',
where: 'description LIKE ? OR project LIKE ?',
whereArgs: ['%$query%', '%$query%'],
);
return List.generate(maps.length, (i) {
return Tasks.fromJson(maps[i]);
});
}
Future<void> close() async {
await _database!.close();
}
}