ClassifyPhotoPlugin.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import Flutter
  2. import StoreKit
  3. import Photos
  4. import UIKit
  5. public class ClassifyPhotoPlugin: NSObject, FlutterPlugin {
  6. var photoClassifier = ClassifyPhoto()
  7. public static func register(with registrar: FlutterPluginRegistrar) {
  8. let channel = FlutterMethodChannel(name: "classify_photo", binaryMessenger: registrar.messenger())
  9. let instance = ClassifyPhotoPlugin()
  10. registrar.addMethodCallDelegate(instance, channel: channel)
  11. }
  12. public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
  13. print("iOS: Received method call: \(call.method)")
  14. switch call.method {
  15. case "getPhoto":
  16. self.getPhoto(flutterResult: result)
  17. case "getStorageInfo":
  18. getStorageInfo(result: result)
  19. // case "checkTrialEligibility":
  20. // if #available(iOS 15.0, *) {
  21. // Task {
  22. // let handler = SubscriptionHandler()
  23. // let isEligible = await handler.checkTrialEligibility()
  24. // DispatchQueue.main.async {
  25. // result(isEligible)
  26. // }
  27. // }
  28. // }
  29. case "getExifInfo":
  30. guard let args = call.arguments as? [String: Any],
  31. let filePath = args["filePath"] as? String else {
  32. result(FlutterError(
  33. code: "INVALID_ARGUMENTS",
  34. message: "Missing filePath parameter",
  35. details: nil
  36. ))
  37. return
  38. }
  39. getExifInfo(filePath: filePath, completion: result)
  40. case "getPlatformVersion":
  41. result("iOS " + UIDevice.current.systemVersion)
  42. default:
  43. result(FlutterMethodNotImplemented)
  44. }
  45. }
  46. private class func blankof<T>(type:T.Type) -> T {
  47. let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size)
  48. let val = ptr.pointee
  49. return val
  50. }
  51. /// 磁盘总大小
  52. private class func getTotalDiskSize() -> Int64 {
  53. var fs = blankof(type: statfs.self)
  54. if statfs("/var",&fs) >= 0{
  55. return Int64(UInt64(fs.f_bsize) * fs.f_blocks)
  56. }
  57. return -1
  58. }
  59. private func getStorageInfo(result: @escaping FlutterResult) {
  60. DispatchQueue.global(qos: .userInitiated).async {
  61. var storageInfo: [String: Int64] = [:]
  62. // 获取总容量和可用容量
  63. if let space = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) {
  64. let totalSpace = ClassifyPhotoPlugin.getTotalDiskSize()
  65. let freeSpace = space[.systemFreeSize] as? Int64 ?? 0
  66. storageInfo["totalSpace"] = totalSpace
  67. storageInfo["freeSpace"] = freeSpace
  68. storageInfo["usedSpace"] = totalSpace - freeSpace
  69. }
  70. // 获取照片占用的空间
  71. let options = PHFetchOptions()
  72. let allPhotos = PHAsset.fetchAssets(with: .image, options: options)
  73. var photoSize: Int64 = 0
  74. let group = DispatchGroup()
  75. let queue = DispatchQueue(label: "com.app.photosize", attributes: .concurrent)
  76. let semaphore = DispatchSemaphore(value: 10) // 限制并发
  77. allPhotos.enumerateObjects { (asset, index, stop) in
  78. group.enter()
  79. semaphore.wait()
  80. let resources = PHAssetResource.assetResources(for: asset)
  81. if let resource = resources.first {
  82. queue.async {
  83. let options = PHAssetResourceRequestOptions()
  84. options.isNetworkAccessAllowed = true
  85. PHAssetResourceManager.default().requestData(
  86. for: resource,
  87. options: options,
  88. dataReceivedHandler: { data in
  89. photoSize += Int64(data.count)
  90. },
  91. completionHandler: { error in
  92. if let error = error {
  93. print("Error getting photo size: \(error)")
  94. }
  95. semaphore.signal()
  96. group.leave()
  97. }
  98. )
  99. }
  100. } else {
  101. semaphore.signal()
  102. group.leave()
  103. }
  104. }
  105. group.notify(queue: .main) {
  106. storageInfo["photoSpace"] = photoSize
  107. result(storageInfo)
  108. }
  109. }
  110. }
  111. private func getPhoto(flutterResult: @escaping FlutterResult) {
  112. DispatchQueue.global(qos: .userInitiated).async { [weak self] in
  113. guard let self = self else { return }
  114. let fetchOptions = PHFetchOptions()
  115. let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
  116. photoClassifier.classifyPhotos(
  117. assets: allPhotos,
  118. progressHandler: { (stage, progress) in
  119. print("Progress: \(stage) - \(progress)")
  120. },
  121. completion: { result in
  122. var resultData: [[String: Any]] = []
  123. let mainGroup = DispatchGroup()
  124. // 处理截图
  125. mainGroup.enter()
  126. self.processPhotoGroup(assets: result.screenshots, groupName: "screenshots", sizeInfo: result.screenshotsSize) { groupData in
  127. if !groupData.isEmpty {
  128. resultData.append(["group": groupData, "type": "screenshots"])
  129. }
  130. mainGroup.leave()
  131. }
  132. // 处理相似照片组
  133. for photoGroup in result.similarPhotos {
  134. mainGroup.enter()
  135. self.processPhotoGroup(assets: photoGroup, groupName: "similar", sizeInfo: result.similarPhotosSize) { groupData in
  136. if !groupData.isEmpty {
  137. resultData.append(["group": groupData, "type": "similar"])
  138. }
  139. mainGroup.leave()
  140. }
  141. }
  142. // 处理地点分组
  143. for (location, assets) in result.locations {
  144. mainGroup.enter()
  145. self.processPhotoGroup(assets: assets, groupName: location, sizeInfo: result.locationsSize) { groupData in
  146. if !groupData.isEmpty {
  147. resultData.append(["group": groupData, "type": "location", "name": location])
  148. }
  149. mainGroup.leave()
  150. }
  151. }
  152. // 处理人物分组
  153. for (person, assets) in result.people {
  154. mainGroup.enter()
  155. self.processPhotoGroup(assets: assets, groupName: person, sizeInfo: result.peopleSize) { groupData in
  156. if !groupData.isEmpty {
  157. resultData.append(["group": groupData, "type": "people"])
  158. }
  159. mainGroup.leave()
  160. }
  161. }
  162. // 处理模糊照片
  163. mainGroup.enter()
  164. self.processPhotoGroup(assets: result.blurryPhotos, groupName: "blurry", sizeInfo: result.blurryPhotosSize) { groupData in
  165. if !groupData.isEmpty {
  166. resultData.append(["group": groupData, "type": "blurry"])
  167. }
  168. mainGroup.leave()
  169. }
  170. mainGroup.notify(queue: .main) {
  171. print("Final result count: \(resultData.count)")
  172. flutterResult(resultData)
  173. }
  174. }
  175. )
  176. }
  177. }
  178. // 处理照片组的辅助方法
  179. private func processPhotoGroup(
  180. assets: [PHAsset],
  181. groupName: String,
  182. sizeInfo: ClassifyPhoto.PhotoSizeInfo,
  183. completion: @escaping ([String: Any]) -> Void
  184. ) {
  185. let photoProcessGroup = DispatchGroup()
  186. var photosData: [[String: Any]] = []
  187. for asset in assets {
  188. photoProcessGroup.enter()
  189. let options = PHContentEditingInputRequestOptions()
  190. options.isNetworkAccessAllowed = true
  191. asset.requestContentEditingInput(with: options) { (input, info) in
  192. defer { photoProcessGroup.leave() }
  193. if let input = input, let url = input.fullSizeImageURL {
  194. let photoInfo: [String: Any] = [
  195. "path": url.path,
  196. "id": asset.localIdentifier,
  197. "width": asset.pixelWidth,
  198. "height": asset.pixelHeight,
  199. "creationDate": asset.creationDate?.timeIntervalSince1970 ?? 0
  200. ]
  201. photosData.append(photoInfo)
  202. }
  203. }
  204. }
  205. photoProcessGroup.notify(queue: .main) {
  206. completion([
  207. "photos": photosData,
  208. "totalSize": sizeInfo.totalSize,
  209. "count": sizeInfo.count
  210. ])
  211. }
  212. }
  213. private func getExifInfo(filePath: String, completion: @escaping FlutterResult) {
  214. // 创建文件 URL
  215. let fileURL: URL
  216. if filePath.starts(with: "file://") {
  217. guard let url = URL(string: filePath) else {
  218. print("Invalid URL string: \(filePath)")
  219. completion([:])
  220. return
  221. }
  222. fileURL = url
  223. } else {
  224. fileURL = URL(fileURLWithPath: filePath)
  225. }
  226. // 检查文件是否存在
  227. guard FileManager.default.fileExists(atPath: fileURL.path) else {
  228. print("File does not exist at path: \(fileURL.path)")
  229. completion([:])
  230. return
  231. }
  232. // 创建图片源
  233. guard let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil) else {
  234. print("Failed to create image source for path: \(fileURL.path)")
  235. completion([:])
  236. return
  237. }
  238. var exifInfo: [String: Any] = [:]
  239. // 获取所有元数据
  240. if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: Any] {
  241. // EXIF 数据
  242. if let exif = imageProperties[kCGImagePropertyExifDictionary as String] as? [String: Any] {
  243. exifInfo["aperture"] = exif[kCGImagePropertyExifFNumber as String]
  244. exifInfo["exposureTime"] = exif[kCGImagePropertyExifExposureTime as String]
  245. exifInfo["iso"] = exif[kCGImagePropertyExifISOSpeedRatings as String]
  246. exifInfo["focalLength"] = exif[kCGImagePropertyExifFocalLength as String]
  247. exifInfo["dateTimeOriginal"] = exif[kCGImagePropertyExifDateTimeOriginal as String]
  248. }
  249. // TIFF 数据
  250. if let tiff = imageProperties[kCGImagePropertyTIFFDictionary as String] as? [String: Any] {
  251. exifInfo["make"] = tiff[kCGImagePropertyTIFFMake as String]
  252. exifInfo["model"] = tiff[kCGImagePropertyTIFFModel as String]
  253. }
  254. // GPS 数据
  255. if let gps = imageProperties[kCGImagePropertyGPSDictionary as String] as? [String: Any] {
  256. exifInfo["latitude"] = gps[kCGImagePropertyGPSLatitude as String]
  257. exifInfo["longitude"] = gps[kCGImagePropertyGPSLongitude as String]
  258. exifInfo["altitude"] = gps[kCGImagePropertyGPSAltitude as String]
  259. }
  260. // 图片基本信息
  261. exifInfo["pixelWidth"] = imageProperties[kCGImagePropertyPixelWidth as String]
  262. exifInfo["pixelHeight"] = imageProperties[kCGImagePropertyPixelHeight as String]
  263. exifInfo["dpi"] = imageProperties[kCGImagePropertyDPIHeight as String]
  264. exifInfo["colorModel"] = imageProperties[kCGImagePropertyColorModel as String]
  265. exifInfo["profileName"] = imageProperties[kCGImagePropertyProfileName as String]
  266. }
  267. completion(exifInfo)
  268. }
  269. }
  270. class SubscriptionHandler: NSObject {
  271. @available(iOS 15.0.0, *)
  272. func checkTrialEligibility() async -> Bool {
  273. do {
  274. // 获取产品信息
  275. let productIds = ["clean.vip.1week"]
  276. let products = try await Product.products(for: Set(productIds))
  277. // 检查第一个产品的试用资格
  278. if let product = products.first {
  279. return await product.subscription?.isEligibleForIntroOffer ?? false
  280. }
  281. return false
  282. } catch {
  283. print("Error checking trial eligibility: \(error)")
  284. return false
  285. }
  286. }
  287. }