NCAutoUpload.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. //
  2. // NCAutoUpload.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 07/06/17.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "NCAutoUpload.h"
  24. #import "AppDelegate.h"
  25. #import "NCBridgeSwift.h"
  26. @interface NCAutoUpload ()
  27. {
  28. CCHud *_hud;
  29. }
  30. @end
  31. @implementation NCAutoUpload
  32. + (NCAutoUpload *)sharedInstance {
  33. static NCAutoUpload *sharedInstance;
  34. @synchronized(self)
  35. {
  36. if (!sharedInstance) {
  37. sharedInstance = [NCAutoUpload new];
  38. }
  39. return sharedInstance;
  40. }
  41. }
  42. #pragma --------------------------------------------------------------------------------------------
  43. #pragma mark ==== Photo Library Change Observer ====
  44. #pragma --------------------------------------------------------------------------------------------
  45. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  46. {
  47. /*
  48. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  49. if (collectionChanges) {
  50. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  51. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  52. [self uploadNewAssets];
  53. });
  54. }
  55. */
  56. }
  57. #pragma --------------------------------------------------------------------------------------------
  58. #pragma mark === initStateAutoUpload ===
  59. #pragma --------------------------------------------------------------------------------------------
  60. - (void)initStateAutoUpload
  61. {
  62. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  63. if (tableAccount.autoUpload) {
  64. [self setupAutoUpload];
  65. if (tableAccount.autoUploadBackground) {
  66. [self checkIfLocationIsEnabled];
  67. }
  68. } else {
  69. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  70. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  71. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  72. }
  73. }
  74. #pragma --------------------------------------------------------------------------------------------
  75. #pragma mark === Camera Upload & Full ===
  76. #pragma --------------------------------------------------------------------------------------------
  77. - (void)setupAutoUpload
  78. {
  79. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  80. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  81. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  82. [self performSelectorOnMainThread:@selector(uploadNewAssets) withObject:nil waitUntilDone:NO];
  83. } else {
  84. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  85. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  86. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  87. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  88. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  89. delegate:nil
  90. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  91. otherButtonTitles:nil];
  92. [alert show];
  93. }
  94. }
  95. - (void)setupAutoUploadFull
  96. {
  97. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  98. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  99. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  100. [self performSelectorOnMainThread:@selector(uploadFullAssets) withObject:nil waitUntilDone:NO];
  101. } else {
  102. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  103. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  104. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  105. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  106. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  107. delegate:nil
  108. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  109. otherButtonTitles:nil];
  110. [alert show];
  111. }
  112. }
  113. #pragma --------------------------------------------------------------------------------------------
  114. #pragma mark === Location ===
  115. #pragma --------------------------------------------------------------------------------------------
  116. - (BOOL)checkIfLocationIsEnabled
  117. {
  118. [CCManageLocation sharedInstance].delegate = self;
  119. if ([CLLocationManager locationServicesEnabled]) {
  120. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  121. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  122. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  123. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  124. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  125. } else {
  126. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  127. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  128. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  129. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  130. delegate:nil
  131. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  132. otherButtonTitles:nil];
  133. [alert show];
  134. } else {
  135. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  136. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  137. delegate:nil
  138. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  139. otherButtonTitles:nil];
  140. [alert show];
  141. }
  142. }
  143. } else {
  144. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  145. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:YES];
  146. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  147. } else {
  148. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  149. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  150. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  151. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  152. delegate:nil
  153. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  154. otherButtonTitles:nil];
  155. [alert show];
  156. }
  157. }
  158. } else {
  159. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  160. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  161. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  162. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  163. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  164. delegate:nil
  165. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  166. otherButtonTitles:nil];
  167. [alert show];
  168. } else {
  169. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  170. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  171. delegate:nil
  172. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  173. otherButtonTitles:nil];
  174. [alert show];
  175. }
  176. }
  177. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  178. return tableAccount.autoUploadBackground;
  179. }
  180. - (void)statusAuthorizationLocationChanged
  181. {
  182. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  183. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  184. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  185. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  186. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  187. } failureBlock:^(NSError *error) {
  188. }];
  189. }
  190. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  191. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  192. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  193. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  194. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  195. }
  196. } else {
  197. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  198. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  199. delegate:nil
  200. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  201. otherButtonTitles:nil];
  202. [alert show];
  203. }
  204. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  205. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  206. if (tableAccount.autoUploadBackground) {
  207. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  208. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  209. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  210. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  211. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  212. delegate:nil
  213. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  214. otherButtonTitles:nil];
  215. [alert show];
  216. } else {
  217. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  218. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  219. delegate:nil
  220. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  221. otherButtonTitles:nil];
  222. [alert show];
  223. }
  224. }
  225. }
  226. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  227. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  228. }
  229. }
  230. }
  231. - (void)changedLocation
  232. {
  233. // Only in background
  234. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  235. if (tableAccount.autoUpload && tableAccount.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  236. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  237. //check location
  238. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  239. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  240. [self uploadNewAssets];
  241. }
  242. } else {
  243. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  244. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  245. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  246. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  247. }
  248. }
  249. }
  250. #pragma --------------------------------------------------------------------------------------------
  251. #pragma mark ===== Upload Assets : NEW & FULL ====
  252. #pragma --------------------------------------------------------------------------------------------
  253. - (void)uploadNewAssets
  254. {
  255. [self uploadAssetsNewAndFull:NO];
  256. }
  257. - (void)uploadFullAssets
  258. {
  259. [self uploadAssetsNewAndFull:YES];
  260. }
  261. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  262. {
  263. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  264. NSMutableArray *newItemsToUpload;
  265. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  266. // Check Asset : NEW or FULL
  267. if (assetsFull) {
  268. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  269. } else {
  270. NSDate *databaseDatePhoto = tableAccount.autoUploadDatePhoto;
  271. NSDate *databaseDateVideo = tableAccount.autoUploadDateVideo;
  272. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  273. }
  274. // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
  275. if ([newItemsToUpload count] == 0)
  276. return;
  277. // Disable idle timer
  278. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  279. if (assetsFull) {
  280. if (!_hud)
  281. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  282. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  283. }
  284. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  285. if (assetsFull)
  286. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  287. else
  288. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  289. });
  290. }
  291. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  292. {
  293. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  294. }
  295. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  296. {
  297. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  298. }
  299. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  300. {
  301. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  302. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  303. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  304. BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
  305. // Conversion from ALAsset -to-> PHAsset
  306. for (ALAsset *asset in newItemsToUpload) {
  307. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  308. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  309. PHAsset *asset = [fetchResult firstObject];
  310. [newItemsPHAssetToUpload addObject:asset];
  311. NSLog(@"Convert url %@", url);
  312. }
  313. // Create the folder for Photos & if request the subfolders
  314. if(![app createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutoUploadAll]) {
  315. // end loading
  316. [_hud hideHud];
  317. // Enable idle timer
  318. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  319. return;
  320. }
  321. for (PHAsset *asset in newItemsPHAssetToUpload) {
  322. NSString *serverUrl;
  323. NSDate *assetDate = asset.creationDate;
  324. PHAssetMediaType assetMediaType = asset.mediaType;
  325. NSString *session;
  326. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  327. // Select type of session
  328. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
  329. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
  330. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
  331. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
  332. NSDateFormatter *formatter = [NSDateFormatter new];
  333. [formatter setDateFormat:@"yyyy"];
  334. NSString *yearString = [formatter stringFromDate:assetDate];
  335. [formatter setDateFormat:@"MM"];
  336. NSString *monthString = [formatter stringFromDate:assetDate];
  337. if (useSubFolder)
  338. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  339. else
  340. serverUrl = autoUploadPath;
  341. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  342. metadataNet.action = actionUploadAsset;
  343. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  344. if (assetsFull) {
  345. metadataNet.selector = selectorUploadAutoUploadAll;
  346. metadataNet.selectorPost = selectorUploadRemovePhoto;
  347. metadataNet.priority = NSOperationQueuePriorityLow;
  348. } else {
  349. metadataNet.selector = selectorUploadAutoUpload;
  350. metadataNet.selectorPost = nil;
  351. metadataNet.priority = NSOperationQueuePriorityNormal;
  352. }
  353. metadataNet.fileName = fileName;
  354. metadataNet.serverUrl = serverUrl;
  355. metadataNet.session = session;
  356. metadataNet.taskStatus = k_taskStatusResume;
  357. if (assetsFull)
  358. [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  359. else
  360. [self writeAssetToSandbox:metadataNet];
  361. }
  362. // end loading
  363. [_hud hideHud];
  364. // Enable idle timer
  365. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  366. }
  367. - (void)writeAssetToSandbox:(CCMetadataNet *)metadataNet
  368. {
  369. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  370. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  371. PHAsset *asset = result[0];
  372. PHAssetMediaType assetMediaType = asset.mediaType;
  373. NSDate *assetDate = asset.creationDate;
  374. __block NSError *error = nil;
  375. // VIDEO
  376. if (assetMediaType == PHAssetMediaTypeVideo) {
  377. @autoreleasepool {
  378. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  379. options.networkAccessAllowed = true;
  380. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  381. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]])
  382. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] error:nil];
  383. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  384. if (exportSession) {
  385. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]];
  386. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  387. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  388. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  389. [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  390. } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
  391. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  392. } else {
  393. NSLog(@"Export Session Status: %ld", (long)exportSession.status);
  394. }
  395. }];
  396. } else {
  397. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  398. }
  399. }];
  400. }
  401. }
  402. // IMAGE
  403. if (assetMediaType == PHAssetMediaTypeImage) {
  404. @autoreleasepool {
  405. PHImageRequestOptions *options = [PHImageRequestOptions new];
  406. options.synchronous = NO;
  407. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  408. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  409. if (error) {
  410. NSString *note = [NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description];
  411. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:note type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  412. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  413. } else {
  414. [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  415. }
  416. }];
  417. }
  418. }
  419. }
  420. - (void)addDatabaseAutoUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
  421. {
  422. if ([[NCManageDatabase sharedInstance] addAutoUploadWithMetadataNet:metadataNet]) {
  423. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload, Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  424. } else {
  425. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload [File already present in Table autoUpload], Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  426. }
  427. dispatch_async(dispatch_get_main_queue(), ^{
  428. // Update Camera Auto Upload data
  429. if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload])
  430. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:assetDate];
  431. // Update icon badge number
  432. [app updateApplicationIconBadgeNumber];
  433. });
  434. }
  435. @end