NCAutoUpload.m 33 KB

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