NCAutoUpload.m 34 KB

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