-
Notifications
You must be signed in to change notification settings - Fork 322
/
PMManager.m
1742 lines (1542 loc) · 71.4 KB
/
PMManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
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
114
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
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
464
465
466
467
468
469
470
471
472
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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "NSString+PM_COMMON.h"
#import "PHAsset+PM_COMMON.h"
#import "PHAssetCollection+PM_COMMON.h"
#import "PHAssetResource+PM_COMMON.h"
#import "PMAssetPathEntity.h"
#import "PMCacheContainer.h"
#import "PMConvertUtils.h"
#import "PMFolderUtils.h"
#import "PMImageUtil.h"
#import "PMManager.h"
#import "PMMD5Utils.h"
#import "PMPathFilterOption.h"
@implementation PMManager {
PMCacheContainer *cacheContainer;
PHCachingImageManager *__cachingManager;
}
- (instancetype)init {
self = [super init];
if (self) {
cacheContainer = [PMCacheContainer new];
}
return self;
}
- (PHCachingImageManager *)cachingManager {
if (__cachingManager == nil) {
__cachingManager = [PHCachingImageManager new];
}
return __cachingManager;
}
- (NSArray<PMAssetPathEntity *> *)getAssetPathList:(int)type hasAll:(BOOL)hasAll onlyAll:(BOOL)onlyAll option:(NSObject <PMBaseFilter> *)option pathFilterOption:(PMPathFilterOption *)pathFilterOption {
NSMutableArray<PMAssetPathEntity *> *array = [NSMutableArray new];
PHFetchOptions *assetOptions = [self getAssetOptions:type filterOption:option];
PHFetchOptions *fetchCollectionOptions = [PHFetchOptions new];
PHFetchResult<PHAssetCollection *> *smartAlbumResult = [PHAssetCollection
fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchCollectionOptions];
if (onlyAll) {
if (smartAlbumResult && smartAlbumResult.count) {
for (PHAssetCollection *collection in smartAlbumResult) {
if (collection.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary) {
PMAssetPathEntity *pathEntity = [PMAssetPathEntity
entityWithId:collection.localIdentifier
name:collection.localizedTitle
assetCollection:collection
];
pathEntity.isAll = YES;
[array addObject:pathEntity];
break;
}
}
}
return array;
}
if ([pathFilterOption.type indexOfObject:@(PHAssetCollectionTypeSmartAlbum)] != NSNotFound) {
[self logCollections:smartAlbumResult option:assetOptions];
[self injectAssetPathIntoArray:array
result:smartAlbumResult
options:assetOptions
hasAll:hasAll
containsModified:option.containsModified
pathFilterOption:pathFilterOption
];
}
if ([pathFilterOption.type indexOfObject:@(PHAssetCollectionTypeAlbum)] != NSNotFound) {
PHFetchResult<PHAssetCollection *> *albumResult = [PHAssetCollection
fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchCollectionOptions];
[self logCollections:albumResult option:assetOptions];
[self injectAssetPathIntoArray:array
result:albumResult
options:assetOptions
hasAll:hasAll
containsModified:option.containsModified
pathFilterOption:pathFilterOption];
}
return array;
}
- (NSUInteger)getAssetCountFromPath:(NSString *)id type:(int)type filterOption:(NSObject<PMBaseFilter> *)filterOption {
PHFetchOptions *assetOptions = [self getAssetOptions:type filterOption:filterOption];
PHFetchOptions *fetchCollectionOptions = [PHFetchOptions new];
PHFetchResult<PHAssetCollection *> *result = [PHAssetCollection
fetchAssetCollectionsWithLocalIdentifiers:@[id]
options:fetchCollectionOptions];
if (result == nil || result.count == 0) {
return 0;
}
PHAssetCollection *collection = result[0];
NSUInteger count = [collection obtainAssetCount:assetOptions];
return count;
}
- (void)logCollections:(PHFetchResult *)collections option:(PHFetchOptions *)option {
if(!PMLogUtils.sharedInstance.isLog){
return;
}
for (PHCollection *phCollection in collections) {
if ([phCollection isKindOfClass:[PHAssetCollection class]]) {
PHAssetCollection *collection = (PHAssetCollection *) phCollection;
PHFetchResult<PHAsset *> *result = [PHAsset fetchKeyAssetsInAssetCollection:collection options:option];
NSLog(@"collection name = %@, count = %lu", collection.localizedTitle, (unsigned long)result.count);
} else {
NSLog(@"collection name = %@", phCollection.localizedTitle);
}
}
}
- (NSUInteger)getAssetCountWithType:(int)type option:(NSObject<PMBaseFilter> *)filter {
PHFetchOptions *options = [filter getFetchOptions:type];
PHFetchResult<PHAsset *> *result = [PHAsset fetchAssetsWithOptions:options];
return result.count;
}
- (NSArray<PMAssetEntity *> *)getAssetsWithType:(int)type option:(NSObject<PMBaseFilter> *)option start:(int)start end:(int)end {
PHFetchOptions *options = [option getFetchOptions:type];
PHFetchResult<PHAsset *> *result = [PHAsset fetchAssetsWithOptions:options];
NSUInteger endOffset = end;
if (endOffset > result.count) {
endOffset = result.count;
}
NSMutableArray<PMAssetEntity*>* array = [NSMutableArray new];
for (NSUInteger i = start; i < endOffset; i++){
if (i >= result.count) {
break;
}
PHAsset *asset = result[i];
PMAssetEntity *pmAsset = [self convertPHAssetToAssetEntity:asset needTitle:[option needTitle]];
[array addObject: pmAsset];
}
return array;
}
- (BOOL)existsWithId:(NSString *)assetId {
PHFetchResult<PHAsset *> *result =
[PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:[PHFetchOptions new]];
return result && result.count > 0;
}
- (BOOL)entityIsLocallyAvailable:(NSString *)assetId
resource:(PHAssetResource *)resource
isOrigin:(BOOL)isOrigin
subtype:(int)subtype
fileType:(AVFileType)fileType {
PHFetchResult<PHAsset *> *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:[PHFetchOptions new]];
if (!result) {
return NO;
}
PHAsset *asset = result.firstObject;
if (@available(iOS 9.1, *)) {
if ((subtype & PHAssetMediaSubtypePhotoLive) == PHAssetMediaSubtypePhotoLive) {
resource = [asset getLivePhotosResource];
}
}
if (@available(macOS 14.0, *)) {
if ((subtype & PHAssetMediaSubtypePhotoLive) == PHAssetMediaSubtypePhotoLive) {
resource = [asset getLivePhotosResource];
}
}
NSFileManager *fileManager = NSFileManager.defaultManager;
NSString *path = [self makeAssetOutputPath:asset
resource:resource
isOrigin:isOrigin
fileType:fileType
manager:fileManager];
BOOL isExist = [fileManager fileExistsAtPath:path];
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"Locally available for path %@: %hhd", path, isExist]];
if (isExist) {
return YES;
}
if (!resource) {
resource = [asset getCurrentResource];
}
if (!resource) {
return NO;
}
// If this returns NO, then the asset is in iCloud or not saved locally yet.
isExist = [[resource valueForKey:@"locallyAvailable"] boolValue];
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"Locally available for asset %@ resource %@: %hhd", assetId, resource, isExist]];
return isExist;
}
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCDFAInspection"
- (void)injectAssetPathIntoArray:(NSMutableArray<PMAssetPathEntity *> *)array
result:(PHFetchResult *)result
options:(PHFetchOptions *)options
hasAll:(BOOL)hasAll
containsModified:(BOOL)containsModified
pathFilterOption:(PMPathFilterOption *)pathFilterOption {
for (id collection in result) {
if (![collection isKindOfClass:[PHAssetCollection class]]) {
continue;
}
PHAssetCollection *assetCollection = (PHAssetCollection *) collection;
// // Check whether it's "Recently Deleted"
// if (assetCollection.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumRecentlyAdded
// || assetCollection.assetCollectionSubtype == 1000000201) {
// continue;
// }
// Check nullable id and name
NSString *localIdentifier = assetCollection.localIdentifier;
NSString *localizedTitle = assetCollection.localizedTitle;
if (!localIdentifier || localIdentifier.isEmpty || !localizedTitle || localizedTitle.isEmpty) {
continue;
}
// [[PMLogUtils sharedInstance] debug:[NSString stringWithFormat:@"id: %@, title: %@, type: %d subType: %d", localIdentifier, localizedTitle, (int)assetCollection.assetCollectionType, (int)assetCollection.assetCollectionSubtype]];
PMAssetPathEntity *entity = [PMAssetPathEntity entityWithId:localIdentifier name:localizedTitle assetCollection:assetCollection];
entity.isAll = assetCollection.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary;
if (containsModified) {
PHFetchResult<PHAsset *> *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];
entity.assetCount = fetchResult.count;
if (fetchResult.count > 0) {
PHAsset *asset = fetchResult.firstObject;
entity.modifiedDate = (long) asset.modificationDate.timeIntervalSince1970;
}
}
if (hasAll && entity.isAll) {
[array addObject:entity];
continue;
}
if ([pathFilterOption.subType indexOfObject:@(PHAssetCollectionSubtypeAny)] != NSNotFound ||
[pathFilterOption.subType indexOfObject:@(assetCollection.assetCollectionSubtype)] != NSNotFound) {
[array addObject:entity];
}
}
}
#pragma clang diagnostic pop
- (NSArray<PMAssetEntity *> *)getAssetListPaged:(NSString *)id type:(int)type page:(NSUInteger)page size:(NSUInteger)size filterOption:(NSObject<PMBaseFilter> *)filterOption {
NSMutableArray<PMAssetEntity *> *result = [NSMutableArray new];
PHFetchOptions *options = [PHFetchOptions new];
PHFetchResult<PHAssetCollection *> *fetchResult =
[PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[id]
options:options];
if (fetchResult && fetchResult.count == 0) {
return result;
}
PHAssetCollection *collection = fetchResult.firstObject;
PHFetchOptions *assetOptions = [self getAssetOptions:type filterOption:filterOption];
PHFetchResult<PHAsset *> *assetArray = [PHAsset fetchAssetsInAssetCollection:collection
options:assetOptions];
if (assetArray.count == 0) {
return result;
}
NSUInteger startIndex = page * size;
NSUInteger endIndex = startIndex + size - 1;
NSUInteger count = assetArray.count;
if (endIndex >= count) {
endIndex = count - 1;
}
BOOL imageNeedTitle = filterOption.needTitle;
BOOL videoNeedTitle = filterOption.needTitle;
for (NSUInteger i = startIndex; i <= endIndex; i++) {
NSUInteger index = i;
if (assetOptions.sortDescriptors == nil) {
index = count - i - 1;
}
PHAsset *asset = assetArray[index];
BOOL needTitle = NO;
if ([asset isVideo]) {
needTitle = videoNeedTitle;
} else if ([asset isImage]) {
needTitle = imageNeedTitle;
}
PMAssetEntity *entity = [self convertPHAssetToAssetEntity:asset needTitle:needTitle];
[result addObject:entity];
[cacheContainer putAssetEntity:entity];
}
return result;
}
- (NSArray<PMAssetEntity *> *)getAssetListRange:(NSString *)id type:(int)type start:(NSUInteger)start end:(NSUInteger)end filterOption:(NSObject<PMBaseFilter> *)filterOption {
NSMutableArray<PMAssetEntity *> *result = [NSMutableArray new];
PHFetchOptions *options = [PHFetchOptions new];
PHFetchResult<PHAssetCollection *> *fetchResult =
[PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[id]
options:options];
if (fetchResult && fetchResult.count == 0) {
return result;
}
PHAssetCollection *collection = fetchResult.firstObject;
PHFetchOptions *assetOptions = [self getAssetOptions:(int) type filterOption:filterOption];
PHFetchResult<PHAsset *> *assetArray = [PHAsset fetchAssetsInAssetCollection:collection
options:assetOptions];
if (assetArray.count == 0) {
return result;
}
NSUInteger startIndex = start;
NSUInteger endIndex = end - 1;
NSUInteger count = assetArray.count;
if (endIndex >= count) {
endIndex = count - 1;
}
for (NSUInteger i = startIndex; i <= endIndex; i++) {
NSUInteger index = i;
if (assetOptions.sortDescriptors == nil) {
index = count - i - 1;
}
PHAsset *asset = assetArray[index];
BOOL needTitle;
if ([asset isVideo]) {
needTitle = filterOption.needTitle;
} else if ([asset isImage]) {
needTitle = filterOption.needTitle;
} else {
needTitle = NO;
}
PMAssetEntity *entity = [self convertPHAssetToAssetEntity:asset needTitle:needTitle];
[result addObject:entity];
[cacheContainer putAssetEntity:entity];
}
return result;
}
- (PMAssetEntity *)convertPHAssetToAssetEntity:(PHAsset *)asset
needTitle:(BOOL)needTitle {
// type:
// 0: all , 1: image, 2:video
int type = 0;
if (asset.isImage) {
type = 1;
} else if (asset.isVideo) {
type = 2;
}
NSDate *date = asset.creationDate;
long createDt = (long) date.timeIntervalSince1970;
NSDate *modifiedDate = asset.modificationDate;
long modifiedTimeStamp = (long) modifiedDate.timeIntervalSince1970;
PMAssetEntity *entity = [PMAssetEntity entityWithId:asset.localIdentifier
createDt:createDt
width:asset.pixelWidth
height:asset.pixelHeight
duration:(long) asset.duration
type:type];
entity.phAsset = asset;
entity.modifiedDt = modifiedTimeStamp;
entity.lat = asset.location.coordinate.latitude;
entity.lng = asset.location.coordinate.longitude;
entity.title = needTitle ? [asset title] : @"";
entity.favorite = asset.isFavorite;
entity.subtype = asset.mediaSubtypes;
return entity;
}
- (PMAssetEntity *)getAssetEntity:(NSString *)assetId {
return [self getAssetEntity:assetId withCache:YES];
}
- (PMAssetEntity *)getAssetEntity:(NSString *)assetId withCache:(BOOL)withCache {
PMAssetEntity *entity;
if (withCache) {
entity = [cacheContainer getAssetEntity:assetId];
if (entity) {
return entity;
}
}
PHFetchResult<PHAsset *> *result =
[PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil];
if (result == nil || result.count == 0) {
return nil;
}
PHAsset *asset = result[0];
entity = [self convertPHAssetToAssetEntity:asset needTitle:NO];
[cacheContainer putAssetEntity:entity];
return entity;
}
- (void)clearCache {
[cacheContainer clearCache];
}
- (void)getThumbWithId:(NSString *)assetId option:(PMThumbLoadOption *)option resultHandler:(NSObject <PMResultHandler> *)handler progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler {
PMAssetEntity *entity = [self getAssetEntity:assetId];
if (entity && entity.phAsset) {
PHAsset *asset = entity.phAsset;
[self fetchThumb:asset option:option resultHandler:handler progressHandler:progressHandler];
} else {
[handler replyError:[NSString stringWithFormat:@"Asset %@ is not found", assetId]];
}
}
- (void)fetchThumb:(PHAsset *)asset option:(PMThumbLoadOption *)option resultHandler:(NSObject <PMResultHandler> *)handler progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler {
PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.deliveryMode = option.deliveryMode;
requestOptions.resizeMode = option.resizeMode;
[requestOptions setNetworkAccessAllowed:YES];
__block double lastProgress = 0.0;
[self notifyProgress:progressHandler progress:0 state:PMProgressStatePrepare];
[requestOptions setProgressHandler:^(double progress, NSError *error, BOOL *stop,
NSDictionary *info) {
if (error) {
[self notifyProgress:progressHandler progress:progress state:PMProgressStateFailed];
return;
}
lastProgress = progress;
if (progress != 1) {
[self notifyProgress:progressHandler progress:progress state:PMProgressStateLoading];
}
}];
int width = option.width;
int height = option.height;
[self.cachingManager requestImageForAsset:asset
targetSize:CGSizeMake(width, height)
contentMode:option.contentMode
options:requestOptions
resultHandler:^(PMImage *result, NSDictionary *info) {
if ([handler isReplied]) {
return;
}
NSObject *error = info[PHImageErrorKey];
if (error) {
[handler replyError:error];
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
return;
}
BOOL downloadFinished = [PMManager isDownloadFinish:info];
if (!downloadFinished) {
return;
}
NSData *imageData = [PMImageUtil convertToData:result formatType:option.format quality:option.quality];
if (imageData) {
id data = [self.converter convertData:imageData];
[handler reply:data];
[self notifySuccess:progressHandler];
} else {
[handler replyError:[NSString stringWithFormat:@"Failed to convert %@ to %u format.", asset.localIdentifier, option.format]];
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
}
}];
}
- (void)getFullSizeFileWithId:(NSString *)assetId
isOrigin:(BOOL)isOrigin
subtype:(int)subtype
fileType:(AVFileType)fileType
resultHandler:(NSObject <PMResultHandler> *)handler
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler {
PMAssetEntity *entity = [self getAssetEntity:assetId];
if (entity && entity.phAsset) {
PHAsset *asset = entity.phAsset;
if (@available(iOS 9.1, *)) {
if (asset.isLivePhoto && (subtype & PHAssetMediaSubtypePhotoLive) == PHAssetMediaSubtypePhotoLive) {
[self fetchLivePhotosFile:asset handler:handler progressHandler:progressHandler withScheme:NO fileType:fileType];
return;
}
}
if (@available(macOS 14.0, *)) {
if (asset.isLivePhoto && (subtype & PHAssetMediaSubtypePhotoLive) == PHAssetMediaSubtypePhotoLive) {
[self fetchLivePhotosFile:asset handler:handler progressHandler:progressHandler withScheme:NO fileType:fileType];
return;
}
}
if (asset.isVideo) {
if (isOrigin) {
[self fetchOriginVideoFile:asset handler:handler progressHandler:progressHandler fileType:fileType];
} else {
[self fetchFullSizeVideo:asset handler:handler progressHandler:progressHandler withScheme:NO fileType:fileType];
}
return;
}
if (isOrigin) {
[self fetchOriginImageFile:asset resultHandler:handler progressHandler:progressHandler];
} else {
[self fetchFullSizeImageFile:asset resultHandler:handler progressHandler:progressHandler];
}
return;
}
[handler replyError:[NSString stringWithFormat:@"Asset %@ file cannot be obtained.", assetId]];
}
- (void)fetchLivePhotosFile:(PHAsset *)asset
handler:(NSObject <PMResultHandler> *)handler
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler
withScheme:(BOOL)withScheme
fileType:(AVFileType)fileType {
PHAssetResource *resource = [asset getLivePhotosResource];
if (!resource) {
[handler replyError:[NSString stringWithFormat:@"Asset %@ does not have a Live-Photo resource.", asset.localIdentifier]];
return;
}
[self fetchResourceToFile:asset
resource:resource
progressHandler:progressHandler
withScheme:withScheme
isOrigin:YES
fileType:fileType
block:^(NSString *path, NSObject *error) {
if (path) {
[handler reply:path];
} else {
[handler replyError:error];
}
}];
}
- (void)fetchOriginVideoFile:(PHAsset *)asset
handler:(NSObject <PMResultHandler> *)handler
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler
fileType:(AVFileType)fileType {
PHAssetResource *resource = [asset getCurrentResource];
if (!resource) {
[handler replyError:[NSString stringWithFormat:@"Asset %@ does not have available resources.", asset.localIdentifier]];
return;
}
[self fetchResourceToFile:asset
resource:resource
progressHandler:progressHandler
withScheme:NO
isOrigin:YES
fileType:fileType
block:^(NSString *path, NSObject *error) {
if (path) {
[handler reply:path];
} else {
[handler replyError:error];
}
}];
}
- (void)fetchFullSizeVideo:(PHAsset *)asset
handler:(NSObject <PMResultHandler> *)handler
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler
withScheme:(BOOL)withScheme
fileType:(AVFileType)fileType {
[self exportAssetToFile:asset
progressHandler:progressHandler
withScheme:withScheme
fileType:fileType
block:^(NSString *path, NSObject *error) {
if (path) {
[handler reply:path];
} else {
[handler replyError:error];
}
}];
}
- (void)fetchResourceToFile:(PHAsset *)asset
resource:(PHAssetResource *)resource
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler
withScheme:(BOOL)withScheme
isOrigin:(BOOL)isOrigin
fileType:(AVFileType)fileType
block:(void (^)(NSString *path, NSObject *error))block {
NSFileManager *fileManager = NSFileManager.defaultManager;
NSString *path = [self makeAssetOutputPath:asset
resource:resource
isOrigin:isOrigin
fileType:nil
manager:fileManager];
if ([fileManager fileExistsAtPath:path]) {
if (fileType) {
NSString *originalPath = path;
NSString *path = [self makeAssetOutputPath:asset
resource:resource
isOrigin:isOrigin
fileType:fileType
manager:fileManager];
if ([fileManager fileExistsAtPath:path]) {
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"read cache from %@", path]];
[self notifySuccess:progressHandler];
if (withScheme) {
block([NSURL fileURLWithPath:path].absoluteString, nil);
} else {
block(path, nil);
}
return;
}
[self exportAVAssetToFile:originalPath
destination:path
progressHandler:progressHandler
withScheme:withScheme
fileType:fileType
block:^(NSString *path, NSObject *error) {
if (path) {
if (withScheme) {
block([NSURL fileURLWithPath:path].absoluteString, nil);
} else {
block(path, nil);
}
} else {
block(nil, error);
}
}];
return;
}
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"read cache from %@", path]];
[self notifySuccess:progressHandler];
if (withScheme) {
block([NSURL fileURLWithPath:path].absoluteString, nil);
} else {
block(path, nil);
}
return;
}
PHAssetResourceRequestOptions *options = [PHAssetResourceRequestOptions new];
[options setNetworkAccessAllowed:YES];
__block double lastProgress = 0.0;
[self notifyProgress:progressHandler progress:0 state:PMProgressStatePrepare];
[options setProgressHandler:^(double progress) {
lastProgress = progress;
if (progress != 1) {
[self notifyProgress:progressHandler progress:progress state:PMProgressStateLoading];
}
}];
PHAssetResourceManager *resourceManager = PHAssetResourceManager.defaultManager;
__block NSURL *fileUrl = [NSURL fileURLWithPath:path];
[resourceManager writeDataForAssetResource:resource
toFile:fileUrl
options:options
completionHandler:^(NSError *_Nullable error) {
if (error) {
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
block(nil, error);
return;
}
if (fileType) {
NSString *newPath = [self makeAssetOutputPath:asset
resource:resource
isOrigin:isOrigin
fileType:fileType
manager:fileManager];
fileUrl = [NSURL fileURLWithPath:newPath];
PHAssetResourceRequestOptions *options = [PHAssetResourceRequestOptions new];
[options setNetworkAccessAllowed:YES];
[resourceManager writeDataForAssetResource:resource
toFile:fileUrl
options:options
completionHandler:^(NSError *_Nullable error) {
if (path) {
[self notifySuccess:progressHandler];
if (withScheme) {
block([NSURL fileURLWithPath:path].absoluteString, nil);
} else {
block(newPath, nil);
}
} else {
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
block(nil, error);
}
}];
return;
}
[self notifySuccess:progressHandler];
if (withScheme) {
block([NSURL fileURLWithPath:path].absoluteString, nil);
} else {
block(path, nil);
}
}];
}
- (void)exportAssetToFile:(PHAsset *)asset
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler
withScheme:(BOOL)withScheme
fileType:(AVFileType)fileType
block:(void (^)(NSString *path, NSObject *error))block {
NSFileManager *manager = NSFileManager.defaultManager;
NSString *path = [self makeAssetOutputPath:asset resource:nil isOrigin:NO fileType:fileType manager:manager];
if ([manager fileExistsAtPath:path]) {
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"Read cache from %@", path]];
if (withScheme) {
block([NSURL fileURLWithPath:path].absoluteString, nil);
} else {
block(path, nil);
}
}
PHVideoRequestOptions *options = [PHVideoRequestOptions new];
[options setDeliveryMode:PHVideoRequestOptionsDeliveryModeAutomatic];
[options setNetworkAccessAllowed:YES];
[options setVersion:PHVideoRequestOptionsVersionCurrent];
__block double lastProgress = 0.0;
[self notifyProgress:progressHandler progress:0 state:PMProgressStatePrepare];
[options setProgressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
lastProgress = progress;
if (error) {
[self notifyProgress:progressHandler progress:progress state:PMProgressStateFailed];
return;
}
if (progress != 1) {
[self notifyProgress:progressHandler progress:progress state:PMProgressStateLoading];
}
}];
[self.cachingManager
requestAVAssetForVideo:asset
options:options
resultHandler:^(AVAsset *_Nullable asset, AVAudioMix *_Nullable audioMix, NSDictionary *_Nullable info) {
NSObject *error = info[PHImageErrorKey];
if (error) {
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
block(nil, error);
return;
}
BOOL downloadFinished = [PMManager isDownloadFinish:info];
if (!downloadFinished) {
return;
}
NSURL *destination = [NSURL fileURLWithPath:path];
// Check whether the asset is already an `AVURLAsset`,
// then copy the asset file into the sandbox instead of export.
if ([asset isKindOfClass:[AVURLAsset class]]) {
AVURLAsset *urlAsset = (AVURLAsset *) asset;
NSURL *videoURL = urlAsset.URL;
if ([[videoURL path] isEqualToString:[destination path]]) {
if (withScheme) {
block(videoURL.absoluteString, nil);
} else {
block([videoURL path], nil);
}
[self notifySuccess:progressHandler];
return;
}
NSError *error;
NSString *destinationPath = destination.path;
if ([manager fileExistsAtPath:destinationPath]) {
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"Reading cache from %@", destinationPath]];
if (withScheme) {
block(destination.absoluteString, nil);
} else {
block(destinationPath, nil);
}
[self notifySuccess:progressHandler];
return;
}
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"Caching the video to %@", destination]];
[[NSFileManager defaultManager] copyItemAtURL:videoURL
toURL:destination
error:&error];
if (error) {
block(nil, error);
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
return;
}
if (withScheme) {
block(destination.absoluteString, nil);
} else {
block(path, nil);
}
[self notifySuccess:progressHandler];
return;
}
// Export the asset eventually, typically for `AVComposition`s.
AVAssetExportSession *exportSession = [AVAssetExportSession
exportSessionWithAsset:asset
presetName:AVAssetExportPresetHighestQuality];
if (exportSession) {
NSString *extension = [[path pathExtension] lowercaseString];
// Determine the output type for the fastest speed.
AVFileType outputFileType;
if (fileType) {
outputFileType = fileType;
} else if ([extension isEqualToString:@"mov"]) {
outputFileType = AVFileTypeQuickTimeMovie;
} else if ([extension isEqualToString:@"m4v"]) {
outputFileType = AVFileTypeAppleM4V;
} else {
outputFileType = AVFileTypeMPEG4;
}
exportSession.outputFileType = outputFileType;
exportSession.outputURL = destination;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if (exportSession.status == AVAssetExportSessionStatusCompleted) {
if (withScheme) {
block(destination.absoluteString, nil);
} else {
block(path, nil);
}
[self notifySuccess:progressHandler];
} else if (exportSession.status == AVAssetExportSessionStatusFailed ||
exportSession.status == AVAssetExportSessionStatusCancelled) {
[self notifyProgress:progressHandler progress:lastProgress state:PMProgressStateFailed];
block(nil, exportSession.error);
}
}];
return;
}
[self notifyProgress: progressHandler progress:lastProgress state:PMProgressStateFailed];
block(nil, @"Unable to initialize an export session.");
}];
}
- (void)exportAVAssetToFile:(NSString *)path
destination:(NSString *)destination
progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler
withScheme:(BOOL)withScheme
fileType:(AVFileType)fileType
block:(void (^)(NSString *path, NSObject *error))block {
AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:path]];
// Export the asset eventually, typically for `AVComposition`s.
AVAssetExportSession *exportSession = [AVAssetExportSession
exportSessionWithAsset:asset
presetName:AVAssetExportPresetHighestQuality];
if (exportSession) {
NSString *extension = [[path pathExtension] lowercaseString];
// Determine the output type for the fastest speed.
AVFileType outputFileType;
if (fileType != nil) {
outputFileType = fileType;
} else if ([extension isEqualToString:@"mov"]) {
outputFileType = AVFileTypeQuickTimeMovie;
} else if ([extension isEqualToString:@"m4v"]) {
outputFileType = AVFileTypeAppleM4V;
} else {
outputFileType = AVFileTypeMPEG4;
}
exportSession.outputFileType = outputFileType;
exportSession.outputURL = [NSURL fileURLWithPath:destination];
[exportSession exportAsynchronouslyWithCompletionHandler:^{
if (exportSession.status == AVAssetExportSessionStatusCompleted) {
[self notifySuccess:progressHandler];
if (withScheme) {
block(destination, nil);
} else {
block(path, nil);
}
} else if (exportSession.status == AVAssetExportSessionStatusFailed ||
exportSession.status == AVAssetExportSessionStatusCancelled) {
[self notifyProgress:progressHandler progress:0.0 state:PMProgressStateFailed];
block(nil, exportSession.error);
}
}];
return;
}
[self notifyProgress: progressHandler progress:0.0 state:PMProgressStateFailed];
block(nil, @"Unable to initialize an export session.");
}
- (NSString *)makeAssetOutputPath:(PHAsset *)asset
resource:(PHAssetResource *)resource
isOrigin:(Boolean)isOrigin
fileType:(AVFileType)fileType
manager:(NSFileManager *)manager {
NSString *id = [asset.localIdentifier stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
NSString *modifiedDate = [NSString stringWithFormat:@"%f", asset.modificationDate.timeIntervalSince1970];
NSString *homePath = NSTemporaryDirectory();
NSMutableString *path = [NSMutableString stringWithString:homePath];
NSString *filename;
if (resource) {
filename = resource.originalFilename;
} else {
filename = [asset valueForKey:@"filename"];
}
filename = [NSString stringWithFormat:@"%@_%@%@_%@",
id, modifiedDate, isOrigin ? @"_o" : @"", filename];
if (fileType) {
NSString *newExtension = [PMConvertUtils convertAVFileTypeToExtension:fileType];
if (newExtension) {
NSString *filenameWithoutExtension = [filename stringByDeletingPathExtension];
filename = [filenameWithoutExtension stringByAppendingPathExtension:[newExtension stringByReplacingOccurrencesOfString:@"." withString:@""]];
}
}
// Convert the extension to lowercased.
NSString *extension = [filename pathExtension];
filename = [filename stringByDeletingPathExtension];
filename = [filename stringByAppendingPathExtension:[extension stringByReplacingOccurrencesOfString:@"." withString:@""]];
NSString *typeDirPath;
if (resource) {
if (resource.isImage) {
typeDirPath = PM_IMAGE_CACHE_PATH;
} else if (resource.isVideo) {
typeDirPath = PM_VIDEO_CACHE_PATH;
} else if (resource.isAudio) {
typeDirPath = PM_AUDIO_CACHE_PATH;
} else {
typeDirPath = PM_OTHER_CACHE_PATH;
}
} else {
if (asset.isImage) {
typeDirPath = PM_IMAGE_CACHE_PATH;
} else if (asset.isVideo) {
typeDirPath = PM_VIDEO_CACHE_PATH;
} else if (asset.isAudio) {
typeDirPath = PM_AUDIO_CACHE_PATH;
} else {
typeDirPath = PM_OTHER_CACHE_PATH;
}
}
NSString *dirPath = [NSString stringWithFormat:@"%@%@", homePath, typeDirPath];
if (manager == nil) {
manager = NSFileManager.defaultManager;
}
[manager createDirectoryAtPath:dirPath withIntermediateDirectories:true attributes:@{} error:nil];
[path appendFormat:@"%@/%@", typeDirPath, filename];
[PMLogUtils.sharedInstance info:[NSString stringWithFormat:@"PHAsset path = %@", path]];
return path;
}
- (NSString *)writeFullFileWithAssetId:(PHAsset *)asset imageData:(NSData *)imageData {
NSFileManager *manager = NSFileManager.defaultManager;
NSMutableString *path = [NSMutableString stringWithString:[self getCachePath:PM_FULL_IMAGE_CACHE_PATH]];
NSError *error;
[manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:@{} error:&error];
[path appendString:@"/"];
[path appendString:[PMMD5Utils getMD5FromString:asset.localIdentifier]];
[path appendString:@"_exif"];
[path appendString:@".jpg"];
[manager createFileAtPath:path contents:imageData attributes:@{}];
return path;
}
- (BOOL)isImage:(PHAssetResource *)resource {
return resource.type == PHAssetResourceTypePhoto || resource.type == PHAssetResourceTypeFullSizePhoto;
}
- (void)fetchOriginImageFile:(PHAsset *)asset resultHandler:(NSObject <PMResultHandler> *)handler progressHandler:(NSObject <PMProgressHandlerProtocol> *)progressHandler {
PHAssetResource *imageResource = [asset getCurrentResource];
if (!imageResource) {
[handler replyError:[NSString stringWithFormat:@"Asset %@ does not have available resources.", asset.localIdentifier]];
return;
}
NSFileManager *fileManager = NSFileManager.defaultManager;
NSString *path = [self makeAssetOutputPath:asset
resource:imageResource
isOrigin:YES
fileType:nil
manager:fileManager];
if ([fileManager fileExistsAtPath:path]) {
[[PMLogUtils sharedInstance] info:[NSString stringWithFormat:@"read cache from %@", path]];
[handler reply:path];
return;
}
PHAssetResourceRequestOptions *options = [PHAssetResourceRequestOptions new];
[options setNetworkAccessAllowed:YES];
__block double lastProgress = 0.0;
[self notifyProgress:progressHandler progress:0 state:PMProgressStatePrepare];
[options setProgressHandler:^(double progress) {