-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdatabase_helper.dart
More file actions
1377 lines (1225 loc) · 40.7 KB
/
database_helper.dart
File metadata and controls
1377 lines (1225 loc) · 40.7 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
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:wispar/models/crossref_journals_works_models.dart';
import 'package:wispar/widgets/publication_card/publication_card.dart';
import 'package:wispar/widgets/downloaded_card.dart';
import 'package:wispar/models/journal_entity.dart';
import 'package:wispar/models/feed_filter_entity.dart';
import 'package:wispar/services/string_format_helper.dart';
import 'dart:convert';
import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wispar/services/logs_helper.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static const platform = MethodChannel('app.wispar.wispar/database_access');
static Future<String?> resolveBookmarkPath(String? path) async {
if (path == null) return null;
if (Platform.isIOS) {
try {
final resolvedPath =
await platform.invokeMethod('resolveCustomPath', path);
return resolvedPath;
} catch (e) {
return null;
}
} else {
return path;
}
}
static Database? _database;
final logger = LogsService().logger;
Future<Database> get database async {
if (_database != null) return _database!;
_database = await initDatabase();
return _database!;
}
Future<String> getDbPath() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? customPath = prefs.getString('customDatabasePath');
String? bookmark = prefs.getString('customDatabaseBookmark');
if (Platform.isIOS && bookmark != null) {
final resolved = await resolveBookmarkPath(bookmark);
if (resolved != null) customPath = resolved;
}
String defaultPath = await getDatabasesPath();
if (Platform.isWindows) {
final dir = await getApplicationSupportDirectory();
defaultPath = dir.path;
}
final databasePath = join(customPath ?? defaultPath, 'wispar.db');
return databasePath;
}
Future<Database> initDatabase() async {
String databasePath = await getDbPath();
return openDatabase(databasePath, version: 9, onOpen: (db) async {
await db.execute('PRAGMA foreign_keys = ON');
}, onCreate: (db, version) async {
await db.execute('PRAGMA foreign_keys = ON');
// Create the journals table
await db.execute('''
CREATE TABLE journals (
journal_id INTEGER PRIMARY KEY AUTOINCREMENT,
issn TEXT,
title TEXT,
publisher TEXT,
dateFollowed TEXT,
lastUpdated TEXT
)
''');
// Create the journal_issns table
await db.execute('''
CREATE TABLE journal_issns (
issn TEXT PRIMARY KEY,
journal_id INTEGER,
FOREIGN KEY (journal_id) REFERENCES journals(journal_id)
)
''');
// Create the 'articles' table
await db.execute('''
CREATE TABLE articles (
article_id INTEGER PRIMARY KEY AUTOINCREMENT,
doi TEXT,
title TEXT,
translatedTitle TEXT,
abstract TEXT,
translatedAbstract TEXT,
publishedDate TEXT,
authors TEXT,
url TEXT,
license TEXT,
licenseName TEXT,
dateLiked TEXT,
dateDownloaded TEXT,
pdfPath TEXT,
dateCached TEXT,
isSavedQuery INTEGER,
isHidden INTEGER,
query_id INTEGER,
graphAbstractPath,
journal_id,
FOREIGN KEY (journal_id) REFERENCES journals(journal_id)
)
''');
// Create the table for saved queries
await db.execute('''
CREATE TABLE savedQueries (
query_id INTEGER PRIMARY KEY AUTOINCREMENT,
queryName TEXT,
queryParams TEXT,
dateSaved TEXT,
includeInFeed INTEGER,
lastFetched TEXT,
queryProvider TEXT
)
''');
// Create the feed filters table
await db.execute('''
CREATE TABLE feed_filters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
includedKeywords TEXT,
excludedKeywords TEXT,
journals TEXT,
dateCreated TEXT DEFAULT CURRENT_TIMESTAMP
)
''');
await db.execute('''
CREATE TABLE knownUrls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
proxySuccess INTEGER
)
''');
}, onUpgrade: (db, oldVersion, newVersion) async {
logger.info("Upgrading DB from $oldVersion to $newVersion");
await db.execute('PRAGMA foreign_keys = ON');
if (oldVersion < 2) {
// Ads the new column to the savedQueries table
await db.execute('''
ALTER TABLE savedQueries ADD COLUMN includeInFeed INTEGER;
''');
await db.execute('''
ALTER TABLE savedQueries ADD COLUMN lastFetched TEXT;
''');
await db.execute('''
ALTER TABLE articles ADD COLUMN isSavedQuery INTEGER;
''');
await db.execute('''
ALTER TABLE articles ADD COLUMN query_id INTEGER;
''');
}
if (oldVersion < 3) {
List<Map<String, dynamic>> articles =
await db.rawQuery('SELECT article_id, pdfPath FROM articles');
for (var article in articles) {
String pdfPath = article['pdfPath'] ?? '';
String filename = pdfPath.split('/').last;
await db.rawUpdate(
'UPDATE articles SET pdfPath = ? WHERE article_id = ?',
[filename, article['article_id']]);
}
await db.execute('''
ALTER TABLE savedQueries ADD COLUMN queryProvider TEXT;
''');
await db.rawUpdate('''
UPDATE savedQueries SET queryProvider = 'Crossref';
''');
}
if (oldVersion < 4) {
await db.execute('''
CREATE TABLE journal_issns (
issn TEXT PRIMARY KEY,
journal_id INTEGER,
FOREIGN KEY (journal_id) REFERENCES journals(journal_id)
);
''');
// Migrate existing ISSNs
final journals = await db.query('journals');
for (final journal in journals) {
final issn = journal['issn'];
final journalId = journal['journal_id'];
if (issn != null) {
await db.insert('journal_issns', {
'issn': issn,
'journal_id': journalId,
});
}
}
// I should probably drop the issn column from the journals table
}
if (oldVersion < 5) {
await db.execute('''
ALTER TABLE articles ADD COLUMN isHidden INTEGER;
''');
}
if (oldVersion < 6) {
await db.execute('''
CREATE TABLE feed_filters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
includedKeywords TEXT,
excludedKeywords TEXT,
journals TEXT,
dateCreated TEXT DEFAULT CURRENT_TIMESTAMP
)
''');
final List<Map<String, dynamic>> articles =
await db.query('articles', columns: ['doi', 'title', 'abstract']);
for (final article in articles) {
final String doi = article['doi'];
final String? rawTitle = article['title'];
final String? rawAbstract = article['abstract'];
String? cleanedTitle = rawTitle != null ? cleanTitle(rawTitle) : null;
String? cleanedAbstract =
rawAbstract != null ? cleanAbstract(rawAbstract) : null;
await db.update(
'articles',
{
if (cleanedTitle != null) 'title': cleanedTitle,
if (cleanedAbstract != null) 'abstract': cleanedAbstract,
},
where: 'doi = ?',
whereArgs: [doi],
);
}
}
if (oldVersion < 7) {
await db.execute('''
ALTER TABLE articles ADD COLUMN translatedTitle TEXT;
''');
await db.execute('''
ALTER TABLE articles ADD COLUMN translatedAbstract TEXT;
''');
}
if (oldVersion < 8) {
await db.execute('''
CREATE TABLE knownUrls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
proxySuccess INTEGER
)
''');
}
if (oldVersion < 9) {
await db.execute('''
ALTER TABLE articles ADD COLUMN graphAbstractPath TEXT;
''');
}
});
}
Future<void> closeDatabase() async {
if (_database != null) {
await _database!.close();
_database = null;
logger.info('Database connection closed and reference cleared.');
}
}
// Functions for journals
Future<void> insertJournal(Journal journal) async {
final db = await database;
final existingIssn = await db.query(
'journal_issns',
where: 'issn IN (${List.filled(journal.issn.length, '?').join(',')})',
whereArgs: journal.issn,
);
if (existingIssn.isNotEmpty) {
final int journalId = existingIssn.first['journal_id'] as int;
final journalMap = await db.query(
'journals',
where: 'journal_id = ?',
whereArgs: [journalId],
);
if (journalMap.isNotEmpty && journalMap.first['dateFollowed'] == null) {
await db.update(
'journals',
{
'dateFollowed': DateTime.now().toIso8601String().substring(0, 10),
'title': journal.title,
'publisher': journal.publisher,
},
where: 'journal_id = ?',
whereArgs: [journalId],
);
await db.delete(
'journal_issns',
where: 'journal_id = ?',
whereArgs: [journalId],
);
for (final issn in journal.issn) {
await db.insert(
'journal_issns',
{
'issn': issn,
'journal_id': journalId,
},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
}
} else {
final journalId = await db.insert('journals', journal.toMap());
for (final issn in journal.issn) {
await db.insert(
'journal_issns',
{
'issn': issn,
'journal_id': journalId,
},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
}
}
Future<List<Journal>> getFollowedJournals() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.rawQuery('''
SELECT j.journal_id, j.title, j.publisher, j.dateFollowed, j.lastUpdated,
GROUP_CONCAT(ji.issn) as issns
FROM journals j
JOIN journal_issns ji ON j.journal_id = ji.journal_id
WHERE j.dateFollowed IS NOT NULL
GROUP BY j.journal_id
''');
return List.generate(maps.length, (i) {
return Journal(
id: maps[i]['journal_id'],
issn: (maps[i]['issns'] as String).split(','),
title: maps[i]['title'],
publisher: maps[i]['publisher'],
dateFollowed: maps[i]['dateFollowed'],
lastUpdated: maps[i]['lastUpdated'],
);
});
}
Future<List<Journal>> getAllJournals() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.rawQuery('''
SELECT j.journal_id, j.title, j.publisher, j.dateFollowed, j.lastUpdated,
GROUP_CONCAT(ji.issn) as issns
FROM journals j
JOIN journal_issns ji ON j.journal_id = ji.journal_id
GROUP BY j.journal_id
''');
return List.generate(maps.length, (i) {
return Journal(
id: maps[i]['journal_id'],
issn: (maps[i]['issns'] as String).split(','),
title: maps[i]['title'],
publisher: maps[i]['publisher'] ?? '',
dateFollowed: maps[i]['dateFollowed'],
lastUpdated: maps[i]['lastUpdated'],
);
});
}
Future<int?> getJournalIdByIssns(List<String> issns) async {
final db = await database;
String whereClause =
'issn IN (${List.filled(issns.length, '?').join(', ')})';
List<Map<String, dynamic>> result = await db.query(
'journal_issns',
columns: ['journal_id'],
where: whereClause,
whereArgs: issns,
);
if (result.isNotEmpty) {
return result.first['journal_id'] as int;
}
return null;
}
Future<String?> getJournalTitleById(int journalId) async {
final db = await database;
final result = await db.query(
'journals',
columns: ['title'],
where: 'journal_id = ?',
whereArgs: [journalId],
);
if (result.isNotEmpty) {
return result.first['title'] as String?;
}
return null;
}
Future<List<String>> getIssnsByJournalId(int journalId) async {
final db = await database;
final result = await db.query(
'journal_issns',
columns: ['issn'],
where: 'journal_id = ?',
whereArgs: [journalId],
);
if (result.isNotEmpty) {
return result.map((row) => row['issn'] as String).toList();
}
return [];
}
Future<void> removeJournal(List<String> issns) async {
final db = await database;
int? journalId = await getJournalIdByIssns(issns);
if (journalId != null) {
await db.update(
'articles',
{'dateCached': null},
where: 'journal_id = ?',
whereArgs: [journalId],
);
await db.update(
'journals',
{'dateFollowed': null, 'lastUpdated': null},
where: 'journal_id = ?',
whereArgs: [journalId],
);
}
}
Future<bool> isJournalFollowed(int journalId) async {
final db = await database;
final query = 'SELECT COUNT(*) FROM journals '
'WHERE journal_id = ? AND dateFollowed IS NOT NULL';
final count = Sqflite.firstIntValue(await db.rawQuery(
query,
[journalId],
))!;
return count > 0;
}
Future<void> updateJournalLastUpdated(int journalId) async {
final db = await database;
await db.update(
'journals',
{'lastUpdated': DateTime.now().toIso8601String()},
where: 'journal_id = ?',
whereArgs: [journalId],
);
}
// Functions for articles
Future<void> insertArticle(
PublicationCard publicationCard, {
bool isLiked = false,
bool isDownloaded = false,
bool isCached = false,
bool isSavedQuery = false,
int? queryId,
String pdfPath = '',
}) async {
final db = await database;
// Check if the article with the given DOI already exists
final List<Map<String, dynamic>> existingArticle = await db.query(
'articles',
columns: ['article_id', 'dateLiked', 'dateDownloaded', 'dateCached'],
where: 'doi = ?',
whereArgs: [publicationCard.doi],
);
if (existingArticle.isNotEmpty) {
// Article already exists, update the timestamp based on parameters
final Map<String, dynamic> updateData = {};
if (isLiked && existingArticle[0]['dateLiked'] == null) {
updateData['dateLiked'] =
DateTime.now().toIso8601String().substring(0, 10);
}
if (isDownloaded && existingArticle[0]['dateDownloaded'] == null) {
updateData['dateDownloaded'] =
DateTime.now().toIso8601String().substring(0, 10);
updateData['pdfPath'] = pdfPath;
}
if (isCached && existingArticle[0]['dateCached'] == null) {
updateData['dateCached'] = DateTime.now().toIso8601String();
}
if (updateData.isNotEmpty) {
await db.update(
'articles',
updateData,
where: 'article_id = ?',
whereArgs: [existingArticle[0]['article_id']],
);
}
} else {
int? journalId = await getJournalIdByIssns(publicationCard.issn);
if (journalId == null) {
// Journal not found, insert it
final Map<String, dynamic> journalData = {
'title': publicationCard.journalTitle,
'publisher': publicationCard.publisher,
};
journalId = await db.insert('journals', journalData);
// Insert the ISSNs into the journal_issns table
for (final issn in publicationCard.issn) {
await db.insert(
'journal_issns',
{
'issn': issn,
'journal_id': journalId,
},
conflictAlgorithm: ConflictAlgorithm.ignore,
);
}
}
// Insert the article
await db.insert('articles', {
'doi': publicationCard.doi,
'title': publicationCard.title,
'abstract': publicationCard.abstract,
'publishedDate': publicationCard.publishedDate?.toIso8601String(),
'authors': jsonEncode(publicationCard.authors
.map((author) => author.toJson())
.toList()), // Serialize authors to JSON
'url': publicationCard.url,
'license': publicationCard.license,
'licenseName': publicationCard.licenseName,
'dateLiked':
isLiked ? DateTime.now().toIso8601String().substring(0, 10) : null,
'dateDownloaded': isDownloaded
? DateTime.now().toIso8601String().substring(0, 10)
: null,
'pdfPath': pdfPath.isNotEmpty ? pdfPath : '',
'dateCached': isCached ? DateTime.now().toIso8601String() : null,
'isSavedQuery': isSavedQuery ? 1 : 0,
'query_id': queryId,
'journal_id': journalId,
});
}
}
Future<List<PublicationCard>> getFavoriteArticles() async {
final Database db = await DatabaseHelper().database;
final List<Map<String, dynamic>> maps = await db.rawQuery('''
SELECT articles.*, journals.title AS journalTitle,
GROUP_CONCAT(journal_issns.issn) AS issns
FROM articles
LEFT JOIN journals ON articles.journal_id = journals.journal_id
LEFT JOIN journal_issns ON journals.journal_id = journal_issns.journal_id
WHERE articles.dateLiked IS NOT NULL
GROUP BY articles.article_id
''');
return List.generate(maps.length, (i) {
List<String> issns = (maps[i]['issns'] as String?)?.split(',') ?? [];
return PublicationCard(
doi: maps[i]['doi'],
title: maps[i]['title'],
issn: issns,
abstract: maps[i]['abstract'],
publishedDate: DateTime.parse(maps[i]['publishedDate']),
authors: List<PublicationAuthor>.from(
(jsonDecode(maps[i]['authors']) as List<dynamic>)
.map((authorJson) => PublicationAuthor.fromJson(authorJson)),
),
dateLiked: maps[i]['dateLiked'],
journalTitle: maps[i]['journalTitle'],
url: maps[i]['url'],
license: maps[i]['license'],
licenseName: maps[i]['licenseName'],
);
});
}
Future<int> getArticleCount() async {
final db = await database;
final result = await db.rawQuery('SELECT COUNT(*) as count FROM articles');
return Sqflite.firstIntValue(result) ?? 0;
}
Future<void> removeFavorite(String doi) async {
final db = await database;
await db.update(
'articles',
{'dateLiked': null},
where: 'doi = ?',
whereArgs: [doi],
);
}
Future<bool> isArticleFavorite(String doi) async {
final db = await database;
final count = Sqflite.firstIntValue(await db.rawQuery(
'SELECT COUNT(*) FROM articles WHERE doi = ? AND dateLiked IS NOT NULL',
[doi],
))!;
return count > 0;
}
Future<void> insertCachedPublication(PublicationCard publicationCard) async {
final db = await database;
final List<Map<String, dynamic>> publicationMaps = await db.query(
'articles',
columns: ['article_id', 'dateCached'],
where: 'doi = ?',
whereArgs: [publicationCard.doi],
);
if (publicationMaps.isNotEmpty) {
// Publication found, retrieve its ID
final int articleId = publicationMaps.first['article_id'];
// If the publication wasn't cached before, update the dateCached
if (publicationMaps.first['dateCached'] == null) {
final int? journalId = await getJournalIdByIssns(publicationCard.issn);
if (journalId == null) {
throw Exception('No matching journal found for the given ISSNs.');
}
await db.update(
'articles',
{
'dateCached': DateTime.now().toIso8601String(),
'title': publicationCard.title,
'abstract': publicationCard.abstract,
'journal_id': journalId,
'publishedDate': publicationCard.publishedDate?.toIso8601String(),
'authors': jsonEncode(
publicationCard.authors.map((author) => author.toJson()).toList(),
),
},
where: 'article_id = ?',
whereArgs: [articleId],
);
}
} else {
// Publication not found, insert it
final int? journalId = await getJournalIdByIssns(publicationCard.issn);
if (journalId == null) {
throw Exception('No matching journal found for the given ISSNs.');
}
await db.insert('articles', {
'doi': publicationCard.doi,
'title': publicationCard.title,
'abstract': publicationCard.abstract,
'journal_id': journalId,
'publishedDate': publicationCard.publishedDate?.toIso8601String(),
'authors': jsonEncode(
publicationCard.authors.map((author) => author.toJson()).toList(),
),
'dateCached': DateTime.now().toIso8601String(),
});
}
}
Future<List<PublicationCard>> getCachedPublications() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.rawQuery('''
SELECT
articles.*,
journals.title AS journalTitle,
GROUP_CONCAT(journal_issns.issn) AS issns
FROM articles
JOIN journals ON articles.journal_id = journals.journal_id
LEFT JOIN journal_issns ON articles.journal_id = journal_issns.journal_id
WHERE articles.dateCached IS NOT NULL
AND (articles.isHidden = 0 OR articles.isHidden IS NULL)
GROUP BY articles.doi
''');
return maps.map((map) {
final List<String> issns = (map['issns'] as String?)?.split(',') ?? [];
return PublicationCard(
doi: map['doi'],
title: map['title'],
issn: issns,
abstract: map['abstract'],
journalTitle: map['journalTitle'],
publishedDate: DateTime.parse(map['publishedDate']),
authors: List<PublicationAuthor>.from(
(jsonDecode(map['authors']) as List<dynamic>)
.map((authorJson) => PublicationAuthor.fromJson(authorJson)),
),
url: map['url'],
license: map['license'],
licenseName: map['licenseName'],
);
}).toList();
}
Future<List<PublicationCard>> getHiddenPublications() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.rawQuery('''
SELECT
articles.*,
journals.title AS journalTitle,
GROUP_CONCAT(journal_issns.issn) AS issns
FROM articles
JOIN journals ON articles.journal_id = journals.journal_id
LEFT JOIN journal_issns ON articles.journal_id = journal_issns.journal_id
WHERE articles.dateCached IS NOT NULL
AND articles.isHidden = 1
GROUP BY articles.doi
''');
return maps.map((map) {
final List<String> issns = (map['issns'] as String?)?.split(',') ?? [];
return PublicationCard(
doi: map['doi'],
title: map['title'],
issn: issns,
abstract: map['abstract'],
journalTitle: map['journalTitle'],
publishedDate: DateTime.parse(map['publishedDate']),
authors: List<PublicationAuthor>.from(
(jsonDecode(map['authors']) as List<dynamic>)
.map((authorJson) => PublicationAuthor.fromJson(authorJson)),
),
url: map['url'],
license: map['license'],
licenseName: map['licenseName'],
);
}).toList();
}
Future<void> hideArticle(String doi) async {
final db = await database;
await db.update(
'articles',
{'isHidden': 1},
where: 'doi = ?',
whereArgs: [doi],
);
}
Future<void> unhideArticle(String doi) async {
final db = await database;
await db.update(
'articles',
{'isHidden': 0},
where: 'doi = ?',
whereArgs: [doi],
);
}
Future<void> updateTranslatedContent({
required String doi,
String? translatedTitle,
String? translatedAbstract,
}) async {
final db = await database;
final Map<String, dynamic> updateData = {};
if (translatedTitle != null) {
updateData['translatedTitle'] = translatedTitle;
}
if (translatedAbstract != null) {
updateData['translatedAbstract'] = translatedAbstract;
}
if (updateData.isNotEmpty) {
final rowsAffected = await db.update(
'articles',
updateData,
where: 'doi = ?',
whereArgs: [doi],
);
if (rowsAffected > 0) {
logger.info('Updated translated content for DOI: $doi');
} else {
logger.warning(
'No article found with DOI: $doi to update translated content.');
}
}
}
Future<Map<String, String?>> getTranslatedContent(String doi) async {
final db = await database;
final result = await db.query(
'articles',
columns: ['translatedTitle', 'translatedAbstract'],
where: 'doi = ?',
whereArgs: [doi],
);
if (result.isNotEmpty) {
return {
'translatedTitle': result.first['translatedTitle'] as String?,
'translatedAbstract': result.first['translatedAbstract'] as String?,
};
}
return {'translatedTitle': null, 'translatedAbstract': null};
}
Future<bool> checkIfDoiExists(String doi) async {
final db = await database;
final result = await db.query(
'articles',
columns: ['doi'],
where: 'doi = ?',
whereArgs: [doi],
);
if (result.isNotEmpty) {
return true;
}
return false;
}
// Updates the abstract of an article after being scraped
Future<void> updateArticleAbstract(String doi, String abstract) async {
final db = await database;
await db.update(
'articles',
{
'abstract': abstract,
},
where: 'doi = ?',
whereArgs: [doi],
);
}
Future<bool> isArticleDownloaded(String doi) async {
final db = await database;
final count = Sqflite.firstIntValue(await db.rawQuery(
'SELECT COUNT(*) FROM articles WHERE doi = ? AND dateDownloaded IS NOT NULL AND pdfPath IS NOT NULL',
[doi],
))!;
return count > 0;
}
Future<List<DownloadedCard>> getDownloadedArticles() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.rawQuery('''
SELECT articles.*, journals.title AS journalTitle,
GROUP_CONCAT(journal_issns.issn) AS issns
FROM articles
LEFT JOIN journals ON articles.journal_id = journals.journal_id
LEFT JOIN journal_issns ON journals.journal_id = journal_issns.journal_id
WHERE articles.dateDownloaded IS NOT NULL
GROUP BY articles.article_id
''');
return List.generate(maps.length, (i) {
List<String> issns = (maps[i]['issns'] as String?)?.split(',') ?? [];
return DownloadedCard(
pdfPath: maps[i]['pdfPath'],
publicationCard: PublicationCard(
doi: maps[i]['doi'],
title: maps[i]['title'],
issn: issns,
abstract: maps[i]['abstract'],
journalTitle: maps[i]['journalTitle'],
publishedDate: DateTime.parse(maps[i]['publishedDate']),
authors: [],
url: '',
license: '',
licenseName: '',
),
onDelete: () {},
);
});
}
Future<String?> getAbstract(String doi) async {
final db = await database;
final result = await db.query(
'articles',
columns: ['abstract'],
where: 'doi = ?',
whereArgs: [doi],
);
return result.isNotEmpty ? result.first['abstract'] as String? : null;
}
Future<void> updateGraphicalAbstractPath(
String doi, File graphicalAbstractFile) async {
final db = await database;
final String filename = basename(graphicalAbstractFile.path);
try {
final rowsAffected = await db.update(
'articles',
{
'graphAbstractPath': filename,
},
where: 'doi = ?',
whereArgs: [doi],
);
if (rowsAffected > 0) {
logger.info(
'Updated graphical abstract path for DOI: $doi with basename: $filename');
} else {
logger.warning(
'No article found with DOI: $doi to update graphical abstract path.');
}
} catch (e, stackTrace) {
logger.severe('Failed to update graphical abstract path for DOI: $doi', e,
stackTrace);
}
}
Future<String?> getGraphicalAbstractPath(String doi) async {
final db = await database;
final result = await db.query(
'articles',
columns: ['graphAbstractPath'],
where: 'doi = ?',
whereArgs: [doi],
);
return result.isNotEmpty
? result.first['graphAbstractPath'] as String?
: null;
}
Future<void> removeDownloaded(String doi) async {
final db = await database;
await db.update(
'articles',
{'dateDownloaded': null, 'pdfPath': null},
where: 'doi = ?',
whereArgs: [doi],
);
}
// Insert function for the saved search queries
Future<void> saveSearchQuery(
String queryName, String queryParams, String provider) async {
final db = await database;
final String dateSaved = DateTime.now().toIso8601String();
await db.insert(
'savedQueries',
{
'queryName': queryName,
'queryParams': queryParams,
'dateSaved': dateSaved,
'includeInFeed': 0,
'queryProvider': provider,
},
);