Surface/lib/providers/widget.dart

61 lines
2.0 KiB
Dart
Raw Normal View History

2024-12-21 13:06:14 +00:00
import 'dart:async';
2024-12-14 10:18:13 +00:00
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:home_widget/home_widget.dart';
import 'package:surface/providers/sn_network.dart';
import 'package:surface/types/post.dart';
2024-12-14 10:18:13 +00:00
class HomeWidgetProvider {
HomeWidgetProvider(BuildContext context);
Future<void> initialize() async {
if (kIsWeb || !(Platform.isAndroid || Platform.isIOS)) return;
2024-12-23 13:55:07 +00:00
if (Platform.isIOS) {
2024-12-14 10:18:13 +00:00
await HomeWidget.setAppGroupId("group.solsynth.solian");
}
}
Future<void> saveWidgetData(String id, dynamic data, {bool update = true}) async {
2024-12-14 10:18:13 +00:00
if (kIsWeb || !(Platform.isAndroid || Platform.isIOS)) return;
await HomeWidget.saveWidgetData(id, jsonEncode(data));
2024-12-14 16:52:42 +00:00
if (update) await updateWidget();
2024-12-14 10:18:13 +00:00
}
Future<void> updateWidget() async {
if (kIsWeb || !(Platform.isAndroid || Platform.isIOS)) return;
2024-12-15 05:34:32 +00:00
if (Platform.isIOS) {
const widgets = ["SolarRandomPostWidget", "SolarCheckInWidget"];
2024-12-15 05:34:32 +00:00
for (final widget in widgets) {
await HomeWidget.updateWidget(
name: widget,
iOSName: widget,
2024-12-15 10:23:12 +00:00
);
}
} else if (Platform.isAndroid) {
const widgets = ["RandomPostWidget", "CheckInWidget"];
2024-12-15 10:23:12 +00:00
for (final widget in widgets) {
await HomeWidget.updateWidget(
androidName: "${widget}Receiver",
qualifiedAndroidName: "dev.solsynth.solian.widgets.${widget}Receiver",
2024-12-15 05:34:32 +00:00
);
}
2024-12-14 16:52:42 +00:00
}
2024-12-14 10:18:13 +00:00
}
}
Future<void> widgetUpdateRandomPost() async {
final snc = await SnNetworkProvider.createOffContextClient();
final resp = await snc.get('/cgi/co/recommendations/shuffle?take=1');
final post = SnPost.fromJson(resp.data['data'][0]);
await HomeWidget.saveWidgetData("int_random_post", jsonEncode(post.toJson()));
await HomeWidget.updateWidget(
name: "SolarRandomPostWidget",
iOSName: "SolarRandomPostWidget",
androidName: "RandomPostWidgetReceiver",
qualifiedAndroidName: "dev.solsynth.solian.widgets.RandomPostWidgetReceiver",
);
}