index.uts 10.8 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
	SaveImageToPhotosAlbum, SaveImageToPhotosAlbumOptions, SaveImageToPhotosAlbumSuccess,
DCloud-yyl's avatar
DCloud-yyl 已提交
6 7 8
} from "../interface.uts";
import {
	UniError_ChooseImage, UniError_SaveImageToPhotosAlbum,
DCloud-yyl's avatar
DCloud-yyl 已提交
9
	MediaErrorImpl,UniError_PreviewImage
DCloud-yyl's avatar
DCloud-yyl 已提交
10
} from "../unierror.uts"
DCloud-yyl's avatar
DCloud-yyl 已提交
11
import { uniChooseImage, uniChooseVideo } from "../ChooseImageUtils.uts";
DCloud-yyl's avatar
DCloud-yyl 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25

import { UTSiOS } from "DCloudUTSFoundation";
import { NSFileManager } from "Foundation";
import { AVCaptureDevice, AVMediaType } from "AVFoundation";
import { PHPhotoLibrary, PhotosTypes, PHAccessLevel } from "Photos";
import { DCloudMediaCamera, DCloudMediaAlbum, DCloudImageBrowser, DCloudImageBrowserLoadImageDelegate } from "DCloudMediaPicker" assert { type: "implementationOnly" };

let mediaPicker : DCUniMediaPicker = new DCUniMediaPicker();

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 已提交
26
					mediaPicker.openCameraForImage(option, compressed)
DCloud-yyl's avatar
DCloud-yyl 已提交
27 28 29 30 31 32 33 34 35 36
				} 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 已提交
37
					mediaPicker.openAlbumForImage(option, count, 101)
DCloud-yyl's avatar
DCloud-yyl 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50
				} else {
					let error = new MediaErrorImpl(1101005, UniError_ChooseImage);
					option.fail?.(error)
					option.complete?.(error)
				}
			})
		}
	});
}

class DCUniMediaPicker {
	private mediaAlbum : DCloudMediaAlbum = new DCloudMediaAlbum();
	private mediaCamera : DCloudMediaCamera = new DCloudMediaCamera();
DCloud-yyl's avatar
DCloud-yyl 已提交
51 52
	openAlbumForImage(option : ChooseImageOptions, count : number, type : number){
		this.chooseImageWithAlbum(option,count,type);
DCloud-yyl's avatar
DCloud-yyl 已提交
53
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
54 55
	openCameraForImage(option : ChooseImageOptions, compressed : boolean){
		this.chooseImageWithCamera(option,compressed);
DCloud-yyl's avatar
DCloud-yyl 已提交
56 57 58 59 60 61 62
	}
	preview(options : PreviewImageOptions){
		this.previewImageWithOptions(options);
	}
	close(){
		this.closePreview();
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
63
	private chooseImageWithAlbum(option : ChooseImageOptions, count : number, type : number){
DCloud-yyl's avatar
DCloud-yyl 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
		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 => {
			this.mediaAlbum.start(options, success = (response : Map<AnyHashable, any>) : void => {
				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)
			})
		})
	}
	
DCloud-yyl's avatar
DCloud-yyl 已提交
114
	private chooseImageWithCamera(option : ChooseImageOptions, compressed : boolean){
DCloud-yyl's avatar
DCloud-yyl 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 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 182 183 184 185 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 233 234 235 236 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 290 291 292 293 294 295 296 297 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 334 335 336 337
		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);
		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 => {
			this.mediaCamera.start(options, success = (response : Map<AnyHashable, any>) : void => {
				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)
			})
		})
	}
	
	private imageBrowser = new PreviewImageBrowser()
	private closePreview(){
		this.imageBrowser.close()
	}
	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 => {
			this.imageBrowser.startPreview(op);
		})
		
		let success : PreviewImageSuccess = { errMsg: 'ok', "errSubject": UniError_PreviewImage }
		options.success?.(success)
		options.complete?.(success)
	}
}

function requestCameraPermission(completion : (status : number) => void) {
	let cameraAuthorized = AVCaptureDevice.authorizationStatus(for=AVMediaType.video)
	
	if (cameraAuthorized == AVAuthorizationStatus.authorized) {
		completion(1)
	} else if (cameraAuthorized == AVAuthorizationStatus.notDetermined) {
		AVCaptureDevice.requestAccess(for=AVMediaType.video, completionHandler = (result : Bool) : void => {
			if (result) {
				completion(1)
			} else {
				completion(0)
			}
		})
	} else {
		completion(0)
	}
}

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) {
		completion(1)
	} else if (albumAuthorized == PHAuthorizationStatus.notDetermined) {
		if (UTSiOS.available("iOS 14, *")) {
			const accessLevel = (level == "readWrite") ? PHAccessLevel.readWrite : PHAccessLevel.addOnly
			PHPhotoLibrary.requestAuthorization(for=accessLevel, handler = (result : PHAuthorizationStatus) : void => {
				if (result == PHAuthorizationStatus.authorized || result == PHAuthorizationStatus.limited) {
					completion(1)
				} else {
					completion(0)
				}
			})
		} else {
			PHPhotoLibrary.requestAuthorization((result : PHAuthorizationStatus) : void => {
				if (result == PHAuthorizationStatus.authorized) {
					completion(1)
				} else {
					completion(0)
				}
			})
		}
	} else {
		completion(0)
	}
}

export const previewImage : PreviewImage = function (options : PreviewImageOptions) {
	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);
	}
}



export const closePreviewImage : ClosePreviewImage = function (options : ClosePreviewImageOptions) {
	mediaPicker.close();
	let callback : ClosePreviewImageSuccess = {
		errMsg: "ok"
	}
	options.success?.(callback)
	options.complete?.(callback)
}

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)
		}
	})
}