Skip to content

Commit

Permalink
✨ Delegate android download
Browse files Browse the repository at this point in the history
  • Loading branch information
vokimon committed Dec 31, 2023
1 parent 5a964bd commit bdb6525
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions frontend/src/services/ovapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,21 +254,43 @@ function invoicePdf(invoiceNumber) {
if (result.error !== undefined) {
throw result
}
const url = window.URL.createObjectURL(new Blob([result.data]))
const link = document.createElement('a')
link.href = url
const filename =
result.headers['content-disposition'].match(/filename="([^"]+)"/)[1]
if (filename) link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
// clean up
document.body.removeChild(link)
URL.revokeObjectURL(url)
return result.data
result.headers['content-disposition']?.match(/filename="([^"]+)"/)[1] ??
`factura-${invoiceNumber}.pdf`
if (androidDownload(filename, result.data)) return result
regulardownload(filename, result.data)
return result
})
}

function androidDownload(filename, blob) {
// SomenergiaPlatform is injected in mobile applications
// as alternative to save the PDF, since the method used
// for regular browers won't work. We need to convert
// the blob to base64 though.
if (!window.SomenergiaPlatform) return
var reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = function () {
// Remove trailing url header
let base64String = reader.result.replace(/.*,/, '')
window.SomenergiaPlatform.save(filename, base64String)
return base64String
}
}
function regulardownload(filename, blob) {
const url = window.URL.createObjectURL(new Blob([blob]))
const link = document.createElement('a')
link.href = url
if (filename) link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
// clean up
document.body.removeChild(link)
URL.revokeObjectURL(url)
return blob
}

export default {
version,
logout,
Expand Down

0 comments on commit bdb6525

Please sign in to comment.