NCAutoUpload.m 32 KB

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