7

Upfront info:

Language: Flutter/Dart
Flutter Packages: flutter_inappwebview, flutter_downloader

I'm having an issue with a mobile application I'm building for Android using Flutter. One function of the app is to be able to download links that are associated with PDF files. These files are located on the server that the app is already accessing. A user has already logged in through the app so authentication has been established. When a URL is clicked that has a PDF it performs a redirect and the homepage (an index.php) is returned and downloaded instead. I am at a loss as to how this is happening but I have thoughts.

  1. I need to have the download occur in the current webview (as in same session and window).
  2. Disable URL redirection.
  3. Figure out why the link is being redirected for authentication (assumption as it's redirecting to the homepage).

Any thoughts or help would be appreciated. Happy to provide more information as well.

In main.dart:

onDownloadStart: (controller, url) async {
                print("onDownloadStart $url");
                final taskId = await FlutterDownloader.enqueue(
                  headers: {'My-Custom-Header': 'custom_value=564hgf34'},
                  url: url,
                  savedDir: (await getExternalStorageDirectory()).path,
                  showNotification: true, // show download progress in status bar (for Android)
                  openFileFromNotification: true, // click on notification to open downloaded file (for Android)
                );
                return taskId;
              },

Logging:

I/flutter (28552): onDownloadStart https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf
W/WM-WorkSpec(28552): Backoff delay duration less than minimum value
D/DownloadWorker(28552): DownloadWorker{url=https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf,filename=null,savedDir=/storage/emulated/0/Android/data/com.coffeepaulconsulting.hjhvtconline/files,header={"My-Custom-Header": "custom_value=564hgf34"},isResume=false
D/DownloadWorker(28552): Update notification: {notificationId: 1, title: https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf, status: 2, progress: 0}
D/DownloadWorker(28552): Open connection to https://hjhvtc.online/pluginfile.php/6723/mod_resource/content/1/Automotive%20industry%20jobs.pdf
D/DownloadWorker(28552): Headers = {"My-Custom-Header": "custom_value=564hgf34"}
D/DownloadWorker(28552): Response with redirection code
D/DownloadWorker(28552): Location = https://hjhvtc.online/login/index.php
D/DownloadWorker(28552): New url: https://hjhvtc.online/login/index.php
D/DownloadWorker(28552): Open connection to https://hjhvtc.online/login/index.php
D/DownloadWorker(28552): Headers = {"My-Custom-Header": "custom_value=564hgf34"}
V/InputMethodManager(28552): b/117267690: Failed to get fallback IMM with expected displayId=197 actual IMM#displayId=0 view=com.pichillilorenzo.flutter_inappwebview.InAppWebView.InAppWebView{4592e22 VFEDHVCL. ......ID 0,0-1080,1997}
D/DownloadWorker(28552): Content-Type = text/html; charset=utf-8
D/DownloadWorker(28552): Content-Length = -1
D/DownloadWorker(28552): Charset = UTF-8
D/DownloadWorker(28552): Content-Disposition = null
D/DownloadWorker(28552): fileName = index.php
D/DownloadWorker(28552): Update too frequently!!!!, this should be dropped
D/DownloadWorker(28552): There's no application that can open the file /storage/emulated/0/Android/data/com.coffeepaulconsulting.hjhvtconline/files/index.php
D/DownloadWorker(28552): Update too frequently!!!!, but it is the final update, we should sleep a second to ensure the update call can be processed
D/DownloadWorker(28552): Update notification: {notificationId: 1, title: index.php, status: 3, progress: 100}
D/DownloadWorker(28552): File downloaded
I/WM-WorkerWrapper(28552): Worker result SUCCESS for Work [ id=633dd93d-99e3-46e2-937d-a4782d62a569, tags={ flutter_download_task, vn.hunghd.flutterdownloader.DownloadWorker } ]
Paul VanGundy
  • 71
  • 1
  • 2
  • https://stackoverflow.com/questions/60371760/why-do-my-downloads-fail-sometimes-using-flutter-downloader i had the same issue found the solution here. – Daniyal Saeed Mar 29 '21 at 13:15

1 Answers1

0

I've finally found the solution after several tries. The DownloadWorker is redirected to the login page because although the user is authenticated in the InAppWebView, the flutter downloader seems to run in a separate context so the user is not authenticated.

To maintain the user session, I created a variable:

  // Store cookies to save user session for download
  String cookiesString = '';

Then, I created the updateCookies function that retrieves the cookies from the CookieManager and update the cookiesString variable:

  Future<void> updateCookies(Uri url) async {
    List<Cookie> cookies = await CookieManager().getCookies(url: url);
    cookiesString = '';
    for (Cookie cookie in cookies) {
      cookiesString += '${cookie.name}=${cookie.value};';
    }
    print(cookiesString);
  }

Then, I call updateCookies in the onLoadStop event listener of InAppWebView:

onLoadStop: (controller, url) async {
    pullToRefreshController.endRefreshing();

    if (url != null) {
        await updateCookies(url);
    }

    setState(() {
        this.url = url.toString();
        urlController.text = this.url;
    });
},

Finally, I pass the cookies to the headers of FlutterDownloader in the onDownloadStart event listener:

                  await FlutterDownloader.enqueue(
                    headers: {
                      HttpHeaders.authorizationHeader: 'Basic ' +
                          authToken,
                      HttpHeaders.connectionHeader: 'keep-alive',
                      HttpHeaders.cookieHeader: cookiesString,
                    },
Dharman
  • 30,962
  • 25
  • 85
  • 135
junsiong2008
  • 107
  • 13