NCAutoUpload.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. //
  2. // NCAutoUpload.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 07/06/17.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  27. @interface NCAutoUpload ()
  28. {
  29. AppDelegate *appDelegate;
  30. CCHud *_hud;
  31. }
  32. @end
  33. @implementation NCAutoUpload
  34. + (NCAutoUpload *)sharedInstance {
  35. static NCAutoUpload *sharedInstance;
  36. @synchronized(self)
  37. {
  38. if (!sharedInstance) {
  39. sharedInstance = [NCAutoUpload new];
  40. sharedInstance->appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  41. }
  42. return sharedInstance;
  43. }
  44. }
  45. #pragma --------------------------------------------------------------------------------------------
  46. #pragma mark === initStateAutoUpload ===
  47. #pragma --------------------------------------------------------------------------------------------
  48. - (void)initStateAutoUpload
  49. {
  50. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  51. if (account.autoUpload) {
  52. [self setupAutoUpload];
  53. if (account.autoUploadBackground) {
  54. [self checkIfLocationIsEnabled];
  55. }
  56. } else {
  57. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  58. }
  59. }
  60. #pragma --------------------------------------------------------------------------------------------
  61. #pragma mark === Camera Upload & Full ===
  62. #pragma --------------------------------------------------------------------------------------------
  63. - (void)setupAutoUpload
  64. {
  65. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  66. [self performSelectorOnMainThread:@selector(uploadNewAssets) withObject:nil waitUntilDone:NO];
  67. } else {
  68. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  69. if (account.autoUpload == YES)
  70. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  71. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  72. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  73. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  74. [alertController addAction:okAction];
  75. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  76. return;
  77. }
  78. }
  79. - (void)setupAutoUploadFull
  80. {
  81. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  82. [self performSelectorOnMainThread:@selector(uploadFullAssets) withObject:nil waitUntilDone:NO];
  83. } else {
  84. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  85. if (account.autoUpload == YES)
  86. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  87. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  88. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  89. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  90. [alertController addAction:okAction];
  91. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  92. }
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark === Location ===
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (BOOL)checkIfLocationIsEnabled
  98. {
  99. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  100. [CCManageLocation sharedInstance].delegate = self;
  101. if ([CLLocationManager locationServicesEnabled]) {
  102. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  103. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  104. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  105. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  106. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  107. } else {
  108. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  109. if (account.autoUploadBackground == YES)
  110. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  111. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  112. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  113. [alertController addAction:okAction];
  114. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  115. } else {
  116. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  117. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  118. [alertController addAction:okAction];
  119. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  120. }
  121. }
  122. } else {
  123. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  124. if (account.autoUploadBackground == NO)
  125. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:YES];
  126. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  127. } else {
  128. if (account.autoUploadBackground == YES)
  129. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  130. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  131. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  132. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  133. [alertController addAction:okAction];
  134. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  135. }
  136. }
  137. } else {
  138. if (account.autoUploadBackground == YES)
  139. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  140. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  141. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  142. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  143. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  144. [alertController addAction:okAction];
  145. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  146. } else {
  147. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  148. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  149. [alertController addAction:okAction];
  150. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  151. }
  152. }
  153. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  154. return tableAccount.autoUploadBackground;
  155. }
  156. - (void)statusAuthorizationLocationChanged
  157. {
  158. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  159. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  160. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  161. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  162. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  163. if (account.autoUploadBackground == YES)
  164. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  165. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  166. }
  167. } else {
  168. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  169. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  170. [alertController addAction:okAction];
  171. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  172. }
  173. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  174. if (account.autoUploadBackground == YES) {
  175. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  176. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  177. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  178. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  179. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  180. [alertController addAction:okAction];
  181. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  182. } else {
  183. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  184. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  185. [alertController addAction:okAction];
  186. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  187. }
  188. }
  189. }
  190. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  191. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  192. }
  193. }
  194. }
  195. - (void)changedLocation
  196. {
  197. // Only in background
  198. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  199. if (account.autoUpload && account.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  200. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  201. //check location
  202. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  203. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  204. [self uploadNewAssets];
  205. }
  206. } else {
  207. if (account.autoUpload == YES)
  208. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  209. if (account.autoUploadBackground == YES)
  210. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  211. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  212. }
  213. }
  214. }
  215. #pragma --------------------------------------------------------------------------------------------
  216. #pragma mark ===== Upload Assets : NEW & FULL ====
  217. #pragma --------------------------------------------------------------------------------------------
  218. - (void)uploadNewAssets
  219. {
  220. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  221. [self uploadAssetsNewAndFull:selectorUploadAutoUpload];
  222. });
  223. }
  224. - (void)uploadFullAssets
  225. {
  226. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  227. [self uploadAssetsNewAndFull:selectorUploadAutoUploadAll];
  228. });
  229. }
  230. - (void)uploadAssetsNewAndFull:(NSString *)selector
  231. {
  232. if (!appDelegate.activeAccount || appDelegate.maintenanceMode)
  233. return;
  234. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  235. NSMutableArray *metadataFull = [NSMutableArray new];
  236. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  237. NSString *serverUrl;
  238. // Check Asset : NEW or FULL
  239. PHFetchResult *newAssetToUpload = [self getCameraRollAssets:tableAccount selector:selector alignPhotoLibrary:NO];
  240. // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
  241. if (newAssetToUpload == nil || [newAssetToUpload count] == 0) {
  242. NSLog(@"[LOG] Auto upload, no new asset found");
  243. return;
  244. } else {
  245. NSLog(@"[LOG] Auto upload, new %lu asset found", (unsigned long)[newAssetToUpload count]);
  246. }
  247. dispatch_async(dispatch_get_main_queue(), ^{
  248. if ([selector isEqualToString:selectorUploadAutoUploadAll]) {
  249. if (!_hud)
  250. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  251. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  252. }
  253. });
  254. // Create the folder for auto upload & if request the subfolders
  255. [[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:tableAccount.autoUploadCreateSubfolder assets:newAssetToUpload selector:selector];
  256. for (PHAsset *asset in newAssetToUpload) {
  257. NSDate *assetDate = asset.creationDate;
  258. PHAssetMediaType assetMediaType = asset.mediaType;
  259. NSString *session;
  260. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameAutoUploadMask keyFileNameType:k_keyFileNameAutoUploadType keyFileNameOriginal:k_keyFileNameOriginalAutoUpload];
  261. // Select type of session
  262. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  263. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  264. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan;
  265. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = NCCommunicationCommon.shared.sessionIdentifierBackgroundWWan;
  266. NSDateFormatter *formatter = [NSDateFormatter new];
  267. [formatter setDateFormat:@"yyyy"];
  268. NSString *yearString = [formatter stringFromDate:assetDate];
  269. [formatter setDateFormat:@"MM"];
  270. NSString *monthString = [formatter stringFromDate:assetDate];
  271. if (tableAccount.autoUploadCreateSubfolder)
  272. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  273. else
  274. serverUrl = autoUploadPath;
  275. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileName]];
  276. if (!metadata) {
  277. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  278. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  279. metadataForUpload.session = session;
  280. metadataForUpload.sessionSelector = selector;
  281. metadataForUpload.size = [[NCUtilityFileSystem shared] getFileSizeWithAsset:asset];
  282. metadataForUpload.status = k_metadataStatusWaitUpload;
  283. if (assetMediaType == PHAssetMediaTypeVideo) {
  284. metadataForUpload.typeFile = k_metadataTypeFile_video;
  285. } else if (assetMediaType == PHAssetMediaTypeImage) {
  286. metadataForUpload.typeFile = k_metadataTypeFile_image;
  287. }
  288. // Add Medtadata MOV LIVE PHOTO for upload
  289. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto) {
  290. NSString *fileNameMove = [NSString stringWithFormat:@"%@.mov", fileName.stringByDeletingPathExtension];
  291. NSString *ocId = [[NSUUID UUID] UUIDString];
  292. NSString *filePath = [CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameMove];
  293. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  294. [self extractLivePhotoAsset:asset filePath:filePath withCompletion:^(NSURL *url) {
  295. if (url != nil) {
  296. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  297. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileNameMove ocId:ocId serverUrl:serverUrl url:@"" contentType:@""];
  298. metadataMOVForUpload.session = session;
  299. metadataMOVForUpload.sessionSelector = selector;
  300. metadataMOVForUpload.size = fileSize;
  301. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  302. metadataMOVForUpload.typeFile = k_metadataTypeFile_video;
  303. [metadataFull addObject:metadataMOVForUpload];
  304. // Update database Auto Upload
  305. if ([selector isEqualToString:selectorUploadAutoUpload])
  306. [[NCManageDatabase sharedInstance] addMetadata:metadataMOVForUpload];
  307. }
  308. dispatch_semaphore_signal(semaphore);
  309. }];
  310. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER))
  311. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:30]];
  312. }
  313. [metadataFull addObject:metadataForUpload];
  314. // Update database Auto Upload
  315. if ([selector isEqualToString:selectorUploadAutoUpload]) {
  316. dispatch_async(dispatch_get_main_queue(), ^{
  317. [self addQueueUploadAndPhotoLibrary:metadataForUpload asset:asset];
  318. });
  319. }
  320. }
  321. }
  322. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  323. // Insert all assets (Full) in tableQueueUpload
  324. if ([selector isEqualToString:selectorUploadAutoUploadAll] && [metadataFull count] > 0) {
  325. [[NCManageDatabase sharedInstance] addMetadatas:metadataFull];
  326. }
  327. // end loadingcand reload
  328. [_hud hideHud];
  329. });
  330. }
  331. - (void)addQueueUploadAndPhotoLibrary:(tableMetadata *)metadata asset:(PHAsset *)asset
  332. {
  333. @synchronized(self) {
  334. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  335. // Add asset in table Photo Library
  336. if ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload]) {
  337. (void)[[NCManageDatabase sharedInstance] addPhotoLibrary:@[asset] account:appDelegate.activeAccount];
  338. }
  339. }
  340. }
  341. #pragma --------------------------------------------------------------------------------------------
  342. #pragma mark ===== Create Folder SubFolder Auto Upload Folder Photos/Videos ====
  343. #pragma --------------------------------------------------------------------------------------------
  344. - (void)createAutoUploadFolderWithSubFolder:(BOOL)useSubFolder assets:(PHFetchResult *)assets selector:(NSString *)selector
  345. {
  346. NSString *serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  347. NSString *filename = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  348. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  349. [[NCOperationQueue shared] createFolderWithFilename:filename serverUrl:serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl overwrite:true];
  350. if (useSubFolder) {
  351. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  352. NSString *filename = dateSubFolder.lastPathComponent;
  353. NSString *serverUrl = [NSString stringWithFormat:@"%@/%@", autoUploadPath, dateSubFolder].stringByDeletingLastPathComponent;
  354. [[NCOperationQueue shared] createFolderWithFilename:filename serverUrl:serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl overwrite:true];
  355. }
  356. }
  357. }
  358. #pragma --------------------------------------------------------------------------------------------
  359. #pragma mark ===== get Camera Roll new Asset ====
  360. #pragma --------------------------------------------------------------------------------------------
  361. - (PHFetchResult *)getCameraRollAssets:(tableAccount *)account selector:(NSString *)selector alignPhotoLibrary:(BOOL)alignPhotoLibrary
  362. {
  363. @synchronized(self) {
  364. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  365. PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
  366. if (result.count == 0) {
  367. return nil;
  368. }
  369. NSPredicate *predicateImage = [NSPredicate predicateWithFormat:@"mediaType == %i", PHAssetMediaTypeImage];
  370. NSPredicate *predicateVideo = [NSPredicate predicateWithFormat:@"mediaType == %i", PHAssetMediaTypeVideo];
  371. NSPredicate *predicate;
  372. NSMutableArray *newAssets =[NSMutableArray new];
  373. if (alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo)) {
  374. predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateImage, predicateVideo]];
  375. } else if (account.autoUploadImage) {
  376. predicate = predicateImage;
  377. } else if (account.autoUploadVideo) {
  378. predicate = predicateVideo;
  379. } else {
  380. return nil;
  381. }
  382. PHFetchOptions *fetchOptions = [PHFetchOptions new];
  383. fetchOptions.predicate = predicate;
  384. PHAssetCollection *collection = result[0];
  385. PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];
  386. if ([selector isEqualToString:selectorUploadAutoUpload]) {
  387. NSString *creationDate;
  388. NSString *idAsset;
  389. NSArray *idsAsset = [[NCManageDatabase sharedInstance] getPhotoLibraryIdAssetWithImage:account.autoUploadImage video:account.autoUploadVideo account:account.account];
  390. for (PHAsset *asset in assets) {
  391. (asset.creationDate != nil) ? (creationDate = [NSString stringWithFormat:@"%@", asset.creationDate]) : (creationDate = @"");
  392. idAsset = [NSString stringWithFormat:@"%@%@%@", account.account, asset.localIdentifier, creationDate];
  393. if (![idsAsset containsObject: idAsset])
  394. [newAssets addObject:asset];
  395. }
  396. return (PHFetchResult *)newAssets;
  397. } else {
  398. return assets;
  399. }
  400. }
  401. }
  402. return nil;
  403. }
  404. - (void)extractLivePhotoAsset:(PHAsset*)asset filePath:(NSString *)filePath withCompletion:(void (^)(NSURL* url))completion {
  405. [CCUtility removeFileAtPath:filePath];
  406. NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
  407. PHLivePhotoRequestOptions *options = [PHLivePhotoRequestOptions new];
  408. options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
  409. options.networkAccessAllowed = YES;
  410. [[PHImageManager defaultManager] requestLivePhotoForAsset:asset targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeDefault options:options resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nullable info) {
  411. if (livePhoto) {
  412. NSArray *assetResources = [PHAssetResource assetResourcesForLivePhoto:livePhoto];
  413. PHAssetResource *videoResource = nil;
  414. for(PHAssetResource *resource in assetResources){
  415. if (resource.type == PHAssetResourceTypePairedVideo) {
  416. videoResource = resource;
  417. break;
  418. }
  419. }
  420. if(videoResource){
  421. [[PHAssetResourceManager defaultManager] writeDataForAssetResource:videoResource toFile:fileUrl options:nil completionHandler:^(NSError * _Nullable error) {
  422. if (!error) {
  423. completion(fileUrl);
  424. } else { completion(nil); }
  425. }];
  426. } else { completion(nil); }
  427. } else { completion(nil); }
  428. }];
  429. }
  430. #pragma --------------------------------------------------------------------------------------------
  431. #pragma mark ===== Align Photo Library ====
  432. #pragma --------------------------------------------------------------------------------------------
  433. - (void)alignPhotoLibrary
  434. {
  435. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  436. PHFetchResult *assets = [self getCameraRollAssets:account selector:selectorUploadAutoUploadAll alignPhotoLibrary:YES];
  437. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:appDelegate.activeAccount];
  438. if (assets != nil) {
  439. (void)[[NCManageDatabase sharedInstance] addPhotoLibrary:(NSArray *)assets account:account.account];
  440. NSLog(@"[LOG] Align Photo Library %lu", (unsigned long)[assets count]);
  441. }
  442. }
  443. @end