CCAutoUpload.m 30 KB

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