ChooseMediaUtils.uts 17.0 KB
Newer Older
1
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
2 3 4
	ChooseImageOptions, ChooseImageSuccess, ChooseImageCropOptions,
	ChooseVideoOptions, ChooseVideoSuccess,
	GetVideoInfoSuccess,
5 6 7
} from "../../interface.uts"
import {
	UniError_ChooseImage, UniError_ChooseVideo,
DCloud-yyl's avatar
DCloud-yyl 已提交
8
	MediaErrorImpl
9 10
} from "../../unierror.uts"
import { getVideoMetadata } from "./MediaUtils.uts"
DCloud-yyl's avatar
DCloud-yyl 已提交
11
import { uniChooseImage, uniChooseVideo } from "../../ChooseImageUtils.uts"
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import { getUniActivity } from "io.dcloud.uts.android";
import Intent from 'android.content.Intent';
import File from 'java.io.File';
import MediaStore from 'android.provider.MediaStore';
import IMGEditActivity from "io.dcloud.uts.gallery.imageedit.IMGEditActivity";
import Media from "io.dcloud.uts.dmcbig.mediapicker.entity.Media";
import Uri from 'android.net.Uri';
import Parcelable from 'android.os.Parcelable';
import FileProvider from 'androidx.core.content.FileProvider';
import Build from 'android.os.Build';
import Manifest from 'android.Manifest';
import Listener from 'io.dcloud.uts.androidtranscoder.MediaTranscoder.Listener';
import MediaTranscoder from 'io.dcloud.uts.androidtranscoder.MediaTranscoder';
import MediaFormatStrategyPresets from 'io.dcloud.uts.androidtranscoder.format.MediaFormatStrategyPresets';
import CompressUtil from 'io.dcloud.uts.util.CompressUtil';

const GALLERY_MEDIA_PICKER_RESULT = 1004;

DCloud-yyl's avatar
DCloud-yyl 已提交
30 31
const mediaCachePath = UTSAndroid.getAppCachePath()+"uni-media/"

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
export function chooseMediaImage(option : ChooseImageOptions) {
	uniChooseImage(option, function (count : number, compressed : boolean, index : number) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			let requestPermissionList : Array<string> = [Manifest.permission.CAMERA]
			if (index == 1) {
				requestPermissionList = [Manifest.permission.READ_EXTERNAL_STORAGE]
				if (getUniActivity()!.getApplicationInfo().targetSdkVersion >= 33) {
					requestPermissionList = ["android.permission.READ_MEDIA_IMAGES"]
				}
			}
			UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, requestPermissionList, (a : boolean, b : string[]) => {
				if (index == 0) {
					openCameraForImage(option, compressed)
				} else {
					openAlbumForImage(option, count, 100)
				}
			}, (a : boolean, b : string[]) => {
				// 失败回调
DCloud-yyl's avatar
DCloud-yyl 已提交
50
				let error = new MediaErrorImpl(1101005, UniError_ChooseImage);
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
				option.fail?.(error)
				option.complete?.(error)
			})
		} else {
			if (index == 0) {
				openCameraForImage(option, compressed)
			} else if (index == 1) {
				openAlbumForImage(option, count, 101)
			}
		}
	})
}

var cropFunction : ((requestCode : Int, resultCode : Int, data ?: Intent) => void) | null = null
var takeCameraFunction : ((requestCode : Int, resultCode : Int, data ?: Intent) => void) | null = null

