NCAutoUpload.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. // ONLY FOR TEST
  239. //[self getCameraRollNewItemsWithDatePhotoTEST:[NSDate distantPast] dateVideo:[NSDate distantPast] account:account];
  240. // Check Asset : NEW or FULL
  241. if (assetsFull) {
  242. newAssetToUpload = [self getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast] account:account];
  243. } else {
  244. NSDate *databaseDatePhoto = account.autoUploadDatePhoto;
  245. NSDate *databaseDateVideo = account.autoUploadDateVideo;
  246. newAssetToUpload = [self getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo account:account];
  247. }
  248. // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
  249. if ([newAssetToUpload count] == 0) {
  250. NSLog(@"[LOG] Auto upload, no new asset found for date image %@, date video %@", account.autoUploadDatePhoto, account.autoUploadDateVideo);
  251. return;
  252. } else {
  253. NSLog(@"[LOG] Auto upload, new %lu asset found for date image %@, date video %@", (unsigned long)[newAssetToUpload count], account.autoUploadDatePhoto, account.autoUploadDateVideo);
  254. }
  255. if (assetsFull) {
  256. if (!_hud)
  257. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  258. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  259. }
  260. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  261. if (assetsFull)
  262. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newAssetToUpload waitUntilDone:NO];
  263. else
  264. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newAssetToUpload waitUntilDone:NO];
  265. });
  266. }
  267. - (void)uploadNewAssetsToNetwork:(PHFetchResult *)newAssetToUpload
  268. {
  269. [self uploadAssetsToNetwork:newAssetToUpload assetsFull:NO];
  270. }
  271. - (void)uploadFullAssetsToNetwork:(PHFetchResult *)newAssetToUpload
  272. {
  273. [self uploadAssetsToNetwork:newAssetToUpload assetsFull:YES];
  274. }
  275. - (void)uploadAssetsToNetwork:(PHFetchResult *)newAssetToUpload assetsFull:(BOOL)assetsFull
  276. {
  277. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  278. NSMutableArray *metadataNetFull = [NSMutableArray new];
  279. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  280. BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
  281. // Create the folder for Photos & if request the subfolders
  282. if(![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newAssetToUpload selector:selectorUploadAutoUploadAll]) {
  283. // end loading
  284. [_hud hideHud];
  285. return;
  286. }
  287. for (PHAsset *asset in newAssetToUpload) {
  288. NSString *serverUrl;
  289. NSDate *assetDate = asset.creationDate;
  290. PHAssetMediaType assetMediaType = asset.mediaType;
  291. NSString *session;
  292. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  293. // Select type of session
  294. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
  295. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
  296. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
  297. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
  298. NSDateFormatter *formatter = [NSDateFormatter new];
  299. [formatter setDateFormat:@"yyyy"];
  300. NSString *yearString = [formatter stringFromDate:assetDate];
  301. [formatter setDateFormat:@"MM"];
  302. NSString *monthString = [formatter stringFromDate:assetDate];
  303. if (useSubFolder)
  304. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  305. else
  306. serverUrl = autoUploadPath;
  307. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  308. metadataNet.action = actionUploadAsset;
  309. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  310. if (assetsFull) {
  311. metadataNet.selector = selectorUploadAutoUploadAll;
  312. // Option
  313. if ([[NCBrandOptions sharedInstance] use_storeLocalAutoUploadAll] == true)
  314. metadataNet.selectorPost = nil;
  315. else
  316. metadataNet.selectorPost = selectorUploadRemovePhoto;
  317. metadataNet.priority = NSOperationQueuePriorityLow;
  318. } else {
  319. metadataNet.selector = selectorUploadAutoUpload;
  320. metadataNet.selectorPost = nil;
  321. metadataNet.priority = NSOperationQueuePriorityLow;
  322. }
  323. metadataNet.fileName = fileName;
  324. metadataNet.serverUrl = serverUrl;
  325. metadataNet.session = session;
  326. metadataNet.taskStatus = k_taskStatusResume;
  327. if (assetsFull) {
  328. [metadataNetFull addObject:metadataNet];
  329. } else {
  330. NCRequestAsset *requestAsset = [NCRequestAsset new];
  331. requestAsset.delegate = self;
  332. [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];
  333. }
  334. }
  335. // Insert all assets (Full) in TableAutoUpload
  336. if (assetsFull && [metadataNetFull count] > 0) {
  337. [[NCManageDatabase sharedInstance] addAutoUploadWithMetadatasNet:metadataNetFull];
  338. // Update icon badge number
  339. [app updateApplicationIconBadgeNumber];
  340. }
  341. // end loading
  342. [_hud hideHud];
  343. }
  344. - (void)addDatabaseAutoUpload:(CCMetadataNet *)metadataNet modificationDate:(NSDate *)modificationDate assetMediaType:(PHAssetMediaType)assetMediaType
  345. {
  346. if ([[NCManageDatabase sharedInstance] addAutoUploadWithMetadataNet:metadataNet]) {
  347. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload, Asset Data: %@", [NSDateFormatter localizedStringFromDate:modificationDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  348. } else {
  349. [[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:modificationDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  350. }
  351. // Update Camera Auto Upload data
  352. if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload])
  353. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:modificationDate];
  354. dispatch_async(dispatch_get_main_queue(), ^{
  355. // Update icon badge number
  356. [app updateApplicationIconBadgeNumber];
  357. });
  358. }
  359. #pragma --------------------------------------------------------------------------------------------
  360. #pragma mark ===== Load Auto Upload ====
  361. #pragma --------------------------------------------------------------------------------------------
  362. - (void)loadAutoUpload:(NSNumber *)maxConcurrent
  363. {
  364. CCMetadataNet *metadataNet;
  365. PHFetchResult *result;
  366. // Stop Timer
  367. [app.timerProcessAutoUpload invalidate];
  368. NSInteger maxConcurrentUpload = [maxConcurrent integerValue];
  369. NSInteger counterUploadInQueueAndInLock = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan] + [[[NCManageDatabase sharedInstance] getLockAutoUpload] count];
  370. NSInteger counterNewUpload = 0;
  371. // ------------------------- <selector Auto Upload> -------------------------
  372. while (counterUploadInQueueAndInLock < maxConcurrentUpload) {
  373. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUpload];
  374. if (metadataNet) {
  375. result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  376. } else
  377. break;
  378. if (result.count > 0) {
  379. [[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];
  380. counterNewUpload++;
  381. } else {
  382. [[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];
  383. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  384. }
  385. counterUploadInQueueAndInLock = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan] + [[[NCManageDatabase sharedInstance] getLockAutoUpload] count];
  386. }
  387. // ------------------------- <selector Auto Upload All> ----------------------
  388. // Verify num error MAX 10 after STOP
  389. 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];
  390. NSInteger errorCount = [metadatas count];
  391. if (errorCount >= 10) {
  392. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  393. } else {
  394. while (counterUploadInQueueAndInLock < maxConcurrentUpload) {
  395. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUploadAll];
  396. if (metadataNet) {
  397. result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  398. } else
  399. break;
  400. if (result.count > 0) {
  401. [[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];
  402. counterNewUpload++;
  403. } else {
  404. [[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];
  405. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  406. }
  407. counterUploadInQueueAndInLock = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan] + [[[NCManageDatabase sharedInstance] getLockAutoUpload] count];
  408. }
  409. }
  410. // Verify Lock
  411. NSInteger counterUploadInQueue = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan];
  412. NSArray *tableMetadatasInLock = [[NCManageDatabase sharedInstance] getLockAutoUpload];
  413. if (counterNewUpload == 0 && counterUploadInQueue == 0 && [tableMetadatasInLock count] > 0) {
  414. // Unlock
  415. for (tableMetadata *metadata in tableMetadatasInLock) {
  416. if ([[NCManageDatabase sharedInstance] isTableInvalidated:metadata] == NO)
  417. [[NCManageDatabase sharedInstance] unlockAutoUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier];
  418. }
  419. }
  420. // Start Timer
  421. app.timerProcessAutoUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoUpload target:app selector:@selector(processAutoUpload) userInfo:nil repeats:YES];
  422. }
  423. #pragma --------------------------------------------------------------------------------------------
  424. #pragma mark ===== Create Folder SubFolder Auto Upload Folder Photos ====
  425. #pragma --------------------------------------------------------------------------------------------
  426. - (BOOL)createFolderSubFolderAutoUploadFolderPhotos:(NSString *)folderPhotos useSubFolder:(BOOL)useSubFolder assets:(PHFetchResult *)assets selector:(NSString *)selector
  427. {
  428. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  429. if ([ocNetworking automaticCreateFolderSync:folderPhotos]) {
  430. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:folderPhotos permissions:@""];
  431. } else {
  432. // Activity
  433. [[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];
  434. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  435. return false;
  436. }
  437. // Create if request the subfolders
  438. if (useSubFolder) {
  439. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  440. if ([ocNetworking automaticCreateFolderSync:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  441. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder] permissions:@""];
  442. } else {
  443. // Activity
  444. [[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];
  445. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  446. return false;
  447. }
  448. }
  449. }
  450. return true;
  451. }
  452. #pragma --------------------------------------------------------------------------------------------
  453. #pragma mark ===== get Camera Roll new Asset ====
  454. #pragma --------------------------------------------------------------------------------------------
  455. - (PHFetchResult *)getCameraRollNewItemsWithDatePhotoOLD:(NSDate *)datePhoto dateVideo:(NSDate *)dateVideo account:(tableAccount *)account
  456. {
  457. @synchronized(self) {
  458. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  459. PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
  460. NSPredicate *predicateImage = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage], [NSPredicate predicateWithFormat:@"creationDate > %@", datePhoto]]];
  461. NSPredicate *predicateVideo = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeVideo], [NSPredicate predicateWithFormat:@"creationDate > %@", dateVideo]]];
  462. NSPredicate *predicate;
  463. if (account.autoUploadPhoto && account.autoUploadVideo) {
  464. predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateImage, predicateVideo]];
  465. } else if (account.autoUploadPhoto) {
  466. predicate = predicateImage;
  467. } else if (account.autoUploadVideo) {
  468. predicate = predicateVideo;
  469. }
  470. PHFetchOptions *newInstantUploadAssetsFetchOptions = [PHFetchOptions new];
  471. newInstantUploadAssetsFetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
  472. newInstantUploadAssetsFetchOptions.predicate = predicate;
  473. PHAssetCollection *collection = result[0];
  474. PHFetchResult *newAssetToUpload = [PHAsset fetchAssetsInAssetCollection:collection options:newInstantUploadAssetsFetchOptions];
  475. return newAssetToUpload;
  476. } else {
  477. 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];
  478. [alert show];
  479. }
  480. }
  481. return nil;
  482. }
  483. - (PHFetchResult *)getCameraRollNewItemsWithDatePhoto:(NSDate *)datePhoto dateVideo:(NSDate *)dateVideo account:(tableAccount *)account
  484. {
  485. @synchronized(self) {
  486. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  487. PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
  488. NSPredicate *predicateImage = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage], [NSPredicate predicateWithFormat:@"modificationDate > %@", datePhoto]]];
  489. NSPredicate *predicateVideo = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeVideo], [NSPredicate predicateWithFormat:@"modificationDate > %@", dateVideo]]];
  490. NSPredicate *predicate;
  491. if (account.autoUploadPhoto && account.autoUploadVideo) {
  492. predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateImage, predicateVideo]];
  493. } else if (account.autoUploadPhoto) {
  494. predicate = predicateImage;
  495. } else if (account.autoUploadVideo) {
  496. predicate = predicateVideo;
  497. }
  498. PHFetchOptions *newInstantUploadAssetsFetchOptions = [PHFetchOptions new];
  499. newInstantUploadAssetsFetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"modificationDate" ascending:YES]];
  500. newInstantUploadAssetsFetchOptions.predicate = predicate;
  501. PHAssetCollection *collection = result[0];
  502. PHFetchResult *newAssetToUpload = [PHAsset fetchAssetsInAssetCollection:collection options:newInstantUploadAssetsFetchOptions];
  503. for (PHAsset *asset in newAssetToUpload) {
  504. NSLog(@"%@ - %@", asset.modificationDate, asset);
  505. }
  506. PHFetchResult *allAssetToUpload = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
  507. for (PHAsset *asset in allAssetToUpload) {
  508. NSLog(@"%@ > %@ - %@", asset.modificationDate, datePhoto, asset);
  509. }
  510. return newAssetToUpload;
  511. } else {
  512. 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];
  513. [alert show];
  514. }
  515. }
  516. return nil;
  517. }
  518. @end