NCAutoUpload.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  27. @interface NCAutoUpload ()
  28. {
  29. PHFetchResult *_assetsFetchResult;
  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. }
  41. return sharedInstance;
  42. }
  43. }
  44. #pragma --------------------------------------------------------------------------------------------
  45. #pragma mark ==== Photo Library Change Observer ====
  46. #pragma --------------------------------------------------------------------------------------------
  47. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  48. {
  49. /*
  50. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  51. if (collectionChanges) {
  52. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  53. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  54. [self uploadNewAssets];
  55. });
  56. }
  57. */
  58. }
  59. #pragma --------------------------------------------------------------------------------------------
  60. #pragma mark === initStateAutoUpload ===
  61. #pragma --------------------------------------------------------------------------------------------
  62. - (void)initStateAutoUpload
  63. {
  64. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  65. if (account.autoUpload) {
  66. [self setupAutoUpload];
  67. if (account.autoUploadBackground) {
  68. [self checkIfLocationIsEnabled];
  69. }
  70. } else {
  71. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  72. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  73. }
  74. }
  75. #pragma --------------------------------------------------------------------------------------------
  76. #pragma mark === Camera Upload & Full ===
  77. #pragma --------------------------------------------------------------------------------------------
  78. - (void)setupAutoUpload
  79. {
  80. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  81. _assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  82. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  83. [self performSelectorOnMainThread:@selector(uploadNewAssets) withObject:nil waitUntilDone:NO];
  84. } else {
  85. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  86. if (account.autoUpload == YES)
  87. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  88. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  89. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  90. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  91. [alert show];
  92. }
  93. }
  94. - (void)setupAutoUploadFull
  95. {
  96. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  97. _assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  98. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  99. [self performSelectorOnMainThread:@selector(uploadFullAssets) withObject:nil waitUntilDone:NO];
  100. } else {
  101. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  102. if (account.autoUpload == YES)
  103. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  104. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  105. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  106. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  107. [alert show];
  108. }
  109. }
  110. #pragma --------------------------------------------------------------------------------------------
  111. #pragma mark === Location ===
  112. #pragma --------------------------------------------------------------------------------------------
  113. - (BOOL)checkIfLocationIsEnabled
  114. {
  115. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  116. [CCManageLocation sharedInstance].delegate = self;
  117. if ([CLLocationManager locationServicesEnabled]) {
  118. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  119. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  120. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  121. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  122. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  123. } else {
  124. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  125. if (account.autoUploadBackground == YES)
  126. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  127. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  128. [alert show];
  129. } else {
  130. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  131. [alert show];
  132. }
  133. }
  134. } else {
  135. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  136. if (account.autoUploadBackground == NO)
  137. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:YES];
  138. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  139. } else {
  140. if (account.autoUploadBackground == YES)
  141. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  142. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  143. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  144. [alert show];
  145. }
  146. }
  147. } else {
  148. if (account.autoUploadBackground == YES)
  149. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  150. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  151. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  152. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  153. [alert show];
  154. } else {
  155. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  156. [alert show];
  157. }
  158. }
  159. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  160. return tableAccount.autoUploadBackground;
  161. }
  162. - (void)statusAuthorizationLocationChanged
  163. {
  164. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  165. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  166. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  167. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  168. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  169. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  170. } failureBlock:^(NSError *error) {
  171. }];
  172. }
  173. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  174. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  175. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  176. if (account.autoUploadBackground == YES)
  177. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  178. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  179. }
  180. } else {
  181. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  182. [alert show];
  183. }
  184. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  185. if (account.autoUploadBackground == YES) {
  186. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  187. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  188. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  189. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  190. [alert show];
  191. } else {
  192. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  193. [alert show];
  194. }
  195. }
  196. }
  197. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  198. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  199. }
  200. }
  201. }
  202. - (void)changedLocation
  203. {
  204. // Only in background
  205. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  206. if (account.autoUpload && account.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  207. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  208. //check location
  209. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  210. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  211. [self uploadNewAssets];
  212. }
  213. } else {
  214. if (account.autoUpload == YES)
  215. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  216. if (account.autoUploadBackground == YES)
  217. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  218. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  219. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  220. }
  221. }
  222. }
  223. #pragma --------------------------------------------------------------------------------------------
  224. #pragma mark ===== Upload Assets : NEW & FULL ====
  225. #pragma --------------------------------------------------------------------------------------------
  226. - (void)uploadNewAssets
  227. {
  228. [self uploadAssetsNewAndFull:NO];
  229. }
  230. - (void)uploadFullAssets
  231. {
  232. [self uploadAssetsNewAndFull:YES];
  233. }
  234. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  235. {
  236. PHFetchResult *newAssetToUpload;
  237. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  238. // Check Asset : NEW or FULL
  239. if (assetsFull) {
  240. newAssetToUpload = [self getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast] account:account];
  241. } else {
  242. NSDate *databaseDatePhoto = account.autoUploadDatePhoto;
  243. NSDate *databaseDateVideo = account.autoUploadDateVideo;
  244. newAssetToUpload = [self getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo account:account];
  245. }
  246. // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
  247. if ([newAssetToUpload count] == 0) {
  248. NSLog(@"[LOG] Auto upload, no new asset found for date image %@, date video %@", account.autoUploadDatePhoto, account.autoUploadDateVideo);
  249. return;
  250. } else {
  251. NSLog(@"[LOG] Auto upload, new %lu asset found for date image %@, date video %@", (unsigned long)[newAssetToUpload count], account.autoUploadDatePhoto, account.autoUploadDateVideo);
  252. }
  253. if (assetsFull) {
  254. if (!_hud)
  255. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  256. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  257. }
  258. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  259. if (assetsFull)
  260. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newAssetToUpload waitUntilDone:NO];
  261. else
  262. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newAssetToUpload waitUntilDone:NO];
  263. });
  264. }
  265. - (void)uploadNewAssetsToNetwork:(PHFetchResult *)newAssetToUpload
  266. {
  267. [self uploadAssetsToNetwork:newAssetToUpload assetsFull:NO];
  268. }
  269. - (void)uploadFullAssetsToNetwork:(PHFetchResult *)newAssetToUpload
  270. {
  271. [self uploadAssetsToNetwork:newAssetToUpload assetsFull:YES];
  272. }
  273. - (void)uploadAssetsToNetwork:(PHFetchResult *)newAssetToUpload assetsFull:(BOOL)assetsFull
  274. {
  275. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  276. NSMutableArray *metadataNetFull = [NSMutableArray new];
  277. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  278. BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
  279. // Create the folder for Photos & if request the subfolders
  280. if(![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newAssetToUpload selector:selectorUploadAutoUploadAll]) {
  281. // end loading
  282. [_hud hideHud];
  283. return;
  284. }
  285. for (PHAsset *asset in newAssetToUpload) {
  286. NSString *serverUrl;
  287. NSDate *assetDate = asset.creationDate;
  288. PHAssetMediaType assetMediaType = asset.mediaType;
  289. NSString *session;
  290. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  291. // Select type of session
  292. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
  293. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
  294. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
  295. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
  296. NSDateFormatter *formatter = [NSDateFormatter new];
  297. [formatter setDateFormat:@"yyyy"];
  298. NSString *yearString = [formatter stringFromDate:assetDate];
  299. [formatter setDateFormat:@"MM"];
  300. NSString *monthString = [formatter stringFromDate:assetDate];
  301. if (useSubFolder)
  302. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  303. else
  304. serverUrl = autoUploadPath;
  305. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  306. metadataNet.action = actionUploadAsset;
  307. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  308. if (assetsFull) {
  309. metadataNet.selector = selectorUploadAutoUploadAll;
  310. // Option
  311. if ([[NCBrandOptions sharedInstance] use_storeLocalAutoUploadAll] == true)
  312. metadataNet.selectorPost = nil;
  313. else
  314. metadataNet.selectorPost = selectorUploadRemovePhoto;
  315. metadataNet.priority = NSOperationQueuePriorityLow;
  316. } else {
  317. metadataNet.selector = selectorUploadAutoUpload;
  318. metadataNet.selectorPost = nil;
  319. metadataNet.priority = NSOperationQueuePriorityLow;
  320. }
  321. metadataNet.fileName = fileName;
  322. metadataNet.serverUrl = serverUrl;
  323. metadataNet.session = session;
  324. metadataNet.taskStatus = k_taskStatusResume;
  325. if (assetsFull) {
  326. [metadataNetFull addObject:metadataNet];
  327. } else {
  328. NCRequestAsset *requestAsset = [NCRequestAsset new];
  329. requestAsset.delegate = self;
  330. [requestAsset writeAssetToSandboxFileName:metadataNet.fileName assetLocalIdentifier:metadataNet.assetLocalIdentifier selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:0 metadataNet:metadataNet serverUrl:serverUrl activeUrl:app.activeUrl directoryUser:app.directoryUser cryptated:NO session:metadataNet.session taskStatus:0 delegate:nil];
  331. }
  332. }
  333. // Insert all assets (Full) in TableAutoUpload
  334. if (assetsFull && [metadataNetFull count] > 0) {
  335. [[NCManageDatabase sharedInstance] addAutoUploadWithMetadatasNet:metadataNetFull];
  336. // Update icon badge number
  337. [app updateApplicationIconBadgeNumber];
  338. }
  339. // end loading
  340. [_hud hideHud];
  341. }
  342. - (void)addDatabaseAutoUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
  343. {
  344. if ([[NCManageDatabase sharedInstance] addAutoUploadWithMetadataNet:metadataNet]) {
  345. [[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];
  346. } else {
  347. [[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];
  348. }
  349. // Update Camera Auto Upload data
  350. if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload])
  351. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:assetDate];
  352. dispatch_async(dispatch_get_main_queue(), ^{
  353. // Update icon badge number
  354. [app updateApplicationIconBadgeNumber];
  355. });
  356. }
  357. #pragma --------------------------------------------------------------------------------------------
  358. #pragma mark ===== Load Auto Upload ====
  359. #pragma --------------------------------------------------------------------------------------------
  360. - (void)loadAutoUpload:(NSNumber *)maxConcurrent
  361. {
  362. CCMetadataNet *metadataNet;
  363. PHFetchResult *result;
  364. // Stop Timer
  365. [app.timerProcessAutoUpload invalidate];
  366. NSInteger maxConcurrentUpload = [maxConcurrent integerValue];
  367. NSInteger counterUploadInQueueAndInLock = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan] + [[[NCManageDatabase sharedInstance] getLockAutoUpload] count];
  368. NSInteger counterNewUpload = 0;
  369. // ------------------------- <selector Auto Upload> -------------------------
  370. while (counterUploadInQueueAndInLock < maxConcurrentUpload) {
  371. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUpload];
  372. if (metadataNet) {
  373. result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  374. } else
  375. break;
  376. if (result.count > 0) {
  377. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet.assetLocalIdentifier fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl cryptated:metadataNet.cryptated session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:app.activeMain];
  378. counterNewUpload++;
  379. } else {
  380. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selectorUploadAutoUploadAll note:@"Internal error image/video not found [0]" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  381. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  382. }
  383. counterUploadInQueueAndInLock = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan] + [[[NCManageDatabase sharedInstance] getLockAutoUpload] count];
  384. }
  385. // ------------------------- <selector Auto Upload All> ----------------------
  386. // Verify num error MAX 10 after STOP
  387. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionSelector = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)", app.activeAccount, selectorUploadAutoUploadAll, k_taskIdentifierError, k_taskIdentifierError] sorted:nil ascending:NO];
  388. NSInteger errorCount = [metadatas count];
  389. if (errorCount >= 10) {
  390. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  391. } else {
  392. while (counterUploadInQueueAndInLock < maxConcurrentUpload) {
  393. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUploadAll];
  394. if (metadataNet) {
  395. result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  396. } else
  397. break;
  398. if (result.count > 0) {
  399. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet.assetLocalIdentifier fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl cryptated:metadataNet.cryptated session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:app.activeMain];
  400. counterNewUpload++;
  401. } else {
  402. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selectorUploadAutoUploadAll note:@"Internal error image/video not found [0]" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  403. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  404. }
  405. counterUploadInQueueAndInLock = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan] + [[[NCManageDatabase sharedInstance] getLockAutoUpload] count];
  406. }
  407. }
  408. // Verify Lock
  409. NSInteger counterUploadInQueue = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan];
  410. NSArray *tableMetadatasInLock = [[NCManageDatabase sharedInstance] getLockAutoUpload];
  411. if (counterNewUpload == 0 && counterUploadInQueue == 0 && [tableMetadatasInLock count] > 0) {
  412. // Unlock
  413. for (tableMetadata *metadata in tableMetadatasInLock) {
  414. if ([[NCManageDatabase sharedInstance] isTableInvalidated:metadata] == NO)
  415. [[NCManageDatabase sharedInstance] unlockAutoUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier];
  416. }
  417. }
  418. // Start Timer
  419. app.timerProcessAutoUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoUpload target:app selector:@selector(processAutoUpload) userInfo:nil repeats:YES];
  420. }
  421. #pragma --------------------------------------------------------------------------------------------
  422. #pragma mark ===== Create Folder SubFolder Auto Upload Folder Photos ====
  423. #pragma --------------------------------------------------------------------------------------------
  424. - (BOOL)createFolderSubFolderAutoUploadFolderPhotos:(NSString *)folderPhotos useSubFolder:(BOOL)useSubFolder assets:(PHFetchResult *)assets selector:(NSString *)selector
  425. {
  426. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  427. if ([ocNetworking automaticCreateFolderSync:folderPhotos]) {
  428. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:folderPhotos permissions:@""];
  429. } else {
  430. // Activity
  431. [[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];
  432. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  433. return false;
  434. }
  435. // Create if request the subfolders
  436. if (useSubFolder) {
  437. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  438. if ([ocNetworking automaticCreateFolderSync:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  439. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder] permissions:@""];
  440. } else {
  441. // Activity
  442. [[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];
  443. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  444. return false;
  445. }
  446. }
  447. }
  448. return true;
  449. }
  450. #pragma --------------------------------------------------------------------------------------------
  451. #pragma mark ===== get Camera Roll new Asset ====
  452. #pragma --------------------------------------------------------------------------------------------
  453. - (PHFetchResult *)getCameraRollNewItemsWithDatePhoto:(NSDate *)datePhoto dateVideo:(NSDate *)dateVideo account:(tableAccount *)account
  454. {
  455. @synchronized(self) {
  456. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  457. PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
  458. NSPredicate *predicateImage = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage], [NSPredicate predicateWithFormat:@"creationDate > %@", datePhoto]]];
  459. NSPredicate *predicateVideo = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeVideo], [NSPredicate predicateWithFormat:@"creationDate > %@", dateVideo]]];
  460. NSPredicate *predicate;
  461. if (account.autoUploadPhoto && account.autoUploadVideo) {
  462. predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateImage, predicateVideo]];
  463. } else if (account.autoUploadPhoto) {
  464. predicate = predicateImage;
  465. } else if (account.autoUploadVideo) {
  466. predicate = predicateVideo;
  467. }
  468. PHFetchOptions *newInstantUploadAssetsFetchOptions = [PHFetchOptions new];
  469. newInstantUploadAssetsFetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
  470. newInstantUploadAssetsFetchOptions.predicate = predicate;
  471. PHAssetCollection *collection = result[0];
  472. PHFetchResult *newAssetToUpload = [PHAsset fetchAssetsInAssetCollection:collection options:newInstantUploadAssetsFetchOptions];
  473. return newAssetToUpload;
  474. } else {
  475. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"_ok_", nil) otherButtonTitles:nil];
  476. [alert show];
  477. }
  478. }
  479. return nil;
  480. }
  481. @end