From 3a9d083c1b626fc06ebbacf5667075128b9e631a Mon Sep 17 00:00:00 2001 From: resucutie Date: Tue, 14 Jan 2025 19:21:10 -0300 Subject: [PATCH] autodownload: fix name of files that come from redirects --- .../preset/autodownload/single/generic.dart | 3 ++- lib/utils/download_image.dart | 23 ++++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/lib/api/preset/autodownload/single/generic.dart b/lib/api/preset/autodownload/single/generic.dart index 306a41a..76b8580 100644 --- a/lib/api/preset/autodownload/single/generic.dart +++ b/lib/api/preset/autodownload/single/generic.dart @@ -2,9 +2,10 @@ part of preset; // twitter: fxtwitter offers a url to give only the image. getting the artist is as easy as reading the first path segment Future twitterToPresetImage(Uri uri) async { - // final res = await http.get(Uri.parse(["https://d.fxtwitter.com", uri.path].join())); + // final res = await lbHttp.get(Uri.parse(["https://d.fxtwitter.com", uri.path].join())); final downloadedFileInfo = await downloadFile(Uri.parse(["https://d.fxtwitter.com", uri.path].join())); + debugPrint(downloadedFileInfo.path); return PresetImage( image: downloadedFileInfo, diff --git a/lib/utils/download_image.dart b/lib/utils/download_image.dart index a0462ef..2f61123 100644 --- a/lib/utils/download_image.dart +++ b/lib/utils/download_image.dart @@ -9,13 +9,24 @@ import 'package:path_provider/path_provider.dart'; typedef HandleChunk = Function(List chunk, http.StreamedResponse response); int hasDownloaded = 0; -Future downloadFile(Uri uri, {HandleChunk? handleChunk}) async { +Future downloadFile(Uri uri, {HandleChunk? handleChunk, bool followRedirects = true}) async { + http.Request request; + http.StreamedResponse response; + do { // lazy work for redirects; do-while because it'll run once if followRedirects = false + request = http.Request("GET", uri); + request.followRedirects = false; + response = await lbHttp.send(request); + if(response.isRedirect) { + final String? newUrl = response.headers['location']; + if(newUrl != null) uri = Uri.parse(newUrl); + else throw "Redirect does not have 'location' header"; + } else break; + } while (followRedirects); + final downloadDir = await getTemporaryDirectory(); - final file = File(p.join(downloadDir.path, uri.pathSegments.last)); - - final request = http.Request("GET", uri); - final response = await lbHttp.send(request); - final sink = file.openWrite(); + final name = uri.pathSegments.last; + final file = File(p.join(downloadDir.path, name)); + IOSink sink = file.openWrite(); await response.stream.map((chunk) { if(handleChunk == null) {