Files
assistant-android/app/src/main/java/com/gh/common/util/UploadImageUtils.kt

203 lines
8.8 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.gh.common.util
import android.graphics.BitmapFactory
import com.gh.gamecenter.retrofit.BiResponse
import com.gh.gamecenter.retrofit.FileRequestBody
import com.gh.gamecenter.retrofit.RetrofitCallback
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.MultipartBody
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.File
object UploadImageUtils {
enum class UploadType {
question,
answer,
suggestion,
icon
}
// 不处理图片,只是单纯的上次
fun uploadImage(type: UploadType, imgPath: String, listener: OnUploadImageListener): Disposable {
return Single.just(imgPath)
.subscribeOn(Schedulers.computation())
.flatMap {
val compressFile = File(imgPath) // compress
val requestBody = FileRequestBody<ResponseBody>(compressFile, object : RetrofitCallback<ResponseBody>() {
override fun onProgress(total: Long, progress: Long) {
listener.onProgress(total, progress)
}
})
val part = MultipartBody.Part.createFormData("Filedata", getFileName(compressFile), requestBody)
return@flatMap RetrofitManager.getInstance(HaloApp.getInstance().application).uploadApi.uploadImage(part, type.name)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BiResponse<ResponseBody>() {
override fun onSuccess(data: ResponseBody) {
val string = data.string()
if (!string.isNullOrEmpty()) {
val url = JSONObject(string).getString("url")
if (!url.isNullOrEmpty()) {
listener.onSuccess(url)
return
}
}
onFailure(IllegalAccessException("HeHe"))
}
override fun onFailure(exception: Exception) {
listener.onError(exception)
}
})
}
// 社区图片上传 后续统一其他
fun compressAndUploadImage(type: UploadType, imgPath: String, compressGif: Boolean, listener: OnUploadImageListener): Disposable {
return Single.just(imgPath)
.subscribeOn(Schedulers.computation())
.flatMap {
val compressFile = compressImage(it, compressGif) // compress
val requestBody = FileRequestBody<ResponseBody>(compressFile, object : RetrofitCallback<ResponseBody>() {
override fun onProgress(total: Long, progress: Long) {
listener.onProgress(total, progress)
}
})
val part = MultipartBody.Part.createFormData("Filedata", getFileName(compressFile), requestBody)
return@flatMap RetrofitManager.getInstance(HaloApp.getInstance().application).uploadApi.uploadImage(part, type.name)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BiResponse<ResponseBody>() {
override fun onSuccess(data: ResponseBody) {
val string = data.string()
if (!string.isNullOrEmpty()) {
val url = JSONObject(string).getString("url")
if (!url.isNullOrEmpty()) {
listener.onSuccess(url)
return
}
}
onFailure(IllegalAccessException("HeHe"))
}
override fun onFailure(exception: Exception) {
listener.onError(exception)
}
})
}
fun compressAndUploadImageList(type: UploadType, imgs: List<String>, compressGif: Boolean, listener: OnUploadImageListListener) {
val postImageList = HashMap<String, String>()
Observable.create(ObservableOnSubscribe<Map<String, String>> {
val compressList = compressImageList(imgs, compressGif)
var listTotal = 0L // 总大小
var listProgress = 0L // 已上传的大小
for (img in compressList) {
listTotal += img.length()
}
for (img in compressList) {
val requestBody = FileRequestBody<ResponseBody>(img, object : RetrofitCallback<ResponseBody>() {
override fun onProgress(total: Long, progress: Long) {
listener.onProgress(listTotal, listProgress + progress)
}
})
val part = MultipartBody.Part.createFormData("Filedata", getFileName(img), requestBody)
RetrofitManager.getInstance(HaloApp.getInstance().application)
.uploadApi.uploadImage(part, type.name)
.subscribe(object : BiResponse<ResponseBody>() {
override fun onSuccess(data: ResponseBody) {
val string = data.string()
if (!string.isNullOrEmpty()) {
val url = JSONObject(string).getString("url")
if (!url.isNullOrEmpty()) {
val map = HashMap<String, String>()
map[img.path] = url
it.onNext(map)
return
}
}
onFailure(IllegalAccessException("HeHe"))
}
override fun onFailure(exception: Exception) {
it.onError(exception)
}
})
listProgress += img.length()
}
it.onComplete()
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<Map<String, String>> {
override fun onSubscribe(d: Disposable) {
}
override fun onComplete() {
if (postImageList.size == 0) {
listener.onError()
} else {
listener.onSuccess(postImageList)
}
}
override fun onNext(t: Map<String, String>) {
postImageList.putAll(t)
}
override fun onError(e: Throwable) {
}
})
}
// 同步调用->避免在主线程调用以免阻塞主线程
private fun compressImageList(imgs: List<String>, compressGif: Boolean): List<File> {
val compressList: MutableList<File> = ArrayList()
for (img in imgs) {
compressList.add(CompressImageUtils.compressImageAndSaveToFile(File(img), compressGif))
}
return compressList
}
// 同步调用->避免在主线程调用以免阻塞主线程
private fun compressImage(imgPath: String, compressGif: Boolean): File {
return CompressImageUtils.compressImageAndSaveToFile(File(imgPath), compressGif)
}
// 防止GIF图片文件后缀不是GIF这个FileName只是告诉服务端后缀格式没有其他用处
private fun getFileName(file: File): String {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(file.absolutePath, options)
if (options.outMimeType.contains("gif") && !file.name.toLowerCase().contains(".gif".toLowerCase())) {
return System.currentTimeMillis().toString() + ".gif"
}
return file.name
}
interface OnUploadImageListener {
fun onSuccess(imageUrl: String)
fun onError(e: Throwable?)
fun onProgress(total: Long, progress: Long)
}
interface OnUploadImageListListener {
fun onSuccess(imageUrl: Map<String, String>) // key:sourceImage value:compressImage
fun onError() // 全部上传失败时回调
fun onProgress(total: Long, progress: Long)
}
}