function openCameraForImage(option : ChooseImageOptions, compressed : boolean) {
	const cameraCode = 22;
	const IMAGE_CAPTURE_EDIT = 5011;
	if (cropFunction != null) {
		UTSAndroid.offAppActivityResult(cropFunction!)
	}
	if (takeCameraFunction != null) {
		UTSAndroid.offAppActivityResult(takeCameraFunction!)
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
76
	let cameraPath = (mediaCachePath + System.currentTimeMillis() + ".jpg") // .jpg为默认配置
77 78 79 80 81 82 83 84 85 86
	try {
		let picFile = new File(cameraPath);
		if (!picFile.getParentFile().exists()) {
			picFile.getParentFile().mkdirs()
		}

		cropFunction = (requestCode : Int, resultCode : Int, data ?: Intent) => {
			if (requestCode == IMAGE_CAPTURE_EDIT) {
				UTSAndroid.offAppActivityResult(cropFunction!)
				if (resultCode == -1) {
DCloud-yyl's avatar
DCloud-yyl 已提交
87
					let success : ChooseImageSuccess = {
88 89 90 91 92 93 94 95
						"errSubject": "uni-chooseImage",
						"tempFilePaths": ["file://" + cameraPath],
						"errMsg": "chooseImage:ok",
						"tempFiles": [{ "path": "file://" + cameraPath, "size": picFile.length() }]
					}
					option.success?.(success)
					option.complete?.(success)
				} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
96
					let error = new MediaErrorImpl(1101007, UniError_ChooseImage);
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
					option.fail?.(error)
					option.complete?.(error)
				}
			}
		}

		takeCameraFunction = (requestCode : Int, resultCode : Int, data ?: Intent) => {
			if (cameraCode == requestCode) {
				UTSAndroid.offAppActivityResult(takeCameraFunction!)
				if (resultCode == -1) {
					if (picFile.exists()) {
						// 图片裁切, 宽高都存在,且都大于0
						if (option.crop != null && option.crop!.height != null && option.crop!.width != null && option.crop!.height! > 0 && option.crop!.width > 0) {
							let media = new Media(cameraPath,
								"",
								System.currentTimeMillis(),
								MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE,
								1,
								/* IMGEditActivity.CAMERA_SCENE, */ -1001,
								picFile.getParent());
							let cropIntent = new Intent(getUniActivity(), IMGEditActivity().javaClass)
							let mUri = Uri.parse("file://" + media.path);
							cropIntent.putExtra("IMAGE_URI", mUri);
							cropIntent.putExtra("IMAGE_MEDIA_ID", media.id);
							cropIntent.putExtra("IMAGE_INDEX", 0); // 传入当前的index,修改结束后方便替换
							cropIntent.putExtra("IMAGE_CROP", JSON.stringify(option.crop!!));
							UTSAndroid.onAppActivityResult(cropFunction!)
							cropIntent.putExtra(/* IMGEditActivity.EXTRA_IMAGE_SAVE_PATH */"IMAGE_SAVE_PATH", media.path);
							getUniActivity()!!.startActivityForResult(cropIntent, IMAGE_CAPTURE_EDIT.toInt());
							getUniActivity()!!.overridePendingTransition(0, 0);
						} else {
							if (compressed) {
								cameraPath = CompressUtil.compressImage(cameraPath, cameraPath, false, getUniActivity()!!)
								picFile = new File(cameraPath)
							}
DCloud-yyl's avatar
DCloud-yyl 已提交
132
							let success : ChooseImageSuccess = {
133 134 135 136 137 138 139 140 141
								"errSubject": "uni-chooseImage",
								"tempFilePaths": ["file://" + cameraPath],
								"errMsg": "chooseImage:ok",
								"tempFiles": [{ "path": "file://" + cameraPath, "size": picFile.length() }]
							}
							option.success?.(success)
							option.complete?.(success)
						}
					} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
142
						let error = new MediaErrorImpl(1101008, UniError_ChooseImage);
143 144 145 146
						option.fail?.(error)
						option.complete?.(error)
					}
				} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
147
					let error = new MediaErrorImpl(1101008, UniError_ChooseImage);
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
					option.fail?.(error)
					option.complete?.(error)
				}
			}
		}
		UTSAndroid.onAppActivityResult(takeCameraFunction!)
		let picUri : Uri = FileProvider.getUriForFile(getUniActivity()!, getUniActivity()!.packageName + ".dc.fileprovider", picFile);
		let intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
		getUniActivity()?.startActivityForResult(intent, cameraCode.toInt())
	} catch (e : Exception) { }
}

var albumFunction : ((requestCode : Int, resultCode : Int, data ?: Intent) => void) | null = null

/**
 * 
 * option
 * count
 * type PICKER_IMAGE = 100 PICKER_VIDEO = 102 PICKER_IMAGE_VIDEO = 101
 */
