index.uts 17.1 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3 4
import {
	ChooseImageOptions, ChooseImage, ChooseImageSuccess,
	PreviewImageOptions, PreviewImage, PreviewImageSuccess,
	ClosePreviewImage, ClosePreviewImageSuccess, ClosePreviewImageOptions,
DCloud-yyl's avatar
DCloud-yyl 已提交
5 6 7
	SaveImageToPhotosAlbum, SaveImageToPhotosAlbumOptions, SaveImageToPhotosAlbumSuccess,
	ChooseVideo, ChooseVideoOptions,
	SaveVideoToPhotosAlbum, SaveVideoToPhotosAlbumOptions, SaveVideoToPhotosAlbumSuccess, ChooseVideoSuccess,
DCloud-yyl's avatar
DCloud-yyl 已提交
8 9 10
} from "../interface.uts";
import {
	UniError_ChooseImage, UniError_SaveImageToPhotosAlbum,
DCloud-yyl's avatar
DCloud-yyl 已提交
11
	MediaErrorImpl,UniError_PreviewImage, UniError_ChooseVideo, UniError_SaveVideoToPhotosAlbum
DCloud-yyl's avatar
DCloud-yyl 已提交
12
} from "../unierror.uts"
DCloud-yyl's avatar
DCloud-yyl 已提交
13
import { uniChooseImage, uniChooseVideo } from "./ChooseImageUtils.uts";
DCloud-yyl's avatar
DCloud-yyl 已提交
14 15 16 17

import { UTSiOS } from "DCloudUTSFoundation";
import { NSFileManager } from "Foundation";
import { AVCaptureDevice, AVMediaType } from "AVFoundation";
DCloud-yyl's avatar
DCloud-yyl 已提交
18 19
import { PHPhotoLibrary, PhotosTypes, PHAccessLevel } from "Photos";
import { DCloudMediaCamera, DCloudMediaAlbum, DCloudImageBrowser, DCloudImageBrowserLoadImageDelegate } from "DCloudMediaPicker" assert { type: "implementationOnly" };
DCloud-yyl's avatar
DCloud-yyl 已提交
20

DCloud-yyl's avatar
DCloud-yyl 已提交
21
let mediaPicker : DCUniMediaPicker = new DCUniMediaPicker();
DCloud-yyl's avatar
DCloud-yyl 已提交
22 23 24 25 26 27

export const chooseImage : ChooseImage = function (option : ChooseImageOptions) {
	uniChooseImage(option, function (count : number, compressed : boolean, index : number) {
		if (index == 0) {
			requestCameraPermission(function (status : number) {
				if (status == 1) {
DCloud-yyl's avatar
DCloud-yyl 已提交
28
					mediaPicker.openCameraForImage(option)
DCloud-yyl's avatar
DCloud-yyl 已提交
29 30 31 32 33 34 35 36 37 38
				} else {
					let error = new MediaErrorImpl(1101005, UniError_ChooseImage);
					option.fail?.(error)
					option.complete?.(error)
				}
			})

		} else if (index == 1) {
			requestAlbumPermission("readWrite", function (status : number) {
				if (status == 1) {
DCloud-yyl's avatar
DCloud-yyl 已提交
39
					mediaPicker.openAlbumForImage(option, count)
DCloud-yyl's avatar
DCloud-yyl 已提交
40 41 42 43 44 45 46 47
				} else {
					let error = new MediaErrorImpl(1101005, UniError_ChooseImage);
					option.fail?.(error)
					option.complete?.(error)
				}
			})
		}
	});
DCloud-yyl's avatar
DCloud-yyl 已提交
48 49 50 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 76 77 78 79 80 81 82 83 84 85 86
}

export const chooseVideo : ChooseVideo = function (option : ChooseVideoOptions) {
	uniChooseVideo(option, (count : number, compressed : boolean, index : number) => {
		if (index == 0) {
			requestCameraPermission(function (status : number) {
				if (status == 1) {
					requestMicrophonePermission(function (status : number){
						if (status == 1) {
							mediaPicker.openCameraForVideo(option)
						}else{
							let error = new MediaErrorImpl(1101005, UniError_ChooseVideo);
							option.fail?.(error)
							option.complete?.(error)
						}
					})
					
				} else {
					let error = new MediaErrorImpl(1101005, UniError_ChooseVideo);
					option.fail?.(error)
					option.complete?.(error)
				}
			})
		
		} else if (index == 1) {
			requestAlbumPermission("readWrite", function (status : number) {
				if (status == 1) {
					mediaPicker.openAlbumForVideo(option)
				} else {
					let error = new MediaErrorImpl(1101005, UniError_ChooseVideo);
					option.fail?.(error)
					option.complete?.(error)
				}
			})
		}
	})
}

