NCAutoUpload.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. //
  2. // NCAutoUpload.m
  3. // Nextcloud iOS
  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. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  27. @interface NCAutoUpload ()
  28. {
  29. CCHud *_hud;
  30. }
  31. @end
  32. @implementation NCAutoUpload
  33. + (NCAutoUpload *)sharedInstance {
  34. static NCAutoUpload *sharedInstance;
  35. @synchronized(self)
  36. {
  37. if (!sharedInstance) {
  38. sharedInstance = [NCAutoUpload new];
  39. }
  40. return sharedInstance;
  41. }
  42. }
  43. #pragma --------------------------------------------------------------------------------------------
  44. #pragma mark === initStateAutoUpload ===
  45. #pragma --------------------------------------------------------------------------------------------
  46. - (void)initStateAutoUpload
  47. {
  48. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  49. if (account.autoUpload) {
  50. [self setupAutoUpload];
  51. if (account.autoUploadBackground) {
  52. [self checkIfLocationIsEnabled];
  53. }
  54. } else {
  55. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  56. }
  57. }
  58. #pragma --------------------------------------------------------------------------------------------
  59. #pragma mark === Camera Upload & Full ===
  60. #pragma --------------------------------------------------------------------------------------------
  61. - (void)setupAutoUpload
  62. {
  63. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  64. [self performSelectorOnMainThread:@selector(uploadNewAssets) withObject:nil waitUntilDone:NO];
  65. } else {
  66. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  67. if (account.autoUpload == YES)
  68. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  69. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  70. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  71. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  72. [alertController addAction:okAction];
  73. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  74. return;
  75. }
  76. }
  77. - (void)setupAutoUploadFull
  78. {
  79. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  80. [self performSelectorOnMainThread:@selector(uploadFullAssets) withObject:nil waitUntilDone:NO];
  81. } else {
  82. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  83. if (account.autoUpload == YES)
  84. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  85. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  86. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  87. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  88. [alertController addAction:okAction];
  89. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  90. }
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark === Location ===
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (BOOL)checkIfLocationIsEnabled
  96. {
  97. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  98. [CCManageLocation sharedInstance].delegate = self;
  99. if ([CLLocationManager locationServicesEnabled]) {
  100. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  101. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  102. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  103. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  104. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  105. } else {
  106. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  107. if (account.autoUploadBackground == YES)
  108. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  109. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  110. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  111. [alertController addAction:okAction];
  112. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  113. } else {
  114. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  115. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  116. [alertController addAction:okAction];
  117. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  118. }
  119. }
  120. } else {
  121. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  122. if (account.autoUploadBackground == NO)
  123. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:YES];
  124. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  125. } else {
  126. if (account.autoUploadBackground == YES)
  127. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  128. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  129. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  130. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  131. [alertController addAction:okAction];
  132. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  133. }
  134. }
  135. } else {
  136. if (account.autoUploadBackground == YES)
  137. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  138. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  139. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  140. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  141. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  142. [alertController addAction:okAction];
  143. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  144. } else {
  145. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  146. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  147. [alertController addAction:okAction];
  148. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  149. }
  150. }
  151. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  152. return tableAccount.autoUploadBackground;
  153. }
  154. - (void)statusAuthorizationLocationChanged
  155. {
  156. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  157. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  158. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  159. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  160. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  161. if (account.autoUploadBackground == YES)
  162. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  163. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  164. }
  165. } else {
  166. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  167. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  168. [alertController addAction:okAction];
  169. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  170. }
  171. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  172. if (account.autoUploadBackground == YES) {
  173. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  174. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  175. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  176. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  177. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  178. [alertController addAction:okAction];
  179. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  180. } else {
  181. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  182. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  183. [alertController addAction:okAction];
  184. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  185. }
  186. }
  187. }
  188. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  189. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  190. }
  191. }
  192. }
  193. - (void)changedLocation
  194. {
  195. // Only in background
  196. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  197. if (account.autoUpload && account.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  198. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  199. //check location
  200. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  201. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  202. [self uploadNewAssets];
  203. }
  204. } else {
  205. if (account.autoUpload == YES)
  206. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  207. if (account.autoUploadBackground == YES)
  208. [[NCManageDatabase sharedInstance] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  209. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  210. }
  211. }
  212. }
  213. #pragma --------------------------------------------------------------------------------------------
  214. #pragma mark ===== Upload Assets : NEW & FULL ====
  215. #pragma --------------------------------------------------------------------------------------------
  216. - (void)uploadNewAssets
  217. {
  218. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  219. [self uploadAssetsNewAndFull:NO];
  220. });
  221. }
  222. - (void)uploadFullAssets
  223. {
  224. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  225. [self uploadAssetsNewAndFull:YES];
  226. });
  227. }
  228. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  229. {
  230. if (!app.activeAccount || app.maintenanceMode)
  231. return;
  232. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  233. // Check Asset : NEW or FULL
  234. PHFetchResult *newAssetToUpload = [self getCameraRollAssets:account assetsFull:assetsFull alignPhotoLibrary:NO];
  235. // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
  236. if ([newAssetToUpload count] == 0) {
  237. NSLog(@"[LOG] Auto upload, no new asset found");
  238. return;
  239. } else {
  240. NSLog(@"[LOG] Auto upload, new %lu asset found", (unsigned long)[newAssetToUpload count]);
  241. }
  242. dispatch_async(dispatch_get_main_queue(), ^{
  243. if (assetsFull) {
  244. if (!_hud)
  245. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  246. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  247. }
  248. });
  249. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  250. if (assetsFull)
  251. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newAssetToUpload waitUntilDone:NO];
  252. else
  253. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newAssetToUpload waitUntilDone:NO];
  254. });
  255. }
  256. - (void)uploadNewAssetsToNetwork:(PHFetchResult *)newAssetToUpload
  257. {
  258. [self uploadAssetsToNetwork:newAssetToUpload assetsFull:NO];
  259. }
  260. - (void)uploadFullAssetsToNetwork:(PHFetchResult *)newAssetToUpload
  261. {
  262. [self uploadAssetsToNetwork:newAssetToUpload assetsFull:YES];
  263. }
  264. - (void)uploadAssetsToNetwork:(PHFetchResult *)newAssetToUpload assetsFull:(BOOL)assetsFull
  265. {
  266. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  267. NSMutableArray *metadataNetFull = [NSMutableArray new];
  268. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  269. BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
  270. // Create the folder for Photos & if request the subfolders
  271. if(![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newAssetToUpload selector:selectorUploadAutoUploadAll]) {
  272. // end loading
  273. [_hud hideHud];
  274. return;
  275. }
  276. for (PHAsset *asset in newAssetToUpload) {
  277. NSString *serverUrl;
  278. NSDate *assetDate = asset.creationDate;
  279. PHAssetMediaType assetMediaType = asset.mediaType;
  280. NSString *session;
  281. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameAutoUploadMask keyFileNameType:k_keyFileNameAutoUploadType];
  282. // Select type of session
  283. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
  284. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
  285. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
  286. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
  287. NSDateFormatter *formatter = [NSDateFormatter new];
  288. [formatter setDateFormat:@"yyyy"];
  289. NSString *yearString = [formatter stringFromDate:assetDate];
  290. [formatter setDateFormat:@"MM"];
  291. NSString *monthString = [formatter stringFromDate:assetDate];
  292. if (useSubFolder)
  293. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  294. else
  295. serverUrl = autoUploadPath;
  296. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  297. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  298. if (assetsFull) {
  299. metadataNet.selector = selectorUploadAutoUploadAll;
  300. // Option
  301. if ([[NCBrandOptions sharedInstance] use_storeLocalAutoUploadAll] == true)
  302. metadataNet.selectorPost = nil;
  303. else
  304. metadataNet.selectorPost = selectorUploadRemovePhoto;
  305. } else {
  306. metadataNet.selector = selectorUploadAutoUpload;
  307. metadataNet.selectorPost = nil;
  308. }
  309. if (assetMediaType == PHAssetMediaTypeImage)
  310. metadataNet.priority = k_priorityAutoUploadImage;
  311. else
  312. metadataNet.priority = k_priorityAutoUploadVideo;
  313. metadataNet.fileName = fileName;
  314. metadataNet.serverUrl = serverUrl;
  315. metadataNet.session = session;
  316. metadataNet.taskStatus = k_taskStatusResume;
  317. [metadataNetFull addObject:metadataNet];
  318. // Update database
  319. if (!assetsFull)
  320. [self addQueueUploadAndPhotoLibrary:metadataNet asset:asset];
  321. }
  322. // Insert all assets (Full) in tableQueueUpload
  323. if (assetsFull && [metadataNetFull count] > 0) {
  324. [[NCManageDatabase sharedInstance] addQueueUploadWithMetadatasNet:metadataNetFull];
  325. // Update icon badge number
  326. [app updateApplicationIconBadgeNumber];
  327. }
  328. // end loading
  329. [_hud hideHud];
  330. }
  331. - (void)addQueueUploadAndPhotoLibrary:(CCMetadataNet *)metadataNet asset:(PHAsset *)asset
  332. {
  333. @synchronized(self) {
  334. if ([[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet]) {
  335. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:@"Add Auto Upload, add new asset" type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  336. } else {
  337. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:@"Add Auto Upload, asset already present or db in write transaction" type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  338. }
  339. // Add asset in table Photo Library
  340. if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload]) {
  341. if (![[NCManageDatabase sharedInstance] addPhotoLibrary:@[asset]]) {
  342. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:@"Add Photo Library, db in write transaction" type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  343. }
  344. }
  345. dispatch_async(dispatch_get_main_queue(), ^{
  346. // Update icon badge number
  347. [app updateApplicationIconBadgeNumber];
  348. });
  349. }
  350. }
  351. #pragma --------------------------------------------------------------------------------------------
  352. #pragma mark ===== Create Folder SubFolder Auto Upload Folder Photos ====
  353. #pragma --------------------------------------------------------------------------------------------
  354. - (BOOL)createFolderSubFolderAutoUploadFolderPhotos:(NSString *)folderPhotos useSubFolder:(BOOL)useSubFolder assets:(PHFetchResult *)assets selector:(NSString *)selector
  355. {
  356. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  357. if ([ocNetworking automaticCreateFolderSync:folderPhotos]) {
  358. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:folderPhotos permissions:nil];
  359. } else {
  360. // Activity
  361. [[NCManageDatabase sharedInstance] addActivityClient:folderPhotos fileID:@"" action:k_activityDebugActionAutoUpload selector:selector note:NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  362. if ([selector isEqualToString:selectorUploadAutoUploadAll])
  363. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  364. return false;
  365. }
  366. // Create if request the subfolders
  367. if (useSubFolder) {
  368. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  369. if ([ocNetworking automaticCreateFolderSync:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  370. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder] permissions:nil];
  371. } else {
  372. // Activity
  373. [[NCManageDatabase sharedInstance] addActivityClient:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder] fileID:@"" action:k_activityDebugActionAutoUpload selector:selector note:NSLocalizedString(@"_error_createsubfolders_upload_",nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  374. if ([selector isEqualToString:selectorUploadAutoUploadAll])
  375. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  376. return false;
  377. }
  378. }
  379. }
  380. return true;
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ===== get Camera Roll new Asset ====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (PHFetchResult *)getCameraRollAssets:(tableAccount *)account assetsFull:(BOOL)assetsFull alignPhotoLibrary:(BOOL)alignPhotoLibrary
  386. {
  387. @synchronized(self) {
  388. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  389. PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
  390. NSPredicate *predicateImage = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
  391. NSPredicate *predicateVideo = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeVideo];
  392. NSPredicate *predicate;
  393. NSMutableArray *newAssets =[NSMutableArray new];
  394. if (alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo)) {
  395. predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateImage, predicateVideo]];
  396. } else if (account.autoUploadImage) {
  397. predicate = predicateImage;
  398. } else if (account.autoUploadVideo) {
  399. predicate = predicateVideo;
  400. } else {
  401. return nil;
  402. }
  403. PHFetchOptions *fetchOptions = [PHFetchOptions new];
  404. fetchOptions.predicate = predicate;
  405. PHAssetCollection *collection = result[0];
  406. PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];
  407. if (assetsFull == NO) {
  408. NSString *creationDate;
  409. NSString *idAsset;
  410. NSArray *idsAsset = [[NCManageDatabase sharedInstance] getPhotoLibraryIdAssetWithImage:account.autoUploadImage video:account.autoUploadVideo];
  411. for (PHAsset *asset in assets) {
  412. (asset.creationDate != nil) ? (creationDate = [NSString stringWithFormat:@"%@", asset.creationDate]) : (creationDate = @"");
  413. idAsset = [NSString stringWithFormat:@"%@%@%@", account.account, asset.localIdentifier, creationDate];
  414. if (![idsAsset containsObject: idAsset])
  415. [newAssets addObject:asset];
  416. }
  417. return (PHFetchResult *)newAssets;
  418. } else {
  419. return assets;
  420. }
  421. }
  422. }
  423. return nil;
  424. }
  425. #pragma --------------------------------------------------------------------------------------------
  426. #pragma mark ===== Align Photo Library ====
  427. #pragma --------------------------------------------------------------------------------------------
  428. - (void)alignPhotoLibrary
  429. {
  430. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  431. PHFetchResult *assets = [self getCameraRollAssets:account assetsFull:YES alignPhotoLibrary:YES];
  432. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:app.activeAccount];
  433. (void)[[NCManageDatabase sharedInstance] addPhotoLibrary:(NSArray *)assets];
  434. NSLog(@"[LOG] Align Photo Library %lu", (unsigned long)[assets count]);
  435. }
  436. @end