Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/*
* Copyright (c) 2018 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.app.browser.filechooser

import android.content.ClipData
import android.content.ClipData.Item
import android.content.ClipDescription
import android.content.ClipDescription.MIMETYPE_TEXT_URILIST
import android.content.Intent
import android.net.Uri
import androidx.net.toUri
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test

class FileChooserIntentBuilderTest {

private lateinit var testee: FileChooserIntentBuilder

@Before
fun setup() {
testee = FileChooserIntentBuilder()
}

@Test
fun whenIntentBuiltThenReadUriPermissionFlagSet() {
val output = testee.intent(emptyArray())
assertTrue("Intent.FLAG_GRANT_READ_URI_PERMISSION flag not set on intent", output.hasFlagSet(Intent.FLAG_GRANT_READ_URI_PERMISSION))
}

@Test
fun whenIntentBuiltThenAcceptTypeSetToAll() {
val output = testee.intent(emptyArray())
assertEquals("*/*", output.type)
}

@Test
fun whenMultipleModeDisabledThenIntentExtraReturnsFalse() {
val output = testee.intent(emptyArray(), canChooseMultiple = false)
assertFalse(output.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false))
}

@Test
fun whenRequestedTypesAreMissingThenShouldNotAddMimeTypeExtra() {
val output = testee.intent(emptyArray())
assertFalse(output.hasExtra(Intent.EXTRA_MIME_TYPES))
}

@Test
fun whenRequestedTypesArePresentThenShouldAddMimeTypeExtra() {
val output = testee.intent(arrayOf("image/png", "image/gif"))
assertTrue(output.hasExtra(Intent.EXTRA_MIME_TYPES))
}

@Test
fun whenUpperCaseTypesGivenThenNormalisedToLowercase() {
val output = testee.intent(arrayOf("ImAgE/PnG"))
assertEquals("image/png", output.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)[0])
}

@Test
fun whenEmptyTypesGivenThenNotIncludedInOutput() {
val output = testee.intent(arrayOf("image/png", "", " ", "image/gif"))
val mimeTypes = output.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)
assertEquals(2, mimeTypes.size)
assertEquals("image/png", mimeTypes[0])
assertEquals("image/gif", mimeTypes[1])
}

@Test
fun whenMultipleModeEnabledThenIntentExtraReturnsTrue() {
val output = testee.intent(emptyArray(), canChooseMultiple = true)
assertTrue(output.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false))
}

@Test
fun whenExtractingSingleUriEmptyClipThenSingleUriReturned() {
val intent = buildIntent("a")
val extractedUris = testee.extractSelectedFileUris(intent)

assertEquals(1, extractedUris!!.size)
assertEquals("a", extractedUris.first().toString())
}

@Test
fun whenExtractingSingleUriNonEmptyClipThenUriReturnedFromClip() {
val intent = buildIntent("a", listOf("b"))
val extractedUris = testee.extractSelectedFileUris(intent)

assertEquals(1, extractedUris!!.size)
assertEquals("b", extractedUris.first().toString())
}

@Test
fun whenExtractingMultipleClipItemsThenCorrectUrisReturnedFromClip() {
val intent = buildIntent("a", listOf("b", "c"))
val extractedUris = testee.extractSelectedFileUris(intent)

assertEquals(2, extractedUris!!.size)
assertEquals("b", extractedUris[0].toString())
assertEquals("c", extractedUris[1].toString())
}

@Test
fun whenExtractingSingleUriMissingButClipDataAvailableThenUriReturnedFromClip() {
val intent = buildIntent(clipData = listOf("b"))
val extractedUris = testee.extractSelectedFileUris(intent)

assertEquals(1, extractedUris!!.size)
assertEquals("b", extractedUris.first().toString())
}

@Test
fun whenNoDataOrClipDataThenNullUriReturned() {
val intent = buildIntent(data = null, clipData = null)
val extractedUris = testee.extractSelectedFileUris(intent)

assertNull(extractedUris)
}

/**
* Helper function to build an `Intent` which contains one or more of `data` and `clipData` values.
*
* This is a bit messy but the Intent APIs are messy themselves; at least this contains the mess to this one helper function
*/

private fun buildIntent(data: String? = null, clipData: List<String>? = null): Intent {
return Intent().also {
if (data != null) {
it.data = data.toUri()
}

if (clipData != null && clipData.isNotEmpty()) {
val clipDescription = ClipDescription("", arrayOf(MIMETYPE_TEXT_URILIST))
it.clipData = ClipData(clipDescription, Item(Uri.parse(clipData.first())))

for (i in 1 until clipData.size) {
it.clipData.addItem(Item(Uri.parse(clipData[i])))
}
}
}
}

private fun Intent.hasFlagSet(expectedFlag: Int): Boolean {
val actual = flags and expectedFlag
return expectedFlag == actual
}
}
88 changes: 8 additions & 80 deletions app/src/main/java/com/duckduckgo/app/browser/BrowserActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,12 @@

package com.duckduckgo.app.browser