class DCUniMediaPicker {
DCloud-yyl's avatar
DCloud-yyl 已提交
87 88 89
	private mediaAlbum : DCloudMediaAlbum | null = null;
	private mediaCamera : DCloudMediaCamera | null = null;
	private imageBrowser : PreviewImageBrowser | null = null;
DCloud-yyl's avatar
DCloud-yyl 已提交
90 91 92 93 94 95 96 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
	openAlbumForImage(option : ChooseImageOptions, count : number){
		this.chooseImageWithAlbum(option,count);
	}
	openAlbumForVideo(option : ChooseVideoOptions){
		this.chooseVideoWithAlbum(option);
	}
	openCameraForVideo(option : ChooseVideoOptions){
		this.chooseVideoWithCamera(option);
	}
	openCameraForImage(option : ChooseImageOptions){
		this.chooseImageWithCamera(option);
	}
	preview(options : PreviewImageOptions){
		this.previewImageWithOptions(options);
	}
	close(){
		this.closePreview();
	}
	
	private chooseVideoWithAlbum(option : ChooseVideoOptions){
		const mediaCachePath = UTSiOS.getMediaCacheDir() + "/"
		let fileManager = FileManager.default
		if (fileManager.fileExists(atPath = mediaCachePath) == false) {
			try {
				UTSiOS.try(fileManager.createDirectory(atPath = mediaCachePath, withIntermediateDirectories = true, attributes = null))
			} catch (e) {
				console.log(e)
			}
		}
		let options : Map<string, any> = new Map();
		options.set('resolution', "high");
		options.set('videoCompress', option.compressed);
		options.set('filePath', mediaCachePath);
		options.set('maximum', 1);
		options.set('filter', "video");
		DispatchQueue.main.async(execute = () : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
126 127 128 129
			if (this.mediaAlbum == null){
				this.mediaAlbum = new DCloudMediaAlbum();
			}
			this.mediaAlbum?.start(options, success = (response : Map<AnyHashable, any>) : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 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
				const filePath : string = response.get('tempFilePath') as string
				let success : ChooseVideoSuccess = {
					tempFilePath: "file://" + filePath,
					width: response.get('width'),
					height: response.get('height'),
					size: response.get('size'),
					duration: response.get('duration'),
				}
				option.success?.(success)
				option.complete?.(success)
			}, fail = (code : number) : void => {
				let mediaError = new MediaErrorImpl(code, UniError_ChooseVideo);
				option.fail?.(mediaError)
				option.complete?.(mediaError)
			})
		})
	}
	
	private chooseImageWithAlbum(option : ChooseImageOptions, count : number){
		const mediaCachePath = UTSiOS.getMediaCacheDir() + "/"
		let fileManager = FileManager.default
		if (fileManager.fileExists(atPath = mediaCachePath) == false) {
			try {
				UTSiOS.try(fileManager.createDirectory(atPath = mediaCachePath, withIntermediateDirectories = true, attributes = null))
			} catch (e) {
				console.log(e)
			}
		}
		let options : Map<string, any> = new Map();
		options.set('resolution', "high");
		options.set('sizeType', option.sizeType);
		options.set('filePath', mediaCachePath);
		if (count > 0) {
			options.set('maximum', count);
		}
		if (option.crop != null) {
			let crop : Map<string, any> = new Map();
			if (option.crop!.width != nil) {
				crop.set('width', option.crop?.width);
			}
			if (option.crop!.height != nil) {
				crop.set('height', option.crop?.height);
			}
			if (option.crop!.resize != nil) {
				crop.set('resize', option.crop?.resize);
			}
			if (option.crop!.quality != nil) {
				crop.set('quality', option.crop?.quality);
			}
			options.set('crop', crop);
		}
		DispatchQueue.main.async(execute = () : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
182 183 184 185
			if (this.mediaAlbum == null){
				this.mediaAlbum = new DCloudMediaAlbum();
			}
			this.mediaAlbum?.start(options, success = (response : Map<AnyHashable, any>) : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 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 232
				let success : ChooseImageSuccess = {
					"errSubject": "uni-chooseImage",
					"tempFilePaths": response.get('tempFilePaths'),
					"errMsg": "chooseImage:ok",
					"tempFiles": response.get('tempFiles')
				}
				option.success?.(success)
				option.complete?.(success)
			}, fail = (code : number) : void => {
				let mediaError = new MediaErrorImpl(code, UniError_ChooseImage);
				option.fail?.(mediaError)
				option.complete?.(mediaError)
			})
		})
	}
	
	private chooseVideoWithCamera(option : ChooseVideoOptions){
		const mediaCachePath = UTSiOS.getMediaCacheDir() + "/"
		const fileManager = FileManager.default
		if (fileManager.fileExists(atPath = mediaCachePath) == false) {
			try {
				UTSiOS.try(fileManager.createDirectory(atPath = mediaCachePath, withIntermediateDirectories = true, attributes = null))
			} catch (e) {
				console.log(e)
			}
		}
		
		const currentTime = Int(Date().timeIntervalSince1970)
		const cameraPath = (mediaCachePath + currentTime.toString() + ".mp4")
		
		let options : Map<string, any> = new Map();
		options.set('resolution', "high");
		options.set('videoCompress', option.compressed);
		options.set('filePath', cameraPath);
		options.set('type', "video");
		if (option.maxDuration != null){
			if(option.maxDuration! > 0){
				options.set('videoMaximumDuration', option.maxDuration);
			}
		}else{
			options.set('videoMaximumDuration', 60);
		}
		if (option.camera != null){
			options.set('index', option.camera == "front" ? 2 : 1);
		}
		
		DispatchQueue.main.async(execute = () : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
233 234 235 236
			if (this.mediaCamera == null){
				this.mediaCamera = new DCloudMediaCamera();
			}
			this.mediaCamera?.start(options, success = (response : Map<AnyHashable, any>) : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
				let success : ChooseVideoSuccess = {
					tempFilePath: "file://" + cameraPath,
					width: response.get('width'),
					height: response.get('height'),
					size: response.get('size'),
					duration: response.get('duration'),
				}
				option.success?.(success)
				option.complete?.(success)
			}, fail = (code : number) : void => {
				let mediaError = new MediaErrorImpl(code, UniError_ChooseVideo);
				option.fail?.(mediaError)
				option.complete?.(mediaError)
			})
		})
	}
	
	private chooseImageWithCamera(option : ChooseImageOptions){
		const mediaCachePath = UTSiOS.getMediaCacheDir() + "/"
		const fileManager = FileManager.default
		if (fileManager.fileExists(atPath = mediaCachePath) == false) {
			try {
				UTSiOS.try(fileManager.createDirectory(atPath = mediaCachePath, withIntermediateDirectories = true, attributes = null))
			} catch (e) {
				console.log(e)
			}
		}
		
		const currentTime = Int(Date().timeIntervalSince1970)
		const cameraPath = (mediaCachePath + currentTime.toString() + ".jpg")
		
		let options : Map<string, any> = new Map();
		options.set('resolution', "high");
		options.set('sizeType', option.sizeType);
		options.set('filePath', cameraPath);
		options.set('type', "image");
		if (option.crop != null) {
			let crop : Map<string, any> = new Map();
			if (option.crop!.width != nil) {
				crop.set('width', option.crop?.width);
			}
			if (option.crop!.height != nil) {
				crop.set('height', option.crop?.height);
			}
			if (option.crop!.resize != nil) {
				crop.set('resize', option.crop?.resize);
			}
			if (option.crop!.quality != nil) {
				crop.set('quality', option.crop?.quality);
			}
			options.set('crop', crop);
		}
		DispatchQueue.main.async(execute = () : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
290 291 292 293
			if (this.mediaCamera == null){
				this.mediaCamera = new DCloudMediaCamera();
			}
			this.mediaCamera?.start(options, success = (response : Map<AnyHashable, any>) : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
				let success : ChooseImageSuccess = {
					"errSubject": "uni-chooseImage",
					"tempFilePaths": ["file://" + cameraPath],
					"errMsg": "chooseImage:ok",
					"tempFiles": response.get('tempFiles')
				}
				option.success?.(success)
				option.complete?.(success)
			}, fail = (code : number) : void => {
				let mediaError = new MediaErrorImpl(code, UniError_ChooseImage);
				option.fail?.(mediaError)
				option.complete?.(mediaError)
			})
		})
	}
	
