NCAutoUpload.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. // Disable idle timer
  279. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  280. if (assetsFull) {
  281. if (!_hud)
  282. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  283. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  284. }
  285. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  286. if (assetsFull)
  287. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  288. else
  289. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  290. });
  291. }
  292. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  293. {
  294. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  295. }
  296. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  297. {
  298. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  299. }
  300. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  301. {
  302. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  303. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  304. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  305. BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
  306. // Conversion from ALAsset -to-> PHAsset
  307. for (ALAsset *asset in newItemsToUpload) {
  308. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  309. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  310. PHAsset *asset = [fetchResult firstObject];
  311. [newItemsPHAssetToUpload addObject:asset];
  312. NSLog(@"Convert url %@", url);
  313. }
  314. // Create the folder for Photos & if request the subfolders
  315. if(![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutoUploadAll]) {
  316. // end loading
  317. [_hud hideHud];
  318. // Enable idle timer
  319. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  320. return;
  321. }
  322. for (PHAsset *asset in newItemsPHAssetToUpload) {
  323. NSString *serverUrl;
  324. NSDate *assetDate = asset.creationDate;
  325. PHAssetMediaType assetMediaType = asset.mediaType;
  326. NSString *session;
  327. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  328. // Select type of session
  329. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
  330. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
  331. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
  332. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
  333. NSDateFormatter *formatter = [NSDateFormatter new];
  334. [formatter setDateFormat:@"yyyy"];
  335. NSString *yearString = [formatter stringFromDate:assetDate];
  336. [formatter setDateFormat:@"MM"];
  337. NSString *monthString = [formatter stringFromDate:assetDate];
  338. if (useSubFolder)
  339. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  340. else
  341. serverUrl = autoUploadPath;
  342. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  343. metadataNet.action = actionUploadAsset;
  344. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  345. if (assetsFull) {
  346. metadataNet.selector = selectorUploadAutoUploadAll;
  347. metadataNet.selectorPost = selectorUploadRemovePhoto;
  348. metadataNet.priority = NSOperationQueuePriorityLow;
  349. } else {
  350. metadataNet.selector = selectorUploadAutoUpload;
  351. metadataNet.selectorPost = nil;
  352. metadataNet.priority = NSOperationQueuePriorityNormal;
  353. }
  354. metadataNet.fileName = fileName;
  355. metadataNet.serverUrl = serverUrl;
  356. metadataNet.session = session;
  357. metadataNet.taskStatus = k_taskStatusResume;
  358. if (assetsFull)
  359. [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  360. else
  361. [self writeAssetToSandbox:metadataNet];
  362. }
  363. // end loading
  364. [_hud hideHud];
  365. // Enable idle timer
  366. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  367. }
  368. - (void)writeAssetToSandbox:(CCMetadataNet *)metadataNet
  369. {
  370. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  371. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  372. PHAsset *asset = result[0];
  373. PHAssetMediaType assetMediaType = asset.mediaType;
  374. NSDate *assetDate = asset.creationDate;
  375. __block NSError *error = nil;
  376. // VIDEO
  377. if (assetMediaType == PHAssetMediaTypeVideo) {
  378. @autoreleasepool {
  379. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  380. options.networkAccessAllowed = true;
  381. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  382. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]])
  383. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] error:nil];
  384. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  385. if (exportSession) {
  386. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]];
  387. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  388. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  389. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  390. [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  391. } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
  392. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  393. } else {
  394. NSLog(@"Export Session Status: %ld", (long)exportSession.status);
  395. }
  396. }];
  397. } else {
  398. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  399. }
  400. }];
  401. }
  402. }
  403. // IMAGE
  404. if (assetMediaType == PHAssetMediaTypeImage) {
  405. @autoreleasepool {
  406. PHImageRequestOptions *options = [PHImageRequestOptions new];
  407. options.synchronous = NO;
  408. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  409. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  410. if (error) {
  411. NSString *note = [NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description];
  412. [[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];
  413. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  414. } else {
  415. [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  416. }
  417. }];
  418. }
  419. }
  420. }
  421. - (void)addDatabaseAutoUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
  422. {
  423. if ([[NCManageDatabase sharedInstance] addAutoUploadWithMetadataNet:metadataNet]) {
  424. [[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];
  425. } else {
  426. [[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];
  427. }
  428. dispatch_async(dispatch_get_main_queue(), ^{
  429. // Update Camera Auto Upload data
  430. if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload])
  431. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:assetDate];
  432. // Update icon badge number
  433. [app updateApplicationIconBadgeNumber];
  434. });
  435. }
  436. #pragma --------------------------------------------------------------------------------------------
  437. #pragma mark ===== Load Auto Upload ====
  438. #pragma --------------------------------------------------------------------------------------------
  439. - (void)loadAutoUpload:(NSNumber *)maxConcurrent
  440. {
  441. CCMetadataNet *metadataNet;
  442. NSInteger counterUpload = 0;
  443. NSInteger maxConcurrentOperationDownloadUpload = [maxConcurrent integerValue];
  444. NSArray *uploadInQueue = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  445. NSArray *recordAutomaticUploadInLock = [[NCManageDatabase sharedInstance] getLockAutoUpload];
  446. for (tableAutoUpload *tableAutoUpload in recordAutomaticUploadInLock) {
  447. BOOL recordFound = NO;
  448. for (CCMetadataNet *metadataNet in uploadInQueue) {
  449. if (metadataNet.assetLocalIdentifier == tableAutoUpload.assetLocalIdentifier)
  450. recordFound = YES;
  451. }
  452. if (!recordFound)
  453. [[NCManageDatabase sharedInstance] unlockAutoUploadWithAssetLocalIdentifier:tableAutoUpload.assetLocalIdentifier];
  454. }
  455. // ------------------------- <selector Auto Upload> -------------------------
  456. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUpload];
  457. counterUpload = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan];
  458. while (metadataNet && counterUpload < maxConcurrentOperationDownloadUpload) {
  459. [[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];
  460. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUpload];
  461. counterUpload++;
  462. }
  463. // ------------------------- <selector Auto Upload All> ----------------------
  464. // Verify num error MAX 10 after STOP
  465. 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];
  466. NSInteger errorCount = [metadatas count];
  467. if (errorCount >= 10) {
  468. [app messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  469. return;
  470. }
  471. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUploadAll];
  472. counterUpload = [app getNumberUploadInQueues] + [app getNumberUploadInQueuesWWan];
  473. while (metadataNet && counterUpload < maxConcurrentOperationDownloadUpload) {
  474. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  475. if (result.count > 0) {
  476. [[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];
  477. counterUpload++;
  478. } else {
  479. [[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];
  480. [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  481. }
  482. metadataNet = [[NCManageDatabase sharedInstance] getAutoUploadWithSelector:selectorUploadAutoUploadAll];
  483. }
  484. }
  485. #pragma --------------------------------------------------------------------------------------------
  486. #pragma mark ===== Create Folder SubFolder Auto Upload Folder Photos ====
  487. #pragma --------------------------------------------------------------------------------------------
  488. - (BOOL)createFolderSubFolderAutoUploadFolderPhotos:(NSString *)folderPhotos useSubFolder:(BOOL)useSubFolder assets:(NSArray *)assets selector:(NSString *)selector
  489. {
  490. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  491. if ([ocNetworking automaticCreateFolderSync:folderPhotos]) {
  492. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:folderPhotos permissions:@""];
  493. } else {
  494. // Activity
  495. [[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];
  496. return false;
  497. }
  498. // Create if request the subfolders
  499. if (useSubFolder) {
  500. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  501. if ([ocNetworking automaticCreateFolderSync:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  502. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder] permissions:@""];
  503. } else {
  504. // Activity
  505. [[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];
  506. return false;
  507. }
  508. }
  509. }
  510. return true;
  511. }
  512. @end