2
0

MWPhoto.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //
  2. // MWPhoto.m
  3. // MWPhotoBrowser
  4. //
  5. // Created by Michael Waterfall on 17/10/2010.
  6. // Copyright 2010 d3i. All rights reserved.
  7. //
  8. //#import <SDWebImage/SDWebImageDecoder.h>
  9. #import <SDWebImage/SDWebImageManager.h>
  10. #import <SDWebImage/SDWebImageOperation.h>
  11. #import <AssetsLibrary/AssetsLibrary.h>
  12. #import "MWPhoto.h"
  13. #import "MWPhotoBrowser.h"
  14. #import <WFChatClient/WFCChatClient.h>
  15. #import "WFCUConfigManager.h"
  16. @interface MWPhoto () {
  17. BOOL _loadingInProgress;
  18. id <SDWebImageOperation> _webImageOperation;
  19. PHImageRequestID _assetRequestID;
  20. PHImageRequestID _assetVideoRequestID;
  21. }
  22. @property (nonatomic, strong) UIImage *image;
  23. @property (nonatomic, strong) NSURL *photoURL;
  24. @property (nonatomic, strong) PHAsset *asset;
  25. @property (nonatomic) CGSize assetTargetSize;
  26. - (void)imageLoadingComplete;
  27. @end
  28. @implementation MWPhoto
  29. @synthesize underlyingImage = _underlyingImage; // synth property from protocol
  30. #pragma mark - Class Methods
  31. + (MWPhoto *)photoWithImage:(UIImage *)image {
  32. return [[MWPhoto alloc] initWithImage:image];
  33. }
  34. + (MWPhoto *)photoWithURL:(NSURL *)url {
  35. return [[MWPhoto alloc] initWithURL:url];
  36. }
  37. + (MWPhoto *)photoWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
  38. return [[MWPhoto alloc] initWithAsset:asset targetSize:targetSize];
  39. }
  40. + (MWPhoto *)videoWithURL:(NSURL *)url {
  41. return [[MWPhoto alloc] initWithVideoURL:url];
  42. }
  43. #pragma mark - Init
  44. - (id)init {
  45. if ((self = [super init])) {
  46. self.emptyImage = YES;
  47. [self setup];
  48. }
  49. return self;
  50. }
  51. - (id)initWithImage:(UIImage *)image {
  52. if ((self = [super init])) {
  53. self.image = image;
  54. [self setup];
  55. }
  56. return self;
  57. }
  58. - (id)initWithURL:(NSURL *)url {
  59. if ((self = [super init])) {
  60. self.photoURL = url;
  61. [self setup];
  62. }
  63. return self;
  64. }
  65. - (id)initWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
  66. if ((self = [super init])) {
  67. self.asset = asset;
  68. self.assetTargetSize = targetSize;
  69. self.isVideo = asset.mediaType == PHAssetMediaTypeVideo;
  70. [self setup];
  71. }
  72. return self;
  73. }
  74. - (id)initWithVideoURL:(NSURL *)url {
  75. if ((self = [super init])) {
  76. self.videoURL = url;
  77. self.isVideo = YES;
  78. self.emptyImage = YES;
  79. [self setup];
  80. }
  81. return self;
  82. }
  83. - (void)setup {
  84. _assetRequestID = PHInvalidImageRequestID;
  85. _assetVideoRequestID = PHInvalidImageRequestID;
  86. }
  87. - (void)dealloc {
  88. [self cancelAnyLoading];
  89. }
  90. #pragma mark - Video
  91. - (void)setVideoURL:(NSURL *)videoURL {
  92. _videoURL = videoURL;
  93. self.isVideo = YES;
  94. }
  95. - (void)getVideoURL:(void (^)(NSURL *url))completion {
  96. if (_videoURL) {
  97. completion(_videoURL);
  98. } else if (_asset && _asset.mediaType == PHAssetMediaTypeVideo) {
  99. [self cancelVideoRequest]; // Cancel any existing
  100. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  101. options.networkAccessAllowed = YES;
  102. typeof(self) __weak weakSelf = self;
  103. _assetVideoRequestID = [[PHImageManager defaultManager] requestAVAssetForVideo:_asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  104. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ // Testing
  105. typeof(self) strongSelf = weakSelf;
  106. if (!strongSelf) return;
  107. strongSelf->_assetVideoRequestID = PHInvalidImageRequestID;
  108. if ([asset isKindOfClass:[AVURLAsset class]]) {
  109. completion(((AVURLAsset *)asset).URL);
  110. } else {
  111. completion(nil);
  112. }
  113. }];
  114. }
  115. }
  116. #pragma mark - MWPhoto Protocol Methods
  117. - (UIImage *)underlyingImage {
  118. return _underlyingImage;
  119. }
  120. - (void)loadUnderlyingImageAndNotify {
  121. NSAssert([[NSThread currentThread] isMainThread], @"This method must be called on the main thread.");
  122. if (_loadingInProgress) return;
  123. _loadingInProgress = YES;
  124. @try {
  125. if (self.underlyingImage) {
  126. [self imageLoadingComplete];
  127. } else {
  128. [self performLoadUnderlyingImageAndNotify];
  129. }
  130. }
  131. @catch (NSException *exception) {
  132. self.underlyingImage = nil;
  133. _loadingInProgress = NO;
  134. [self imageLoadingComplete];
  135. }
  136. @finally {
  137. }
  138. }
  139. // Set the underlyingImage
  140. - (void)performLoadUnderlyingImageAndNotify {
  141. // Get underlying image
  142. if (_image) {
  143. // We have UIImage!
  144. self.underlyingImage = _image;
  145. [self imageLoadingComplete];
  146. } else if (_photoURL) {
  147. // Check what type of url it is
  148. if ([[[_photoURL scheme] lowercaseString] isEqualToString:@"assets-library"]) {
  149. // Load from assets library
  150. [self _performLoadUnderlyingImageAndNotifyWithAssetsLibraryURL: _photoURL];
  151. } else if ([_photoURL isFileReferenceURL]) {
  152. // Load from local file async
  153. [self _performLoadUnderlyingImageAndNotifyWithLocalFileURL: _photoURL];
  154. } else {
  155. // Load async from web (using SDWebImage)
  156. [self _performLoadUnderlyingImageAndNotifyWithWebURL: _photoURL];
  157. }
  158. } else if (_asset) {
  159. // Load from photos asset
  160. [self _performLoadUnderlyingImageAndNotifyWithAsset: _asset targetSize:_assetTargetSize];
  161. } else {
  162. // Image is empty
  163. [self imageLoadingComplete];
  164. }
  165. }
  166. // Load from local file
  167. - (void)_performLoadUnderlyingImageAndNotifyWithWebURL:(NSURL *)url {
  168. [[WFCCIMService sharedWFCIMService] getAuthorizedMediaUrl:self.message.messageUid mediaType:Media_Type_IMAGE mediaPath:url.absoluteString success:^(NSString *authorizedUrl, NSString *backupAuthorizedUrl) {
  169. [self _performLoadUnderlyingImageAndNotifyWithWebURLWithAuthedUrl:[NSURL URLWithString:authorizedUrl]];
  170. } error:^(int error_code) {
  171. [self _performLoadUnderlyingImageAndNotifyWithWebURLWithAuthedUrl:url];
  172. }];
  173. }
  174. - (void)_performLoadUnderlyingImageAndNotifyWithWebURLWithAuthedUrl:(NSURL *)url {
  175. @try {
  176. SDWebImageManager *manager = [SDWebImageManager sharedManager];
  177. _webImageOperation = [manager loadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
  178. if (expectedSize > 0) {
  179. float progress = receivedSize / (float)expectedSize;
  180. NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
  181. [NSNumber numberWithFloat:progress], @"progress",
  182. self, @"photo", nil];
  183. [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_PROGRESS_NOTIFICATION object:dict];
  184. }
  185. } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
  186. if (error) {
  187. MWLog(@"SDWebImage failed to download image: %@", error);
  188. }
  189. _webImageOperation = nil;
  190. self.underlyingImage = image;
  191. dispatch_async(dispatch_get_main_queue(), ^{
  192. [self imageLoadingComplete];
  193. });
  194. }];
  195. } @catch (NSException *e) {
  196. MWLog(@"Photo from web: %@", e);
  197. _webImageOperation = nil;
  198. [self imageLoadingComplete];
  199. }
  200. }
  201. // Load from local file
  202. - (void)_performLoadUnderlyingImageAndNotifyWithLocalFileURL:(NSURL *)url {
  203. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  204. @autoreleasepool {
  205. @try {
  206. self.underlyingImage = [UIImage imageWithContentsOfFile:url.path];
  207. if (!_underlyingImage) {
  208. MWLog(@"Error loading photo from path: %@", url.path);
  209. }
  210. } @finally {
  211. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  212. }
  213. }
  214. });
  215. }
  216. // Load from asset library async
  217. - (void)_performLoadUnderlyingImageAndNotifyWithAssetsLibraryURL:(NSURL *)url {
  218. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  219. @autoreleasepool {
  220. @try {
  221. ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
  222. [assetslibrary assetForURL:url
  223. resultBlock:^(ALAsset *asset){
  224. ALAssetRepresentation *rep = [asset defaultRepresentation];
  225. CGImageRef iref = [rep fullScreenImage];
  226. if (iref) {
  227. self.underlyingImage = [UIImage imageWithCGImage:iref];
  228. }
  229. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  230. }
  231. failureBlock:^(NSError *error) {
  232. self.underlyingImage = nil;
  233. MWLog(@"Photo from asset library error: %@",error);
  234. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  235. }];
  236. } @catch (NSException *e) {
  237. MWLog(@"Photo from asset library error: %@", e);
  238. [self performSelectorOnMainThread:@selector(imageLoadingComplete) withObject:nil waitUntilDone:NO];
  239. }
  240. }
  241. });
  242. }
  243. // Load from photos library
  244. - (void)_performLoadUnderlyingImageAndNotifyWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
  245. PHImageManager *imageManager = [PHImageManager defaultManager];
  246. PHImageRequestOptions *options = [PHImageRequestOptions new];
  247. options.networkAccessAllowed = YES;
  248. options.resizeMode = PHImageRequestOptionsResizeModeFast;
  249. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  250. options.synchronous = false;
  251. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  252. NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
  253. [NSNumber numberWithDouble: progress], @"progress",
  254. self, @"photo", nil];
  255. [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_PROGRESS_NOTIFICATION object:dict];
  256. };
  257. _assetRequestID = [imageManager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
  258. dispatch_async(dispatch_get_main_queue(), ^{
  259. self.underlyingImage = result;
  260. [self imageLoadingComplete];
  261. });
  262. }];
  263. }
  264. // Release if we can get it again from path or url
  265. - (void)unloadUnderlyingImage {
  266. _loadingInProgress = NO;
  267. self.underlyingImage = nil;
  268. }
  269. - (void)imageLoadingComplete {
  270. NSAssert([[NSThread currentThread] isMainThread], @"This method must be called on the main thread.");
  271. // Complete so notify
  272. _loadingInProgress = NO;
  273. // Notify on next run loop
  274. [self performSelector:@selector(postCompleteNotification) withObject:nil afterDelay:0];
  275. if(self.underlyingImage && [self.message.content isKindOfClass:[WFCCImageMessageContent class]]) {
  276. WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)self.message.content;
  277. if(!imgCnt.localPath.length) {
  278. UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
  279. NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:self.message.conversation mediaType:Media_Type_IMAGE];
  280. NSString *path = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"img%lld.jpg", recordTime]];
  281. NSData *imgData = UIImageJPEGRepresentation(self.underlyingImage, 0.85);
  282. if([imgData writeToFile:path atomically:YES]) {
  283. imgCnt.localPath = path;
  284. imgCnt.size = self.underlyingImage.size;
  285. if(!imgCnt.thumbnail || imgCnt.thumbnail == [WFCCIMService sharedWFCIMService].defaultThumbnailImage) {
  286. imgCnt.thumbnail = [WFCCUtilities generateThumbnail:self.underlyingImage withWidth:120 withHeight:120];
  287. }
  288. [[WFCCIMService sharedWFCIMService] updateMessage:self.message.messageId content:imgCnt];
  289. }
  290. }
  291. }
  292. }
  293. - (void)postCompleteNotification {
  294. [[NSNotificationCenter defaultCenter] postNotificationName:MWPHOTO_LOADING_DID_END_NOTIFICATION
  295. object:self];
  296. }
  297. - (void)cancelAnyLoading {
  298. if (_webImageOperation != nil) {
  299. [_webImageOperation cancel];
  300. _loadingInProgress = NO;
  301. }
  302. [self cancelImageRequest];
  303. [self cancelVideoRequest];
  304. }
  305. - (void)cancelImageRequest {
  306. if (_assetRequestID != PHInvalidImageRequestID) {
  307. [[PHImageManager defaultManager] cancelImageRequest:_assetRequestID];
  308. _assetRequestID = PHInvalidImageRequestID;
  309. }
  310. }
  311. - (void)cancelVideoRequest {
  312. if (_assetVideoRequestID != PHInvalidImageRequestID) {
  313. [[PHImageManager defaultManager] cancelImageRequest:_assetVideoRequestID];
  314. _assetVideoRequestID = PHInvalidImageRequestID;
  315. }
  316. }
  317. @end