DCloud-yyl's avatar
DCloud-yyl 已提交
310
	
DCloud-yyl's avatar
DCloud-yyl 已提交
311
	private closePreview(){
DCloud-yyl's avatar
DCloud-yyl 已提交
312 313 314 315 316 317
		DispatchQueue.main.async(execute=():void => {
			if (this.imageBrowser == null){
				this.imageBrowser = new PreviewImageBrowser();
			}
			this.imageBrowser?.close();
		})
DCloud-yyl's avatar
DCloud-yyl 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
	}
	private previewImageWithOptions(options : PreviewImageOptions){
		
		const op: Map<string,any> = new Map();
		let images: Array<any> = [];
		for (var i = 0; i < options.urls.length; i++) {
			const item : Map<string,any> = new Map();
			item.set('src', options.urls[i]);
			item.set("path", UTSiOS.getResourceAbsolutePath(options.urls[i], null));
			images.push(item)
		}
		op.set('images', images);
		if (options.current != null) {
			op.set('current', options.current);
		}
		if (options.indicator != null) {
			op.set('indicator', options.indicator);
		}
		op.set('loop', options.loop);
		op.set("cachePath", UTSiOS.getMediaCacheDir());
		DispatchQueue.main.async(execute=():void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
339 340 341 342
			if (this.imageBrowser == null){
				this.imageBrowser = new PreviewImageBrowser();
			}
			this.imageBrowser?.startPreview(op);
DCloud-yyl's avatar
DCloud-yyl 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
		})
		
		let success : PreviewImageSuccess = { errMsg: 'ok', "errSubject": UniError_PreviewImage }
		options.success?.(success)
		options.complete?.(success)
	}
}

