Skip to content

Commit

Permalink
Merge pull request #3 from alibaba/feat/down
Browse files Browse the repository at this point in the history
feat:add download api
  • Loading branch information
LiCola-Exist authored Dec 19, 2023
2 parents cf06501 + 7830527 commit 4533672
Show file tree
Hide file tree
Showing 14 changed files with 857 additions and 13 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ android {
}

dependencies {
// implementation project(":opensdk")
implementation project(":opensdk")
// implementation 'com.github.alibaba:aliyunpan-android-sdk:v0.1.4'
implementation "com.squareup.okhttp3:okhttp:4.11.0"
implementation 'com.github.alibaba:aliyunpan-android-sdk:v0.1.4'

implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.alicloud.databox.demo

import android.content.Context
import android.os.Environment
import com.alicloud.databox.opensdk.AliyunpanClient
import com.alicloud.databox.opensdk.AliyunpanClientConfig
import java.io.File

object AliyunpanApp {

Expand All @@ -11,6 +13,12 @@ object AliyunpanApp {
fun initApp(context: Context) {
// 配置
val config = AliyunpanClientConfig.Builder(context, BuildConfig.APP_KEY)
.downFolder(
File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"Aliyunpan-Sdk"
)
)
.build()
// 初始化client
aliyunpanClient = AliyunpanClient.init(config)
Expand Down
62 changes: 57 additions & 5 deletions app/src/callback/java/com/alicloud/databox/demo/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.alicloud.databox.demo.ViewHelper.appendWithTime
import com.alicloud.databox.opensdk.io.BaseTask
import com.alicloud.databox.opensdk.scope.AliyunpanFileScope
import com.alicloud.databox.opensdk.scope.AliyunpanUserScope

class MainActivity : AppCompatActivity() {

private var defaultDriveId: String? = null
private var fileId: String? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -33,6 +35,10 @@ class MainActivity : AppCompatActivity() {
findViewById<View>(R.id.btnFileListInfo).setOnClickListener {
getFileList(defaultDriveId, tvResult)
}

findViewById<View>(R.id.btnFileDownload).setOnClickListener {
startDownloadFile(defaultDriveId, fileId, tvResult)
}
}

private fun startOAuth(tvResult: TextView) {
Expand Down Expand Up @@ -66,10 +72,56 @@ class MainActivity : AppCompatActivity() {
return
}
AliyunpanApp.aliyunpanClient
?.send(AliyunpanFileScope.GetFileList(driveId, parentFileId = "root", fields = "*", limit = 2), {
tvResult.appendWithTime("GetFileList success: $it")
}, {
tvResult.appendWithTime("GetFileList failed: $it")
})
?.send(
AliyunpanFileScope.GetFileList(
driveId,
parentFileId = "root",
fields = "*",
limit = 2,
type = "file",
orderBy = "size",
orderDirection = "ASC"
), {
tvResult.appendWithTime("GetFileList success: $it")

val items = it.data.asJSONObject().optJSONArray("items")
fileId = items.getJSONObject(0).optString("file_id")

}, {
tvResult.appendWithTime("GetFileList failed: $it")
})
}

private fun startDownloadFile(defaultDriveId: String?, fileId: String?, tvResult: TextView) {
AliyunpanApp.aliyunpanClient?.buildDownload(defaultDriveId ?: "", fileId ?: "", { task ->
tvResult.appendWithTime("buildDownload success $task")
task.addStateChange { taskState ->
when (taskState) {
BaseTask.TaskState.Abort -> {
tvResult.appendWithTime("taskState Abort ")
}

is BaseTask.TaskState.Completed -> {
tvResult.appendWithTime("taskState Completed ${taskState.filePath}")
}

is BaseTask.TaskState.Failed -> {
tvResult.appendWithTime("taskState Failed ${taskState.exception}")
}

is BaseTask.TaskState.Running -> {
tvResult.appendWithTime("taskState Running ${taskState.completedChunkSize}/${taskState.totalChunkSize} Progress=${taskState.getProgress()}")
}

BaseTask.TaskState.Waiting -> {
tvResult.appendWithTime("taskState Waiting")
}
}
}
val startResult = task.start()
tvResult.appendWithTime("start task = $task startResult = $startResult")
}, {
tvResult.appendWithTime("buildDownload failed $it")
})
}
}
2 changes: 2 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<!-- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>-->
<!-- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>-->

<application
android:name=".MainApp"
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
android:layout_height="wrap_content"
android:text="获取文件列表" />

<Button
android:id="@+id/btnFileDownload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载文件" />

<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
Expand Down
3 changes: 2 additions & 1 deletion opensdk/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ android {

consumerProguardFiles "consumer-rules.pro"

buildConfigField 'String', 'VERSION', '"' + String.valueOf("0.0.1") + '"'
buildConfigField 'String', 'VERSION', '"' + String.valueOf("0.1.5") + '"'
}

buildFeatures {
Expand Down Expand Up @@ -44,6 +44,7 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

testImplementation 'junit:junit:4.13.2'
}

afterEvaluate {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,25 @@ import android.net.Uri
import android.os.Handler
import android.os.Looper
import com.alicloud.databox.opensdk.AliyunpanException.Companion.buildError
import com.alicloud.databox.opensdk.io.AliyunpanDownloader
import com.alicloud.databox.opensdk.http.OKHttpHelper
import com.alicloud.databox.opensdk.http.OKHttpHelper.enqueue
import com.alicloud.databox.opensdk.http.OKHttpHelper.execute
import com.alicloud.databox.opensdk.http.TokenAuthenticator
import com.alicloud.databox.opensdk.io.BaseTask
import okhttp3.HttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import kotlin.jvm.Throws

class AliyunpanClient private constructor(private val config: AliyunpanClientConfig) : AliyunpanBaseClient,
TokenAuthenticator.TokenAuthenticatorConfig {

private val handler = Handler(Looper.myLooper()!!)
internal val handler = Handler(Looper.myLooper()!!)

private val downloader: AliyunpanDownloader by lazy { AliyunpanDownloader(this, config.downloadFolderPath) }

private val okHttpInstance = OKHttpHelper.buildOKHttpClient(this, config)

Expand Down Expand Up @@ -203,6 +209,17 @@ class AliyunpanClient private constructor(private val config: AliyunpanClientCon
send(request, onSuccess, onFailure)
}

@Throws(Exception::class)
internal fun sendSync(scope: AliyunpanScope): ResultResponse {
val request = buildRequest(scope)
if (request == null) {
val exception = AliyunpanException.CODE_REQUEST_INVALID.buildError("build request failed")
LLogger.log(TAG, "sendSync failed", exception)
throw exception
}
return okHttpInstance.execute(request)
}

/**
* Send 发送请求
*
Expand All @@ -214,6 +231,38 @@ class AliyunpanClient private constructor(private val config: AliyunpanClientCon
okHttpInstance.enqueue(request, handler, onSuccess, onFailure)
}

fun buildDownload(
driveId: String,
fileId: String,
onSuccess: Consumer<BaseTask>,
onFailure: Consumer<Exception>
) {
this.buildDownload(driveId, fileId, null, onSuccess, onFailure)
}

/**
* Build download
*
* @param driveId
* @param fileId
* @param expireSec 下载地址过期时间 单位秒 默认900秒
* @param onSuccess
* @param onFailure
*/
fun buildDownload(
driveId: String,
fileId: String,
expireSec: Int? = null,
onSuccess: Consumer<BaseTask>,
onFailure: Consumer<Exception>
) {
if (expireSec != null && expireSec <= 0) {
onFailure.accept(AliyunpanException.CODE_DOWNLOAD_ERROR.buildError("expireSec must be more than 0"))
return
}
downloader.buildDownload(driveId, fileId, expireSec, onSuccess, onFailure)
}

private fun buildRequest(scope: AliyunpanScope): Request? {
val baseHttpUrl = HttpUrl.Builder()
.scheme("https")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import android.os.Build
import com.alicloud.databox.opensdk.auth.AliyunpanPKCECredentials
import com.alicloud.databox.opensdk.auth.AliyunpanServerCredentials
import com.alicloud.databox.opensdk.http.HttpHeaderInterceptor
import java.io.File

class AliyunpanClientConfig private constructor(
internal val context: Context,
internal val scope: String,
internal val baseApi: String,
internal val credentials: AliyunpanCredentials
internal val credentials: AliyunpanCredentials,
internal val downloadFolderPath: String
) : HttpHeaderInterceptor.HttpHeaderConfig {

private val userAgent: String by lazy {
Expand Down Expand Up @@ -41,7 +43,7 @@ class AliyunpanClientConfig private constructor(

companion object {

private const val USER_AGENT_FORMAT = "%s/%s (%s; build:{%s}; Android %s) AliyunpanSDK/%s"
private const val USER_AGENT_FORMAT = "%s/%s (%s; build:%s; Android %s) AliyunpanSDK/%s"
}

class Builder {
Expand All @@ -66,6 +68,8 @@ class AliyunpanClientConfig private constructor(

private var tokenServer: AliyunpanTokenServer? = null

private var downloadFolderPath: String = ""

constructor(context: Context, appId: String) {
this.context = context.applicationContext
this.appId = appId
Expand All @@ -77,6 +81,20 @@ class AliyunpanClientConfig private constructor(

fun tokenServer(tokenServer: AliyunpanTokenServer) = apply { this.tokenServer = tokenServer }

/**
* Down folder
* 配置文件下载文件夹路径,下载时注意文件读写权限授予
* @param downloadFolderPath 下载文件夹路径
*/
fun downFolder(downloadFolderPath: String) = apply { this.downloadFolderPath = downloadFolderPath }

/**
* Down folder
* 配置文件下载文件夹,下载时注意文件读写权限授予
* @param downloadFolder 下载文件夹
*/
fun downFolder(downloadFolder: File) = apply { this.downloadFolderPath = downloadFolder.absolutePath }

fun build(): AliyunpanClientConfig {
val aliyunpanTokenServer = tokenServer
val credentials = if (aliyunpanTokenServer == null) {
Expand All @@ -89,7 +107,8 @@ class AliyunpanClientConfig private constructor(
context,
scope,
baseApi,
credentials
credentials,
downloadFolderPath
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ open class AliyunpanException(open val code: String, override val message: Strin

const val CODE_REQUEST_INVALID = "RequestInvalid"

const val CODE_DOWNLOAD_ERROR = "DownloadError"

inline fun String.buildError(message: String) = AliyunpanException(this, message)
}
}
Loading

0 comments on commit 4533672

Please sign in to comment.