function openAlbumForImage(option : ChooseImageOptions, count : number, type : number) {
	if (albumFunction != null) {
		UTSAndroid.offAppActivityResult(albumFunction!)
	}
	albumFunction = (requestCode : Int, resultCode : Int, data ?: Intent) => {
		if (requestCode == GALLERY_MEDIA_PICKER_RESULT) {
			UTSAndroid.offAppActivityResult(albumFunction!)
			let picPaths : Array<string> = []
			let picTempPathJson : Array<UTSJSONObject> = []
			if (data != null) {
				let selectMediaResult : kotlin.collections.ArrayList<Parcelable> | null = data!!.getParcelableArrayListExtra("select_result");
				if (selectMediaResult != null) {
					selectMediaResult.forEach((current) => {
						let path = (current as Media).path;
						picPaths.push("file://" + (current as Media).path);
						let tempPathJson = {}
						tempPathJson["path"] = "file://" + path
						try {
							tempPathJson["size"] = new File(path).length()
						} catch (e) { }
						picTempPathJson.push(tempPathJson)
					})
				}
			}
			if (picPaths.length > 0) {
DCloud-yyl's avatar
DCloud-yyl 已提交
194
				let success : ChooseImageSuccess = {
195 196 197 198 199 200 201 202
					"errSubject": "uni-chooseImage",
					"tempFilePaths": picPaths,
					"errMsg": "chooseImage:ok",
					"tempFiles": picTempPathJson
				}
				option.success?.(success)
				option.complete?.(success)
			} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
203
				let error = new MediaErrorImpl(1101001, UniError_ChooseImage);
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
				option.fail?.(error)
				option.complete?.(error)
			}
		}
	}
	UTSAndroid.onAppActivityResult(albumFunction!)
	openGalleryActivity(count, type, false, option.sizeType, option.crop);
}

export function chooseMediaVideo(options : ChooseVideoOptions) {
	uniChooseVideo(options, (count : number, compressed : boolean, index : number) => {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			let requestPermissionList : Array<string> = [Manifest.permission.CAMERA]
			if (index == 1) {
				requestPermissionList = [Manifest.permission.READ_EXTERNAL_STORAGE]
				if (getUniActivity()!.getApplicationInfo().targetSdkVersion >= 33) {
					requestPermissionList = ["android.permission.READ_MEDIA_VIDEO"]
				}
			}
			UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, requestPermissionList, (a : boolean, b : string[]) => {
				if (index == 0) {
					openCameraForVideo(options, compressed)
				} else {
					openAlbumForVideo(options, count, 102, compressed)
				}
			}, (a : boolean, b : string[]) => {
				// 失败回调
				if (index == 0) {
DCloud-yyl's avatar
DCloud-yyl 已提交
232
					let error = new MediaErrorImpl(1101005, UniError_ChooseVideo);
233 234 235
					options.fail?.(error)
					options.complete?.(error)
				} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
236
					let error = new MediaErrorImpl(1101005, UniError_ChooseVideo);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
					options.fail?.(error)
					options.complete?.(error)
				}
			})
		} else {
			if (index == 0) {
				openCameraForVideo(options, compressed)
			} else if (index == 1) {
				openAlbumForVideo(options, count, 102, compressed)
			}
		}
	})
}

var takeVideoFunction : ((requestCode : Int, resultCode : Int, data ?: Intent) => void) | null = null