function requestMicrophonePermission(completion : (status : number) => void) {
	let authorized = AVCaptureDevice.authorizationStatus(for= AVMediaType.audio)
	if (authorized == AVAuthorizationStatus.authorized) {
		completion(1)
	} else if (authorized == AVAuthorizationStatus.notDetermined) {
		AVCaptureDevice.requestAccess(for=AVMediaType.audio, completionHandler = (result : Bool) : void => {
			if (result) {
				completion(1)
			} else {
				completion(0)
			}
		})
	} else {
		completion(0)
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
366 367
}

DCloud-yyl's avatar
DCloud-yyl 已提交
368 369 370 371
function requestCameraPermission(completion : (status : number) => void) {
	let cameraAuthorized = AVCaptureDevice.authorizationStatus(for=AVMediaType.video)
	
	if (cameraAuthorized == AVAuthorizationStatus.authorized) {
DCloud-yyl's avatar
DCloud-yyl 已提交
372
		completion(1)
DCloud-yyl's avatar
DCloud-yyl 已提交
373 374
	} else if (cameraAuthorized == AVAuthorizationStatus.notDetermined) {
		AVCaptureDevice.requestAccess(for=AVMediaType.video, completionHandler = (result : Bool) : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
375 376 377 378 379 380 381 382 383 384 385
			if (result) {
				completion(1)
			} else {
				completion(0)
			}
		})
	} else {
		completion(0)
	}
}

DCloud-yyl's avatar
DCloud-yyl 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
function requestAlbumPermission(level : string, completion : (status : number) => void) {
	let albumAuthorized = PHAuthorizationStatus.notDetermined
	if (UTSiOS.available("iOS 14, *")) {
		const level: PHAccessLevel = PHAccessLevel.readWrite
		albumAuthorized = PHPhotoLibrary.authorizationStatus(for=level)
	}else{
		albumAuthorized = PHPhotoLibrary.authorizationStatus()
	}
	
	if (UTSiOS.available("iOS 14, *")) {
		if (albumAuthorized == PHAuthorizationStatus.authorized || albumAuthorized == PHAuthorizationStatus.limited) {
			completion(1)
			return;
		}
	}
	if (albumAuthorized == PHAuthorizationStatus.authorized) {
DCloud-yyl's avatar
DCloud-yyl 已提交
402
		completion(1)
DCloud-yyl's avatar
DCloud-yyl 已提交
403
	} else if (albumAuthorized == PHAuthorizationStatus.notDetermined) {
DCloud-yyl's avatar
DCloud-yyl 已提交
404 405
		if (UTSiOS.available("iOS 14, *")) {
			const accessLevel = (level == "readWrite") ? PHAccessLevel.readWrite : PHAccessLevel.addOnly
DCloud-yyl's avatar
DCloud-yyl 已提交
406 407
			PHPhotoLibrary.requestAuthorization(for=accessLevel, handler = (result : PHAuthorizationStatus) : void => {
				if (result == PHAuthorizationStatus.authorized || result == PHAuthorizationStatus.limited) {
DCloud-yyl's avatar
DCloud-yyl 已提交
408 409 410 411 412 413 414
					completion(1)
				} else {
					completion(0)
				}
			})
		} else {
			PHPhotoLibrary.requestAuthorization((result : PHAuthorizationStatus) : void => {
DCloud-yyl's avatar
DCloud-yyl 已提交
415
				if (result == PHAuthorizationStatus.authorized) {
DCloud-yyl's avatar
DCloud-yyl 已提交
416 417 418 419 420 421 422 423 424 425 426 427
					completion(1)
				} else {
					completion(0)
				}
			})
		}
	} else {
		completion(0)
	}
}

