Skip to content

Commit

Permalink
Fix download from URL for Google Drive and Dropbox
Browse files Browse the repository at this point in the history
For URLs to download books in Google Drive and Dropbox, the URL provided
by the user needs to be fixed up before a download can be attempted.

Tested book download from Google Drive and Dropbox URLs for individual
files and zip files.

Fixes: #1077
Signed-off-by: Nithya Vasudevan <[email protected]>
  • Loading branch information
nithya2511 committed Aug 1, 2024
1 parent af9a5cc commit 5a036df
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion BookPlayer/Library/ItemList Screen/ItemListViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ class ItemListViewModel: ViewModelProtocol {
BPActionItem(
title: "download_title".localized,
inputHandler: { [weak self] url in
if let bookUrl = URL(string: url) {
if let bookUrl = self?.getDownloadURL(for: url) {
self?.handleDownload(bookUrl)
} else {
self?.sendEvent(.showAlert(
Expand Down Expand Up @@ -1311,6 +1311,43 @@ extension ItemListViewModel {
)
))
}

func getDownloadURL(for givenString : String) -> URL? {
let givenUrl = URL(string: givenString)

if let givenUrl, let hostname = givenUrl.host {
if hostname == "drive.google.com" {
return getGoogleDriveURL(for: givenUrl)
} else if hostname == "www.dropbox.com" {
return getDropboxURL(for: givenUrl)
}
}
return nil
}

func getGoogleDriveURL(for url: URL) -> URL?
{
let pathComponents = url.pathComponents
if let index = pathComponents.firstIndex(of: "d"), index + 1 < pathComponents.count {
return URL(string: "https://drive.google.com/uc?export=download&id=" + pathComponents[index + 1])
}
return nil;
}

func getDropboxURL (for url : URL) -> URL?
{
guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
var queryItems = urlComponents.queryItems ?? []
if let index = queryItems.firstIndex(where: {$0.name == "dl"}) {
queryItems[index].value = "1"
} else {
queryItems.append(URLQueryItem(name: "dl", value: "1"))
}
urlComponents.queryItems = queryItems
return urlComponents.url
}
}

extension ItemListViewModel: AlertPresenter {
Expand Down

0 comments on commit 5a036df

Please sign in to comment.