function openCameraForVideo(option : ChooseVideoOptions, compressed : boolean) {
	const cameraCode = 22;

	if (takeVideoFunction != null) {
		UTSAndroid.offAppActivityResult(takeVideoFunction!)
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
259
	let cameraPath = (mediaCachePath + System.currentTimeMillis() + ".mp4") // .mp4为默认配置
260 261 262 263 264 265 266 267 268 269 270 271 272
	try {
		let picFile = new File(cameraPath);
		if (!picFile.getParentFile().exists()) {
			picFile.getParentFile().mkdirs()
		}
		takeVideoFunction = (requestCode : Int, resultCode : Int, data ?: Intent) => {
			if (cameraCode == requestCode) {
				UTSAndroid.offAppActivityResult(takeVideoFunction!)
				if (resultCode == -1) {
					if (picFile.exists()) {
						if (compressed) {
							// cameraPath = CompressUtil.compressImage(cameraPath, cameraPath, false, getUniActivity()!!)
							// picFile = new File(cameraPath)
DCloud-yyl's avatar
DCloud-yyl 已提交
273
							let outPath = (mediaCachePath + System.currentTimeMillis() + ".mp4")
274 275
							MediaTranscoder.getInstance().transcodeVideo(cameraPath, outPath, MediaFormatStrategyPresets.createAndroid720pStrategy(2, 1.0), new MediaTranscoderListener(option, cameraPath, outPath))
						} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
276
							var metadata : GetVideoInfoSuccess | null = null
277
							let result = getVideoMetadata(cameraPath)
DCloud-yyl's avatar
DCloud-yyl 已提交
278 279
							if (result instanceof GetVideoInfoSuccess) {
								metadata = result as GetVideoInfoSuccess
280
							}
DCloud-yyl's avatar
DCloud-yyl 已提交
281
							let success : ChooseVideoSuccess = {
282 283 284 285 286 287 288 289 290 291
								tempFilePath: "file://" + cameraPath,
								width: metadata == null ? 0 : metadata!.width,
								height: metadata == null ? 0 : metadata!.height,
								size: metadata == null ? 0 : metadata!.size,
								duration: metadata == null ? 0 : metadata!.duration,
							}
							option.success?.(success)
							option.complete?.(success)
						}
					} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
292
						let error = new MediaErrorImpl(1101008, UniError_ChooseVideo);
293 294 295 296
						option.fail?.(error)
						option.complete?.(error)
					}
				} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
297
					let error = new MediaErrorImpl(1101008, UniError_ChooseVideo);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
					option.fail?.(error)
					option.complete?.(error)
				}
			}
		}
		UTSAndroid.onAppActivityResult(takeVideoFunction!)
		let picUri : Uri = FileProvider.getUriForFile(getUniActivity()!, getUniActivity()!.packageName + ".dc.fileprovider", picFile);
		let intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
		if (option.maxDuration != null && option.maxDuration! > 0) {
			intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, option.maxDuration!);
		}
		if (option.camera != null && option.camera! == "front") {
			intent.putExtra("android.intent.extras.CAMERA_FACING", 1);//前置摄像
		} else {
			intent.putExtra("android.intent.extras.CAMERA_FACING", 0);//后置摄像
		}
		getUniActivity()?.startActivityForResult(intent, cameraCode.toInt())
	} catch (e : Exception) { }
}

class MediaTranscoderListener implements Listener {
	option : ChooseVideoOptions
	inPath : string
	outPath : string
	constructor(option : ChooseVideoOptions, inPath : string, outPath : string) {
		this.option = option
		this.inPath = inPath
		this.outPath = outPath
	}
	override onTranscodeProgress(progress : Double) {

	}

	override onTranscodeCompleted() {
		this.deleteInPath()
DCloud-yyl's avatar
DCloud-yyl 已提交
334
		var metadata : GetVideoInfoSuccess | null = null
335
		let result = getVideoMetadata(this.outPath)
DCloud-yyl's avatar
DCloud-yyl 已提交
336 337
		if (result instanceof GetVideoInfoSuccess) {
			metadata = result as GetVideoInfoSuccess
338
		}
DCloud-yyl's avatar
DCloud-yyl 已提交
339
		let success : ChooseVideoSuccess = {
340 341 342 343 344 345 346 347 348 349 350 351
			tempFilePath: "file://" + this.outPath,
			width: metadata == null ? 0 : metadata!.width,
			height: metadata == null ? 0 : metadata!.height,
			size: metadata == null ? 0 : metadata!.size,
			duration: metadata == null ? 0 : metadata!.duration,
		}
		this.option.success?.(success)
		this.option.complete?.(success)
	}

	override onTranscodeCanceled() {
		this.deleteInPath()
DCloud-yyl's avatar
DCloud-yyl 已提交
352
		let error = new MediaErrorImpl(1101004, UniError_ChooseVideo);
353 354 355 356 357 358
		this.option.fail?.(error)
		this.option.complete?.(error)
	}

	override onTranscodeFailed(exception : Exception) {
		this.deleteInPath()
DCloud-yyl's avatar
DCloud-yyl 已提交
359
		let error = new MediaErrorImpl(1101010, UniError_ChooseVideo);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
		this.option.fail?.(error)
		this.option.complete?.(error)
	}

	deleteInPath() {
		let file = new File(this.inPath)
		if (file.exists()) {
			file.delete()
		}
	}
}

var openAlbumFunction : ((requestCode : Int, resultCode : Int, data ?: Intent) => void) | null = null