export const previewImage : PreviewImage = function (options : PreviewImageOptions) {
DCloud-yyl's avatar
DCloud-yyl 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
	if (options.urls.length > 0) {
		mediaPicker.preview(options);
	}else{
		let error = new MediaErrorImpl(1101002, UniError_PreviewImage);
		options.fail?.(error)
		options.complete?.(error)
	}
}
@UTSiOS.keyword("private") class PreviewImageBrowser implements DCloudImageBrowserLoadImageDelegate {
	private browser = new DCloudImageBrowser(frame=CGRectZero);
	
	startPreview(options: Map<string,any>){
		preview(options);
	}
	
	private preview(options: Map<string,any>){
		let window = UTSiOS.getKeyWindow()
		browser.frame = window.bounds;
		browser.loadImageDelegate = this;
		browser.setupOptions(options);
		window.addSubview(browser);
	}
	
	close(){
		closePreview()
	}
	
	private closePreview(){
		browser.exitBroswerMode();
	}

	dispatchLoadImage(url: String,@argumentLabel("") completion:(res: UIImage) => void) {
		UTSiOS.loadImage(url,completion);
	}
}

DCloud-yyl's avatar
DCloud-yyl 已提交
464 465


DCloud-yyl's avatar
DCloud-yyl 已提交
466 467 468 469 470 471 472
export const closePreviewImage : ClosePreviewImage = function (options : ClosePreviewImageOptions) {
	mediaPicker.close();
	let callback : ClosePreviewImageSuccess = {
		errMsg: "ok"
	}
	options.success?.(callback)
	options.complete?.(callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
}

export const saveImageToPhotosAlbum : SaveImageToPhotosAlbum = function (options : SaveImageToPhotosAlbumOptions) {
	const path = UTSiOS.getResourceAbsolutePath(options.filePath,null)
	let url = new URL(string = path)
	if (url == null) {
		let error = new MediaErrorImpl(1101003, UniError_SaveImageToPhotosAlbum);
		options.fail?.(error)
		options.complete?.(error)
		return
	}
	requestAlbumPermission("addOnly", function (status : number) {
		if (status == 1) {
			try {
				UTSiOS.try(PHPhotoLibrary.shared().performChangesAndWait(() : void => {
					PHAssetCreationRequest.creationRequestForAssetFromImage(atFileURL = url!)
				}))
				let success : SaveImageToPhotosAlbumSuccess = {
					"path": path
				}
				options.success?.(success)
				options.complete?.(success)
			} catch (e) {
				let error = new MediaErrorImpl(1101006, UniError_SaveImageToPhotosAlbum);
				options.fail?.(error)
				options.complete?.(error)
			}
		} else {
			let error = new MediaErrorImpl(1101005, UniError_SaveImageToPhotosAlbum);
			options.fail?.(error)
			options.complete?.(error)
		}
	})
DCloud-yyl's avatar
DCloud-yyl 已提交
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
}

export const saveVideoToPhotosAlbum : SaveVideoToPhotosAlbum = function (options : SaveVideoToPhotosAlbumOptions) {
	const path = UTSiOS.getResourceAbsolutePath(options.filePath,null)
	let url = new URL(string = path)
	if (url == null) {
		let error = new MediaErrorImpl(1101003, UniError_SaveVideoToPhotosAlbum);
		options.fail?.(error)
		options.complete?.(error)
		return
	}
	requestAlbumPermission("addOnly", function (status : number) {
		if (status == 1) {
			try {
				UTSiOS.try(PHPhotoLibrary.shared().performChangesAndWait(() : void => {
					PHAssetCreationRequest.creationRequestForAssetFromVideo(atFileURL = url!)
				}))
				let success : SaveVideoToPhotosAlbumSuccess = {}
				options.success?.(success)
				options.complete?.(success)
			} catch (e) {
				let error = new MediaErrorImpl(1101006, UniError_SaveVideoToPhotosAlbum);
				options.fail?.(error)
				options.complete?.(error)
			}
		} else {
			let error = new MediaErrorImpl(1101005, UniError_SaveVideoToPhotosAlbum);
			options.fail?.(error)
			options.complete?.(error)
		}
	})
DCloud-yyl's avatar
DCloud-yyl 已提交
537
}