CCAutoUpload.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. //
  2. // CCAutoUpload.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 07/06/17.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "CCAutoUpload.h"
  24. #import "AppDelegate.h"
  25. #import "NCBridgeSwift.h"
  26. #import "CCHud.h"
  27. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  28. @interface CCAutoUpload ()
  29. {
  30. AppDelegate *appDelegate;
  31. CCHud *_hud;
  32. BOOL endForAssetToUpload;
  33. }
  34. @end
  35. @implementation CCAutoUpload
  36. + (CCAutoUpload *)shared {
  37. static CCAutoUpload *shared;
  38. @synchronized(self)
  39. {
  40. if (!shared) {
  41. shared = [CCAutoUpload new];
  42. shared->appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  43. }
  44. return shared;
  45. }
  46. }
  47. #pragma --------------------------------------------------------------------------------------------
  48. #pragma mark === initStateAutoUpload ===
  49. #pragma --------------------------------------------------------------------------------------------
  50. - (void)initStateAutoUpload
  51. {
  52. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  53. if (account.autoUpload) {
  54. [self setupAutoUpload];
  55. if (account.autoUploadBackground) {
  56. [self checkIfLocationIsEnabled];
  57. }
  58. } else {
  59. [[CCManageLocation shared] stopSignificantChangeUpdates];
  60. }
  61. }
  62. #pragma --------------------------------------------------------------------------------------------
  63. #pragma mark === Camera Upload & Full ===
  64. #pragma --------------------------------------------------------------------------------------------
  65. - (void)setupAutoUpload
  66. {
  67. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  68. [self performSelectorOnMainThread:@selector(uploadNewAssets) withObject:nil waitUntilDone:NO];
  69. } else {
  70. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  71. if (account.autoUpload == YES)
  72. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  73. [[CCManageLocation shared] stopSignificantChangeUpdates];
  74. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  75. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  76. [alertController addAction:okAction];
  77. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  78. return;
  79. }
  80. }
  81. - (void)setupAutoUploadFull
  82. {
  83. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  84. [self performSelectorOnMainThread:@selector(uploadFullAssets) withObject:nil waitUntilDone:NO];
  85. } else {
  86. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  87. if (account.autoUpload == YES)
  88. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  89. [[CCManageLocation shared] stopSignificantChangeUpdates];
  90. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  91. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  92. [alertController addAction:okAction];
  93. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  94. }
  95. }
  96. #pragma --------------------------------------------------------------------------------------------
  97. #pragma mark === Location ===
  98. #pragma --------------------------------------------------------------------------------------------
  99. - (BOOL)checkIfLocationIsEnabled
  100. {
  101. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  102. [CCManageLocation shared].delegate = self;
  103. if ([CLLocationManager locationServicesEnabled]) {
  104. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Check if location is enabled: authorizationStatus: %d", [CLLocationManager authorizationStatus]]];
  105. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  106. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  107. [[NCCommunicationCommon shared] writeLog:@"Check if location is enabled: Location services not determined"];
  108. [[CCManageLocation shared] startSignificantChangeUpdates];
  109. } else {
  110. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  111. if (account.autoUploadBackground == YES)
  112. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  113. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  114. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  115. [alertController addAction:okAction];
  116. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  117. } else {
  118. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  119. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  120. [alertController addAction:okAction];
  121. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  122. }
  123. }
  124. } else {
  125. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  126. if (account.autoUploadBackground == NO)
  127. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:YES];
  128. [[CCManageLocation shared] startSignificantChangeUpdates];
  129. } else {
  130. if (account.autoUploadBackground == YES)
  131. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  132. [[CCManageLocation shared] stopSignificantChangeUpdates];
  133. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  134. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  135. [alertController addAction:okAction];
  136. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  137. }
  138. }
  139. } else {
  140. if (account.autoUploadBackground == YES)
  141. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  142. [[CCManageLocation shared] stopSignificantChangeUpdates];
  143. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  144. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  145. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  146. [alertController addAction:okAction];
  147. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  148. } else {
  149. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  150. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  151. [alertController addAction:okAction];
  152. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  153. }
  154. }
  155. tableAccount *tableAccount = [[NCManageDatabase shared] getAccountActive];
  156. return tableAccount.autoUploadBackground;
  157. }
  158. - (void)statusAuthorizationLocationChanged
  159. {
  160. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  161. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  162. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  163. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  164. if ([CCManageLocation shared].firstChangeAuthorizationDone) {
  165. if (account.autoUploadBackground == YES)
  166. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  167. [[CCManageLocation shared] stopSignificantChangeUpdates];
  168. }
  169. } else {
  170. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  171. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  172. [alertController addAction:okAction];
  173. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  174. }
  175. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  176. if (account.autoUploadBackground == YES) {
  177. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  178. [[CCManageLocation shared] stopSignificantChangeUpdates];
  179. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  180. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_location_not_enabled_", nil) message:NSLocalizedString(@"_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  181. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  182. [alertController addAction:okAction];
  183. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  184. } else {
  185. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  186. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  187. [alertController addAction:okAction];
  188. [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertController animated:YES completion:nil];
  189. }
  190. }
  191. }
  192. if (![CCManageLocation shared].firstChangeAuthorizationDone) {
  193. [CCManageLocation shared].firstChangeAuthorizationDone = YES;
  194. }
  195. }
  196. }
  197. - (void)changedLocation
  198. {
  199. // Only in background
  200. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  201. if (account.autoUpload && account.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  202. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  203. //check location
  204. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  205. [[NCCommunicationCommon shared] writeLog:@"Changed Location call upload new assets"];
  206. [self uploadNewAssets];
  207. }
  208. } else {
  209. if (account.autoUpload == YES)
  210. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUpload" state:NO];
  211. if (account.autoUploadBackground == YES)
  212. [[NCManageDatabase shared] setAccountAutoUploadProperty:@"autoUploadBackground" state:NO];
  213. [[CCManageLocation shared] stopSignificantChangeUpdates];
  214. }
  215. }
  216. }
  217. #pragma --------------------------------------------------------------------------------------------
  218. #pragma mark ===== Upload Assets : NEW & FULL ====
  219. #pragma --------------------------------------------------------------------------------------------
  220. - (void)uploadNewAssets
  221. {
  222. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  223. [self uploadAssetsNewAndFull:NCBrandGlobal.shared.selectorUploadAutoUpload];
  224. });
  225. }
  226. - (void)uploadFullAssets
  227. {
  228. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  229. [self uploadAssetsNewAndFull:NCBrandGlobal.shared.selectorUploadAutoUploadAll];
  230. });
  231. }
  232. - (void)uploadAssetsNewAndFull:(NSString *)selector
  233. {
  234. if (!appDelegate.account) return;
  235. tableAccount *tableAccount = [[NCManageDatabase shared] getAccountActive];
  236. if (tableAccount == nil) {
  237. return;
  238. }
  239. NSMutableArray *metadataFull = [NSMutableArray new];
  240. NSString *autoUploadPath = [[NCManageDatabase shared] getAccountAutoUploadPathWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  241. NSString *serverUrl;
  242. __block NSInteger counterLivePhoto = 0;
  243. // Check Asset : NEW or FULL
  244. NSArray *newAssetToUpload = [self getCameraRollAssets:tableAccount selector:selector alignPhotoLibrary:NO];
  245. // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
  246. if (newAssetToUpload == nil || [newAssetToUpload count] == 0) {
  247. [[NCCommunicationCommon shared] writeLog:@"Automatic upload, no new assets found"];
  248. return;
  249. } else {
  250. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Automatic upload, new %lu assets found", (unsigned long)[newAssetToUpload count]]];
  251. }
  252. dispatch_async(dispatch_get_main_queue(), ^{
  253. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  254. if (!_hud)
  255. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  256. [[NCContentPresenter shared] messageNotification:@"_attention_" description:@"_create_full_upload_" delay:[[NCBrandGlobal shared] dismissAfterSecondLong] type:messageTypeInfo errorCode:0 forced:true];
  257. [_hud visibleHudTitle:NSLocalizedString(@"_wait_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  258. }
  259. });
  260. // Create the folder for auto upload & if request the subfolders
  261. if ([[NCNetworking shared] createFolderWithAssets:newAssetToUpload selector:selector useSubFolder:tableAccount.autoUploadCreateSubfolder account:appDelegate.account urlBase:appDelegate.urlBase]) {
  262. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  263. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" delay:[[NCBrandGlobal shared] dismissAfterSecond] type:messageTypeError errorCode:NCBrandGlobal.shared.ErrorInternalError forced:true];
  264. dispatch_async(dispatch_get_main_queue(), ^{
  265. [_hud hideHud];
  266. });
  267. }
  268. return;
  269. }
  270. endForAssetToUpload = false;
  271. for (PHAsset *asset in newAssetToUpload) {
  272. BOOL livePhoto = false;
  273. NSDate *assetDate = asset.creationDate;
  274. PHAssetMediaType assetMediaType = asset.mediaType;
  275. NSString *session;
  276. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:NCBrandGlobal.shared.keyFileNameAutoUploadMask keyFileNameType:NCBrandGlobal.shared.keyFileNameAutoUploadType keyFileNameOriginal:NCBrandGlobal.shared.keyFileNameOriginalAutoUpload];
  277. // Detect LivePhoto Upload
  278. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto) {
  279. livePhoto = true;
  280. }
  281. // Select type of session
  282. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  283. session = NCCommunicationCommon.shared.sessionIdentifierUpload;
  284. } else {
  285. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = NCNetworking.shared.sessionIdentifierBackground;
  286. else if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = NCNetworking.shared.sessionIdentifierBackground;
  287. else if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = NCNetworking.shared.sessionIdentifierBackgroundWWan;
  288. else if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = NCNetworking.shared.sessionIdentifierBackgroundWWan;
  289. else session = NCNetworking.shared.sessionIdentifierBackground;
  290. }
  291. NSDateFormatter *formatter = [NSDateFormatter new];
  292. [formatter setDateFormat:@"yyyy"];
  293. NSString *yearString = [formatter stringFromDate:assetDate];
  294. [formatter setDateFormat:@"MM"];
  295. NSString *monthString = [formatter stringFromDate:assetDate];
  296. if (tableAccount.autoUploadCreateSubfolder)
  297. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  298. else
  299. serverUrl = autoUploadPath;
  300. tableMetadata *metadata = [[NCManageDatabase shared] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.account, serverUrl, fileName]];
  301. if (metadata) {
  302. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUpload]) {
  303. [[NCManageDatabase shared] addPhotoLibrary:@[asset] account:appDelegate.account];
  304. }
  305. } else {
  306. /* INSERT METADATA FOR UPLOAD */
  307. tableMetadata *metadataForUpload = [[NCManageDatabase shared] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  308. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  309. metadataForUpload.livePhoto = livePhoto;
  310. metadataForUpload.session = session;
  311. metadataForUpload.sessionSelector = selector;
  312. metadataForUpload.size = [[NCUtilityFileSystem shared] getFileSizeWithAsset:asset];
  313. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload;
  314. if (assetMediaType == PHAssetMediaTypeVideo) {
  315. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileVideo;
  316. } else if (assetMediaType == PHAssetMediaTypeImage) {
  317. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileImage;
  318. }
  319. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUpload]) {
  320. [[NCManageDatabase shared] addMetadataForAutoUpload:metadataForUpload];
  321. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Automatic upload added %@ (%lu bytes) with Identifier %@", metadata.fileNameView, (unsigned long)metadata.size, metadata.assetLocalIdentifier]];
  322. [[NCManageDatabase shared] addPhotoLibrary:@[asset] account:appDelegate.account];
  323. } else if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  324. [metadataFull addObject:metadataForUpload];
  325. }
  326. /* INSERT METADATA MOV LIVE PHOTO FOR UPLOAD */
  327. if (livePhoto) {
  328. counterLivePhoto++;
  329. NSString *fileNameMove = [NSString stringWithFormat:@"%@.mov", fileName.stringByDeletingPathExtension];
  330. NSString *ocId = [[NSUUID UUID] UUIDString];
  331. NSString *filePath = [CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameMove];
  332. [CCUtility extractLivePhotoAsset:asset filePath:filePath withCompletion:^(NSURL *url) {
  333. if (url != nil) {
  334. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  335. tableMetadata *metadataMOVForUpload = [[NCManageDatabase shared] createMetadataWithAccount:appDelegate.account fileName:fileNameMove ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  336. metadataMOVForUpload.livePhoto = true;
  337. metadataMOVForUpload.session = session;
  338. metadataMOVForUpload.sessionSelector = selector;
  339. metadataMOVForUpload.size = fileSize;
  340. metadataMOVForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload;
  341. metadataMOVForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileVideo;
  342. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUpload]) {
  343. [[NCManageDatabase shared] addMetadataForAutoUpload:metadataMOVForUpload];
  344. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Automatic upload added Live Photo %@ (%llu bytes)", fileNameMove, fileSize]];
  345. } else if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  346. [metadataFull addObject:metadataMOVForUpload];
  347. }
  348. }
  349. counterLivePhoto--;
  350. dispatch_async(dispatch_get_main_queue(), ^{
  351. if (endForAssetToUpload && counterLivePhoto == 0 && [selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  352. [[NCManageDatabase shared] addMetadatas:metadataFull];
  353. [_hud hideHud];
  354. }
  355. });
  356. }];
  357. }
  358. }
  359. }
  360. endForAssetToUpload = true;
  361. dispatch_async(dispatch_get_main_queue(), ^{
  362. if (counterLivePhoto == 0 && [selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUploadAll]) {
  363. [[NCManageDatabase shared] addMetadatas:metadataFull];
  364. [_hud hideHud];
  365. }
  366. });
  367. }
  368. #pragma --------------------------------------------------------------------------------------------
  369. #pragma mark ===== get Camera Roll new Asset ====
  370. #pragma --------------------------------------------------------------------------------------------
  371. - (NSArray *)getCameraRollAssets:(tableAccount *)account selector:(NSString *)selector alignPhotoLibrary:(BOOL)alignPhotoLibrary
  372. {
  373. @synchronized(self) {
  374. if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
  375. PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
  376. if (result.count == 0) {
  377. return nil;
  378. }
  379. NSPredicate *predicateImage = [NSPredicate predicateWithFormat:@"mediaType == %i", PHAssetMediaTypeImage];
  380. NSPredicate *predicateVideo = [NSPredicate predicateWithFormat:@"mediaType == %i", PHAssetMediaTypeVideo];
  381. NSPredicate *predicate;
  382. NSMutableArray *newAssets =[NSMutableArray new];
  383. if (alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo)) {
  384. predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateImage, predicateVideo]];
  385. } else if (account.autoUploadImage) {
  386. predicate = predicateImage;
  387. } else if (account.autoUploadVideo) {
  388. predicate = predicateVideo;
  389. } else {
  390. return nil;
  391. }
  392. PHFetchOptions *fetchOptions = [PHFetchOptions new];
  393. fetchOptions.predicate = predicate;
  394. PHAssetCollection *collection = result[0];
  395. PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];
  396. if ([selector isEqualToString:NCBrandGlobal.shared.selectorUploadAutoUpload]) {
  397. NSString *creationDate;
  398. NSString *idAsset;
  399. NSArray *idsAsset = [[NCManageDatabase shared] getPhotoLibraryIdAssetWithImage:account.autoUploadImage video:account.autoUploadVideo account:account.account];
  400. for (PHAsset *asset in assets) {
  401. (asset.creationDate != nil) ? (creationDate = [NSString stringWithFormat:@"%@", asset.creationDate]) : (creationDate = @"");
  402. idAsset = [NSString stringWithFormat:@"%@%@%@", account.account, asset.localIdentifier, creationDate];
  403. if (![idsAsset containsObject: idAsset])
  404. [newAssets addObject:asset];
  405. }
  406. return newAssets;
  407. } else {
  408. return (NSArray *)[assets copy];
  409. }
  410. }
  411. }
  412. return nil;
  413. }
  414. #pragma --------------------------------------------------------------------------------------------
  415. #pragma mark ===== Align Photo Library ====
  416. #pragma --------------------------------------------------------------------------------------------
  417. - (void)alignPhotoLibrary
  418. {
  419. tableAccount *account = [[NCManageDatabase shared] getAccountActive];
  420. NSArray *assets = [self getCameraRollAssets:account selector:NCBrandGlobal.shared.selectorUploadAutoUploadAll alignPhotoLibrary:YES];
  421. [[NCManageDatabase shared] clearTable:[tablePhotoLibrary class] account:appDelegate.account];
  422. if (assets != nil) {
  423. (void)[[NCManageDatabase shared] addPhotoLibrary:assets account:account.account];
  424. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Align Photo Library %lu", (unsigned long)[assets count]]];
  425. }
  426. }
  427. @end