import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.app.DownloadManager
import android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.content.Intent.EXTRA_TEXT
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat.requestPermissions
import android.support.v4.content.ContextCompat.checkSelfPermission
import android.webkit.URLUtil
import com.duckduckgo.app.bookmarks.ui.BookmarksActivity
import com.duckduckgo.app.browser.BrowserViewModel.Command
import com.duckduckgo.app.browser.BrowserViewModel.Command.*
Expand All @@ -43,7 +33,6 @@ import com.duckduckgo.app.privacy.ui.PrivacyDashboardActivity
import com.duckduckgo.app.settings.SettingsActivity
import com.duckduckgo.app.tabs.model.TabEntity
import com.duckduckgo.app.tabs.ui.TabSwitcherActivity
import kotlinx.android.synthetic.main.fragment_browser_tab.*
import org.jetbrains.anko.longToast
import timber.log.Timber
import javax.inject.Inject
Expand All @@ -60,9 +49,6 @@ class BrowserActivity : DuckDuckGoActivity() {
ViewModelProviders.of(this, viewModelFactory).get(BrowserViewModel::class.java)
}

// Used to represent a file to download, but may first require permission
private var pendingFileDownload: PendingFileDownload? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_browser)
Expand Down Expand Up @@ -159,12 +145,13 @@ class BrowserActivity : DuckDuckGoActivity() {
}
}

private fun processCommand(it: Command?) {
when (it) {
is NewTab -> openNewTab(it.tabId, it.query)
is Query -> currentTab?.submitQuery(it.query)
private fun processCommand(command: Command?) {
Timber.i("Processing command: $command")
when (command) {
is NewTab -> openNewTab(command.tabId, command.query)
is Query -> currentTab?.submitQuery(command.query)
is Refresh -> currentTab?.refresh()
is Command.DisplayMessage -> applicationContext?.longToast(it.messageId)
is Command.DisplayMessage -> applicationContext?.longToast(command.messageId)
}
}

Expand Down Expand Up @@ -201,65 +188,12 @@ class BrowserActivity : DuckDuckGoActivity() {
startActivity(BookmarksActivity.intent(this))
}

fun downloadFile(url: String) {
pendingFileDownload = PendingFileDownload(url, Environment.DIRECTORY_DOWNLOADS)
downloadFileWithPermissionCheck()
}

fun downloadImage(url: String) {
pendingFileDownload = PendingFileDownload(url, Environment.DIRECTORY_PICTURES)
downloadFileWithPermissionCheck()
}

private fun downloadFileWithPermissionCheck() {
if (hasWriteStoragePermission()) {
downloadFile()
} else {
requestStoragePermission()
}
}

private fun downloadFile() {
val pending = pendingFileDownload
pending?.let {
val uri = Uri.parse(pending.url)
val guessedFileName = URLUtil.guessFileName(pending.url, null, null)
Timber.i("Guessed filename of $guessedFileName for url ${pending.url}")
val request = DownloadManager.Request(uri).apply {
allowScanningByMediaScanner()
setDestinationInExternalPublicDir(pending.directory, guessedFileName)
setNotificationVisibility(VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
}
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
pendingFileDownload = null
applicationContext?.longToast(getString(R.string.webviewDownload))
}
}

private fun hasWriteStoragePermission(): Boolean {
return checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
}

private fun requestStoragePermission() {
requestPermissions(this, arrayOf(WRITE_EXTERNAL_STORAGE), PERMISSION_REQUEST_EXTERNAL_STORAGE)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == PERMISSION_REQUEST_EXTERNAL_STORAGE) {
if ((grantResults.isNotEmpty()) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Timber.i("Permission granted")
downloadFile()
} else {
Timber.i("Permission refused")
Snackbar.make(toolbar, R.string.permissionRequiredToDownload, Snackbar.LENGTH_LONG).show()
}
}
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == DASHBOARD_REQUEST_CODE) {
viewModel.receivedDashboardResult(resultCode)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}

Expand All @@ -269,11 +203,6 @@ class BrowserActivity : DuckDuckGoActivity() {
}
}

private data class PendingFileDownload(
val url: String,
val directory: String
)

companion object {

fun intent(context: Context, queryExtra: String? = null, newSearch: Boolean = false): Intent {
Expand All @@ -285,6 +214,5 @@ class BrowserActivity : DuckDuckGoActivity() {

private const val NEW_SEARCH_EXTRA = "NEW_SEARCH_EXTRA"
private const val DASHBOARD_REQUEST_CODE = 100
private const val PERMISSION_REQUEST_EXTERNAL_STORAGE = 200
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@

package com.duckduckgo.app.browser

import android.net.Uri
import android.view.View
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import timber.log.Timber
Expand Down Expand Up @@ -56,4 +58,8 @@ class BrowserChromeClient @Inject constructor() : WebChromeClient() {
webViewClientListener?.titleReceived(title)
}

override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
webViewClientListener?.showFileChooser(filePathCallback, fileChooserParams)
return true
}
}
Loading