Surface/lib/providers/sn_attachment.dart

47 lines
1.4 KiB
Dart
Raw Normal View History

2024-11-09 04:04:03 +00:00
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:surface/providers/sn_network.dart';
import 'package:surface/types/attachment.dart';
class SnAttachmentProvider {
2024-11-09 11:32:21 +00:00
late final SnNetworkProvider _sn;
2024-11-09 04:04:03 +00:00
final Map<String, SnAttachment> _cache = {};
SnAttachmentProvider(BuildContext context) {
2024-11-09 11:32:21 +00:00
_sn = context.read<SnNetworkProvider>();
2024-11-09 04:04:03 +00:00
}
Future<SnAttachment> getOne(String rid, {noCache = false}) async {
if (!noCache && _cache.containsKey(rid)) {
return _cache[rid]!;
}
2024-11-09 11:32:21 +00:00
final resp = await _sn.client.get('/cgi/uc/attachments/$rid/meta');
2024-11-09 04:04:03 +00:00
final out = SnAttachment.fromJson(resp.data);
_cache[rid] = out;
return out;
}
Future<List<SnAttachment>> getMultiple(List<String> rids,
{noCache = false}) async {
final pendingFetch =
noCache ? rids : rids.where((rid) => !_cache.containsKey(rid)).toList();
if (pendingFetch.isEmpty) {
return rids.map((rid) => _cache[rid]!).toList();
}
2024-11-09 11:32:21 +00:00
final resp = await _sn.client.get('/cgi/uc/attachments', queryParameters: {
2024-11-09 04:04:03 +00:00
'take': pendingFetch.length,
'id': pendingFetch.join(','),
});
final out = resp.data['data'].map((e) => SnAttachment.fromJson(e)).toList();
for (var i = 0; i < out.length; i++) {
_cache[pendingFetch[i]] = out[i];
}
return rids.map((rid) => _cache[rid]!).toList();
}
}