creek

The AI Image Editor of 2030

lib/services/instagram_download_service.dart (1738B)


 1import 'dart:io';
 2import 'package:path_provider/path_provider.dart';
 3import 'package:uuid/uuid.dart';
 4import 'python_service.dart';
 5
 6class InstagramDownloadService {
 7  final _pythonService = PythonService();
 8  final _uuid = const Uuid();
 9
10  Future<List<String>?> downloadInstagramImage(String url) async {
11    try {
12      final dir = await getApplicationDocumentsDirectory();
13
14      // Create directories
15      final instagramDir = Directory('${dir.path}/instagram_downloads');
16      if (!await instagramDir.exists()) {
17        await instagramDir.create(recursive: true);
18      }
19
20      final imagesDir = Directory('${dir.path}/images');
21      if (!await imagesDir.exists()) await imagesDir.create(recursive: true);
22
23      // Call Python Service
24      final jsonResult = await _pythonService.downloadInstagramImage(
25        url,
26        instagramDir.path,
27      );
28
29      if (jsonResult != null && jsonResult['success'] == true) {
30        final List<dynamic> paths = jsonResult['file_paths'];
31        final List<String> savedFilePaths = [];
32
33        // Save downloaded files to app storage
34        for (var path in paths) {
35          final String sourcePath = path as String;
36          final File sourceFile = File(sourcePath);
37
38          if (await sourceFile.exists()) {
39            final String imageId = _uuid.v4();
40            final extension = sourcePath.split('.').last;
41            final String targetPath = '${imagesDir.path}/$imageId.$extension';
42            await sourceFile.copy(targetPath);
43            savedFilePaths.add(targetPath);
44          }
45        }
46        return savedFilePaths.isNotEmpty ? savedFilePaths : null;
47      }
48      return null;
49    } catch (e) {
50      throw Exception("Download failed: $e");
51    }
52  }
53}