|
| 1 | +import 'dart:io'; |
| 2 | + |
| 3 | +import 'package:flutter/material.dart'; |
| 4 | +import 'package:path_provider/path_provider.dart'; |
| 5 | +import 'package:piwigo_ng/services/preferences_service.dart'; |
| 6 | +import 'package:shared_preferences/shared_preferences.dart'; |
| 7 | +import 'package:workmanager/workmanager.dart'; |
| 8 | + |
| 9 | +class AutoUploadManager { |
| 10 | + final String taskKey = 'com.piwigo.piwigo_ng.auto_upload'; |
| 11 | + final String tag = '<auto_upload>'; |
| 12 | + late Workmanager _manager; |
| 13 | + |
| 14 | + AutoUploadManager() { |
| 15 | + _manager = Workmanager(); |
| 16 | + } |
| 17 | + |
| 18 | + Future<void> endAutoUpload() async { |
| 19 | + appPreferences.setBool( |
| 20 | + Preferences.autoUploadKey, |
| 21 | + false, |
| 22 | + ); |
| 23 | + await _manager.cancelByUniqueName(taskKey); |
| 24 | + } |
| 25 | + |
| 26 | + Future<void> startAutoUpload() async { |
| 27 | + appPreferences.setBool( |
| 28 | + Preferences.autoUploadKey, |
| 29 | + true, |
| 30 | + ); |
| 31 | + await _manager.registerPeriodicTask( |
| 32 | + taskKey, |
| 33 | + taskKey, |
| 34 | + frequency: const Duration(minutes: 15), |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + Future<Directory?> getUploadDirectory() async { |
| 39 | + return await getTemporaryDirectory(); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +@pragma('vm:entry-point') |
| 44 | +void callbackDispatcher() { |
| 45 | + Workmanager().executeTask((task, inputData) async { |
| 46 | + final SharedPreferences prefs = await SharedPreferences.getInstance(); |
| 47 | + debugPrint("Background $task"); |
| 48 | + debugPrint(prefs.getString('UPLOAD_AUTHOR_NAME') ?? ''); |
| 49 | + final Directory? appDocDir = await AutoUploadManager().getUploadDirectory(); |
| 50 | + if (appDocDir == null) return false; |
| 51 | + debugPrint(appDocDir.listSync().toString()); |
| 52 | + // final List<File> files = appDocDir.listSync().whereType<File>().toList(); |
| 53 | + // List<XFile> uploadFiles = files.map<XFile>((file) => XFile(file.path)).toList(); |
| 54 | + // final result = await uploadPhotos(uploadFiles, 92); |
| 55 | + // debugPrint(result.toString()); |
| 56 | + return Future.value(true); |
| 57 | + }); |
| 58 | +} |
| 59 | + |
| 60 | +void initializeWorkManager() { |
| 61 | + Workmanager().initialize( |
| 62 | + callbackDispatcher, // The top level function, aka callbackDispatcher |
| 63 | + isInDebugMode: true, // If enabled it will post a notification whenever the task is running. Handy for debugging tasks |
| 64 | + ); |
| 65 | +} |
0 commit comments