function openAlbumForVideo(option : ChooseVideoOptions, count : number, type : number, compressed : boolean) {
	if (openAlbumFunction != null) {
		UTSAndroid.offAppActivityResult(openAlbumFunction!)
	}
	openAlbumFunction = (requestCode : Int, resultCode : Int, data ?: Intent) => {
		if (requestCode == GALLERY_MEDIA_PICKER_RESULT) {
			UTSAndroid.offAppActivityResult(openAlbumFunction!)
			let picPaths = ""
			if (data != null) {
				let selectMediaResult : kotlin.collections.ArrayList<Parcelable> | null = data!!.getParcelableArrayListExtra("select_result");
				if (selectMediaResult != null && selectMediaResult!.size > 0) {
					picPaths = (selectMediaResult![0] as Media).path
				}
			}
			if (picPaths.isEmpty()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
389
				let error = new MediaErrorImpl(1101001, UniError_ChooseVideo);
390 391 392
				option.fail?.(error)
				option.complete?.(error)
			} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
393
				var metadata : GetVideoInfoSuccess | null = null
394
				let result = getVideoMetadata(picPaths)
DCloud-yyl's avatar
DCloud-yyl 已提交
395 396
				if (result instanceof GetVideoInfoSuccess) {
					metadata = result as GetVideoInfoSuccess
397
				}
DCloud-yyl's avatar
DCloud-yyl 已提交
398
				let success : ChooseVideoSuccess = {
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
					tempFilePath: "file://" + picPaths,
					width: metadata == null ? 0 : metadata!.width,
					height: metadata == null ? 0 : metadata!.height,
					size: metadata == null ? 0 : metadata!.size,
					duration: metadata == null ? 0 : metadata!.duration,
				}
				option.success?.(success)
				option.complete?.(success)
			}
		}
	}
	UTSAndroid.onAppActivityResult(openAlbumFunction!)
	openGalleryActivity(count, type, compressed, null, null);
}

DCloud-yyl's avatar
DCloud-yyl 已提交
414
function openGalleryActivity(count : number, type : number, compressed : boolean, sizeType ?: (string[]) | null, crop ?: ChooseImageCropOptions | null) {
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
	let selected : Array<string> = [];// 已选中的图片
	let maximum = -1;
	let editable = true; // 是否可编辑,对应editable
	let doneBtnText = "" // 完成按钮文字可编辑
	// let compressed = false; // 视频压缩,对应“videoCompress”

	let albumIntent = new Intent()
	albumIntent.setClassName(getUniActivity()!!, "io.dcloud.uts.dmcbig.mediapicker.PickerActivity");
	albumIntent.putExtra(/* SELECT_MODE = */"select_mode",/* PICKER_IMAGE_VIDEO = */type)
	albumIntent.putExtra(/* SINGLE_SELECT = */"single_select", false)
	albumIntent.putExtra(/* COMPRESSED = */"COMPRESSED", compressed)
	albumIntent.putExtra(/* MAX_SELECT_COUNT = */"max_select_count", count)
	// albumIntent.putExtra(/* DEFAULT_SELECTED_LIST = */"default_list",null); // 暂未对非uni的属性进行支持
	// albumIntent.putExtra(/* SELECTED_MAX_CALLBACK_ID = */"select_max_cb_id","") // 暂未对非uni的属性进行支持
	// albumIntent.putExtra(/* DONE_BUTTON_TEXT = */"done_button_text","")  // 暂未对非uni的属性进行支持
	if (sizeType != null) {
		albumIntent.putExtra(/* PickerConfig.SIZE_TYPE */"size_type", JSON.stringify(sizeType!))
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
433
	albumIntent.putExtra(/* DOC_PATH = */"doc_path", mediaCachePath)
434 435 436 437 438 439 440
	albumIntent.putExtra(/* IMAGE_EDITABLE = */"image_editable", true);
	if (crop != null && crop!.height != null && crop!.width != null && crop!.height! > 0 && crop!.width > 0) {
		albumIntent.putExtra(/* IMAGE_CROP = */"image_crop", JSON.stringify(crop))
		albumIntent.putExtra(/* MAX_SELECT_COUNT = */"max_select_count", 1)  // 编辑模式下只能选中一个
	}
	getUniActivity()!!.startActivityForResult(albumIntent, GALLERY_MEDIA_PICKER_RESULT.toInt())
}