NCAutoUpload.m 30 KB

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