CCPhotos.m 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. //
  2. // CCPhotos.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  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 "CCPhotos.h"
  24. #import "AppDelegate.h"
  25. #import "NCBridgeSwift.h"
  26. @interface CCPhotos () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  27. {
  28. tableMetadata *_metadata;
  29. BOOL _cellEditing;
  30. NSMutableArray *_queueMetadatas;
  31. NSMutableArray *_selectedMetadatas;
  32. NSUInteger _numSelectedMetadatas;
  33. CCSectionDataSourceMetadata *_sectionDataSource;
  34. CCHud *_hud;
  35. }
  36. @end
  37. @implementation CCPhotos
  38. #pragma --------------------------------------------------------------------------------------------
  39. #pragma mark ===== Init =====
  40. #pragma --------------------------------------------------------------------------------------------
  41. - (id)initWithCoder:(NSCoder *)aDecoder
  42. {
  43. if (self = [super initWithCoder:aDecoder]) {
  44. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initStateAutoUpload:) name:@"initStateAutoUpload" object:nil];
  45. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupAutoUploadFull) name:@"setupAutoUploadFull" object:nil];
  46. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  47. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  48. app.activePhotos = self;
  49. }
  50. return self;
  51. }
  52. #pragma --------------------------------------------------------------------------------------------
  53. #pragma mark ===== View =====
  54. #pragma --------------------------------------------------------------------------------------------
  55. - (void)viewDidLoad
  56. {
  57. [super viewDidLoad];
  58. _queueMetadatas = [[NSMutableArray alloc] init];
  59. _selectedMetadatas = [[NSMutableArray alloc] init];
  60. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  61. // empty Data Source
  62. self.collectionView.emptyDataSetDelegate = self;
  63. self.collectionView.emptyDataSetSource = self;
  64. [self reloadDatasource];
  65. }
  66. // Apparirà
  67. - (void)viewWillAppear:(BOOL)animated
  68. {
  69. [super viewWillAppear:animated];
  70. // Color
  71. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  72. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  73. // Plus Button
  74. [app plusButtonVisibile:true];
  75. }
  76. // E' arrivato
  77. - (void)viewDidAppear:(BOOL)animated
  78. {
  79. [super viewDidAppear:animated];
  80. [self reloadDatasource];
  81. }
  82. - (void)changeTheming
  83. {
  84. if (self.isViewLoaded && self.view.window)
  85. [app changeTheming:self];
  86. [self.collectionView reloadData];
  87. }
  88. #pragma --------------------------------------------------------------------------------------------
  89. #pragma mark ===== Gestione Grafica Window =====
  90. #pragma --------------------------------------------------------------------------------------------
  91. - (void)setUINavigationBarDefault
  92. {
  93. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  94. // select
  95. UIImage *icon = [UIImage imageNamed:@"seleziona"];
  96. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  97. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  98. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  99. } else {
  100. self.navigationItem.rightBarButtonItems = nil;
  101. }
  102. self.navigationItem.leftBarButtonItem = nil;
  103. // Title
  104. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  105. }
  106. - (void)setUINavigationBarSelected
  107. {
  108. UIImage *icon;
  109. icon = [UIImage imageNamed:@"deleteSelectedFiles"];
  110. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  111. icon = [UIImage imageNamed:@"openSelectedFiles"];
  112. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  113. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  114. self.navigationItem.leftBarButtonItem = leftButton;
  115. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  116. // Title
  117. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  118. }
  119. - (void)collectionSelect:(BOOL)edit
  120. {
  121. [self.collectionView setAllowsMultipleSelection:edit];
  122. _cellEditing = edit;
  123. if (edit)
  124. [self setUINavigationBarSelected];
  125. else
  126. [self setUINavigationBarDefault];
  127. }
  128. - (void)collectionSelectYES
  129. {
  130. [self collectionSelect:YES];
  131. }
  132. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(tableMetadata *)metadata
  133. {
  134. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  135. UIVisualEffectView *effect = [cell viewWithTag:200];
  136. UIImageView *checked = [cell viewWithTag:300];
  137. if (select) {
  138. effect.hidden = NO;
  139. effect.alpha = 0.4;
  140. checked.hidden = NO;
  141. [_selectedMetadatas addObject:metadata];
  142. } else {
  143. effect.hidden = YES;
  144. checked.hidden = YES;
  145. [_selectedMetadatas removeObject:metadata];
  146. }
  147. // Title
  148. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  149. }
  150. - (void)scrollToTop
  151. {
  152. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  153. }
  154. - (void)getGeoLocationForSection:(NSInteger)section
  155. {
  156. NSString *addLocation = @"";
  157. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  158. for (NSString *fileID in fileIDsForKey) {
  159. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  160. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  161. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  162. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  163. }
  164. }
  165. }
  166. #pragma --------------------------------------------------------------------------------------------
  167. #pragma mark ==== Photo Library Change Observer ====
  168. #pragma --------------------------------------------------------------------------------------------
  169. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  170. {
  171. /*
  172. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  173. if (collectionChanges) {
  174. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  175. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  176. [self uploadNewAssets];
  177. });
  178. }
  179. */
  180. }
  181. #pragma --------------------------------------------------------------------------------------------
  182. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  183. #pragma --------------------------------------------------------------------------------------------
  184. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  185. {
  186. return [UIColor whiteColor];
  187. }
  188. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  189. {
  190. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"photosNoRecord"] color:[NCBrandColor sharedInstance].brand];
  191. }
  192. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  193. {
  194. NSString *text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  195. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  196. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  197. }
  198. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  199. {
  200. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  201. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  202. paragraph.alignment = NSTextAlignmentCenter;
  203. NSString *text;
  204. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  205. if (account.autoUpload)
  206. text = [NSString stringWithFormat:@"%@", @"\n\n\n\n"];
  207. else
  208. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_autoupload_view_", nil)];
  209. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  210. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  211. }
  212. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  213. {
  214. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  215. if (!account.autoUpload) {
  216. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"button"] color:[NCBrandColor sharedInstance].brand];
  217. return [CCUtility drawText:NSLocalizedString(@"_activate_autoupload_", nil) inImage:buttonImage colorText:[UIColor whiteColor]];
  218. } else return nil;
  219. }
  220. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  221. {
  222. CCManageAutoUpload *viewController = [[CCManageAutoUpload alloc] initWithNibName:nil bundle:nil];
  223. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  224. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  225. [self presentViewController:navigationController animated:YES completion:nil];
  226. }
  227. #pragma --------------------------------------------------------------------------------------------
  228. #pragma mark ===== openSelectedFiles =====
  229. #pragma--------------------------------------------------------------------------------------------
  230. - (void)openSelectedFiles
  231. {
  232. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  233. for (tableMetadata *metadata in _selectedMetadatas) {
  234. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  235. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  236. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  237. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  238. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  239. [dataToShare addObject:data];
  240. }
  241. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  242. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  243. }
  244. }
  245. }
  246. if ([dataToShare count] > 0) {
  247. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  248. // iPad
  249. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  250. self.navigationItem.leftBarButtonItem.enabled = NO;
  251. self.navigationItem.rightBarButtonItem.enabled = NO;
  252. [self presentViewController:activityViewController animated:YES completion:^{
  253. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  254. self.navigationItem.leftBarButtonItem.enabled = YES;
  255. self.navigationItem.rightBarButtonItem.enabled = YES;
  256. if (completed) {
  257. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  258. if ([obj isKindOfClass:[UIImage class]])
  259. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  260. if ([obj isKindOfClass:[NSURL class]])
  261. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  262. }];
  263. [self performSelector:@selector(reloadCollection) withObject:nil];
  264. }
  265. }];
  266. }];
  267. }
  268. }
  269. #pragma --------------------------------------------------------------------------------------------
  270. #pragma mark ===== Download =====
  271. #pragma--------------------------------------------------------------------------------------------
  272. - (void)downloadFileFailure:(NSInteger)errorCode
  273. {
  274. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  275. }
  276. - (void)downloadFileSuccess:(tableMetadata *)metadata
  277. {
  278. NSIndexPath *indexPath;
  279. BOOL existsIcon = NO;
  280. if (metadata.fileID) {
  281. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  282. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  283. }
  284. if (indexPath && existsIcon) {
  285. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  286. if (cell) {
  287. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  288. UIVisualEffectView *effect = [cell viewWithTag:200];
  289. UIImageView *checked = [cell viewWithTag:300];
  290. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  291. effect.hidden = YES;
  292. checked.hidden = YES;
  293. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  294. }
  295. }
  296. }
  297. #pragma --------------------------------------------------------------------------------------------
  298. #pragma mark ===== Delete =====
  299. #pragma--------------------------------------------------------------------------------------------
  300. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  301. {
  302. [self deleteFileOrFolderSuccess:metadataNet];
  303. }
  304. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  305. {
  306. [_queueMetadatas removeObject:metadataNet.selector];
  307. if ([_queueMetadatas count] == 0) {
  308. [_hud hideHud];
  309. if ([_selectedMetadatas count] > 0) {
  310. [_selectedMetadatas removeObjectAtIndex:0];
  311. if ([_selectedMetadatas count] > 0) {
  312. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  313. } else {
  314. [self reloadDatasource];
  315. }
  316. } else {
  317. [self reloadDatasource];
  318. }
  319. }
  320. }
  321. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  322. {
  323. if (metadata.cryptated) {
  324. [_queueMetadatas addObject:selectorDeleteCrypto];
  325. [_queueMetadatas addObject:selectorDeletePlist];
  326. } else {
  327. [_queueMetadatas addObject:selectorDelete];
  328. }
  329. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  330. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  331. }
  332. - (void)deleteSelectedFiles
  333. {
  334. [_queueMetadatas removeAllObjects];
  335. _numSelectedMetadatas = [_selectedMetadatas count];
  336. if ([_selectedMetadatas count] == 0)
  337. return;
  338. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  339. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  340. style:UIAlertActionStyleDestructive
  341. handler:^(UIAlertAction *action) {
  342. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  343. }]];
  344. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  345. style:UIAlertActionStyleCancel
  346. handler:^(UIAlertAction *action) {
  347. [alertController dismissViewControllerAnimated:YES completion:nil];
  348. }]];
  349. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  350. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  351. [alertController.view layoutIfNeeded];
  352. [self presentViewController:alertController animated:YES completion:NULL];
  353. }
  354. #pragma --------------------------------------------------------------------------------------------
  355. #pragma mark ==== Download Thumbnail Delegate ====
  356. #pragma --------------------------------------------------------------------------------------------
  357. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  358. {
  359. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  360. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  361. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  362. }
  363. - (void)triggerProgressTask:(NSNotification *)notification
  364. {
  365. NSDictionary *dict = notification.userInfo;
  366. float progress = [[dict valueForKey:@"progress"] floatValue];
  367. if (progress == 0)
  368. [self.navigationController cancelCCProgress];
  369. else
  370. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:[NCBrandColor sharedInstance].navigationBarProgress];
  371. }
  372. #pragma --------------------------------------------------------------------------------------------
  373. #pragma mark ==== Collection ====
  374. #pragma --------------------------------------------------------------------------------------------
  375. - (void)reloadDatasourceForced
  376. {
  377. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  378. [self reloadDatasource];
  379. }
  380. - (void)reloadDatasource
  381. {
  382. // test
  383. if (app.activeAccount.length == 0)
  384. return;
  385. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  386. if (_sectionDataSource) {
  387. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  388. NSArray *metadatas = [[NCManageDatabase sharedInstance] getTableMetadatasPhotosWithServerUrl:autoUploadPath];
  389. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  390. dispatch_async(dispatch_get_main_queue(), ^{
  391. [self reloadCollection];
  392. });
  393. });
  394. } else {
  395. NSArray *results = [[NCManageDatabase sharedInstance] getTableMetadatasPhotosWithServerUrl:autoUploadPath];
  396. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:results listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  397. [self reloadCollection];
  398. }
  399. }
  400. - (void)reloadCollection
  401. {
  402. [self.collectionView reloadData];
  403. [_selectedMetadatas removeAllObjects];
  404. [self collectionSelect:NO];
  405. }
  406. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  407. {
  408. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  409. }
  410. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  411. {
  412. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  413. }
  414. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  415. {
  416. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  417. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  418. return CGSizeMake(collectionView.frame.size.width / 5.3f, collectionView.frame.size.width / 5.3f);
  419. else
  420. return CGSizeMake(collectionView.frame.size.width / 7.3f, collectionView.frame.size.width / 7.3f);
  421. }
  422. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  423. {
  424. if ([_sectionDataSource.sections count] - 1 == section)
  425. return CGSizeMake(collectionView.frame.size.width, 50);
  426. return CGSizeZero;
  427. }
  428. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  429. {
  430. if (kind == UICollectionElementKindSectionHeader) {
  431. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  432. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  433. [self getGeoLocationForSection:indexPath.section];
  434. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  435. titleLabel.textColor = [UIColor blackColor];
  436. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  437. return headerView;
  438. }
  439. if (kind == UICollectionElementKindSectionFooter) {
  440. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  441. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  442. titleLabel.textColor = [UIColor grayColor];
  443. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  444. return footerView;
  445. }
  446. return nil;
  447. }
  448. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  449. {
  450. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  451. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  452. UIVisualEffectView *effect = [cell viewWithTag:200];
  453. UIImageView *checked = [cell viewWithTag:300];
  454. checked.image = [UIImage imageNamed:@"checked"];
  455. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  456. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  457. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  458. // Image
  459. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  460. imageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  461. if (imageView.image == nil) {
  462. // insert Image
  463. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  464. imageView.image = image;
  465. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  466. }
  467. } else {
  468. // Thumbnail not present
  469. imageView.image = [UIImage imageNamed:@"file_photo"];
  470. if (metadata.thumbnailExists)
  471. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  472. }
  473. // Cheched
  474. if (cell.selected) {
  475. checked.hidden = NO;
  476. effect.hidden = NO;
  477. effect.alpha = 0.4;
  478. } else {
  479. checked.hidden = YES;
  480. effect.hidden = YES;
  481. }
  482. return cell;
  483. }
  484. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  485. {
  486. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  487. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  488. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  489. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  490. if (_cellEditing) {
  491. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  492. } else {
  493. if ([self shouldPerformSegue])
  494. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  495. }
  496. }
  497. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  498. {
  499. if (_cellEditing == NO)
  500. return;
  501. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  502. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  503. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  504. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  505. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  506. }
  507. #pragma --------------------------------------------------------------------------------------------
  508. #pragma mark ===== Navigation ====
  509. #pragma --------------------------------------------------------------------------------------------
  510. - (BOOL)shouldPerformSegue
  511. {
  512. // Test
  513. // Background ? exit
  514. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  515. return NO;
  516. // Not in first plain ? exit
  517. if (self.view.window == NO)
  518. return NO;
  519. // Collapsed but in first plain in detail exit
  520. if (self.splitViewController.isCollapsed)
  521. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  522. return NO;
  523. // Video running exit
  524. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  525. return NO;
  526. // ok perform segue
  527. return YES;
  528. }
  529. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  530. {
  531. id controller = segue.destinationViewController;
  532. if ([controller isKindOfClass:[UINavigationController class]]) {
  533. UINavigationController *navigationController = controller;
  534. self.detailViewController = (CCDetail *)navigationController.topViewController;
  535. } else {
  536. self.detailViewController = segue.destinationViewController;
  537. }
  538. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  539. for (NSString *fileID in _sectionDataSource.allEtag) {
  540. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  541. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  542. [allRecordsDataSourceImagesVideos addObject:metadata];
  543. }
  544. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  545. self.detailViewController.metadataDetail = _metadata;
  546. self.detailViewController.dateFilterQuery = _metadata.date;
  547. [self.detailViewController setTitle:_metadata.fileNamePrint];
  548. }
  549. #pragma --------------------------------------------------------------------------------------------
  550. #pragma mark === initStateAutoUpload ===
  551. #pragma --------------------------------------------------------------------------------------------
  552. - (void)initStateAutoUpload:(NSNotification *)notification
  553. {
  554. int afterDelay = 0;
  555. if (notification.object)
  556. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  557. [self performSelector:@selector(initStateAutoUpload) withObject:nil afterDelay:afterDelay];
  558. }
  559. - (void)initStateAutoUpload
  560. {
  561. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  562. if (tableAccount.autoUpload) {
  563. [self setupAutoUpload];
  564. if (tableAccount.autoUploadBackground)
  565. [self checkIfLocationIsEnabled];
  566. } else {
  567. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  568. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  569. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  570. }
  571. }
  572. #pragma --------------------------------------------------------------------------------------------
  573. #pragma mark === Camera Upload & Full ===
  574. #pragma --------------------------------------------------------------------------------------------
  575. - (void)setupAutoUpload
  576. {
  577. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  578. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  579. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  580. [self uploadNewAssets];
  581. } else {
  582. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  583. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  584. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  585. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  586. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  587. delegate:nil
  588. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  589. otherButtonTitles:nil];
  590. [alert show];
  591. }
  592. }
  593. - (void)setupAutoUploadFull
  594. {
  595. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  596. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  597. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  598. [self uploadFullAssets];
  599. } else {
  600. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  601. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  602. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  603. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  604. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  605. delegate:nil
  606. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  607. otherButtonTitles:nil];
  608. [alert show];
  609. }
  610. }
  611. #pragma --------------------------------------------------------------------------------------------
  612. #pragma mark === Location ===
  613. #pragma --------------------------------------------------------------------------------------------
  614. - (BOOL)checkIfLocationIsEnabled
  615. {
  616. [CCManageLocation sharedInstance].delegate = self;
  617. if ([CLLocationManager locationServicesEnabled]) {
  618. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  619. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  620. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  621. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  622. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  623. } else {
  624. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  625. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  626. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  627. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  628. delegate:nil
  629. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  630. otherButtonTitles:nil];
  631. [alert show];
  632. } else {
  633. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  634. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  635. delegate:nil
  636. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  637. otherButtonTitles:nil];
  638. [alert show];
  639. }
  640. }
  641. } else {
  642. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  643. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:YES];
  644. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  645. } else {
  646. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  647. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  648. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  649. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  650. delegate:nil
  651. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  652. otherButtonTitles:nil];
  653. [alert show];
  654. }
  655. }
  656. } else {
  657. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  658. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  659. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  660. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  661. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  662. delegate:nil
  663. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  664. otherButtonTitles:nil];
  665. [alert show];
  666. } else {
  667. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  668. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  669. delegate:nil
  670. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  671. otherButtonTitles:nil];
  672. [alert show];
  673. }
  674. }
  675. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  676. return tableAccount.autoUploadBackground;
  677. }
  678. - (void)statusAuthorizationLocationChanged
  679. {
  680. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  681. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  682. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  683. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  684. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  685. } failureBlock:^(NSError *error) {
  686. }];
  687. }
  688. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  689. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  690. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  691. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  692. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  693. }
  694. } else {
  695. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  696. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  697. delegate:nil
  698. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  699. otherButtonTitles:nil];
  700. [alert show];
  701. }
  702. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  703. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  704. if (tableAccount.autoUploadBackground) {
  705. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  706. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  707. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  708. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  709. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  710. delegate:nil
  711. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  712. otherButtonTitles:nil];
  713. [alert show];
  714. } else {
  715. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  716. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  717. delegate:nil
  718. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  719. otherButtonTitles:nil];
  720. [alert show];
  721. }
  722. }
  723. }
  724. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  725. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  726. }
  727. }
  728. }
  729. - (void)changedLocation
  730. {
  731. // Only in background
  732. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  733. if (tableAccount.autoUpload && tableAccount.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  734. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  735. //check location
  736. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  737. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  738. [self uploadNewAssets];
  739. }
  740. } else {
  741. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
  742. [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
  743. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  744. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  745. }
  746. }
  747. }
  748. #pragma --------------------------------------------------------------------------------------------
  749. #pragma mark ===== Upload Assets : NEW & FULL ====
  750. #pragma --------------------------------------------------------------------------------------------
  751. - (void)uploadNewAssets
  752. {
  753. [self uploadAssetsNewAndFull:NO];
  754. }
  755. - (void)uploadFullAssets
  756. {
  757. [self uploadAssetsNewAndFull:YES];
  758. }
  759. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  760. {
  761. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  762. NSMutableArray *newItemsToUpload;
  763. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  764. // Check Asset : NEW or FULL
  765. if (assetsFull) {
  766. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  767. } else {
  768. NSDate *databaseDatePhoto = tableAccount.autoUploadDatePhoto;
  769. NSDate *databaseDateVideo = tableAccount.autoUploadDateVideo;
  770. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  771. }
  772. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  773. if ([newItemsToUpload count] == 0)
  774. return;
  775. // Disable idle timer
  776. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  777. if (assetsFull) {
  778. if (!_hud)
  779. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  780. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  781. }
  782. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  783. if (assetsFull)
  784. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  785. else
  786. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  787. });
  788. }
  789. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  790. {
  791. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  792. }
  793. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  794. {
  795. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  796. }
  797. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  798. {
  799. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  800. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  801. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  802. BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
  803. // Conversion from ALAsset -to-> PHAsset
  804. for (ALAsset *asset in newItemsToUpload) {
  805. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  806. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  807. PHAsset *asset = [fetchResult firstObject];
  808. [newItemsPHAssetToUpload addObject:asset];
  809. NSLog(@"Convert url %@", url);
  810. }
  811. // Create the folder for Photos & if request the subfolders
  812. if(![app createFolderSubFolderAutomaticUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutomaticAll]) {
  813. // end loading
  814. [_hud hideHud];
  815. // Enable idle timer
  816. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  817. return;
  818. }
  819. for (PHAsset *asset in newItemsPHAssetToUpload) {
  820. NSString *serverUrl;
  821. NSDate *assetDate = asset.creationDate;
  822. PHAssetMediaType assetMediaType = asset.mediaType;
  823. NSString *session;
  824. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  825. // Select type of session
  826. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
  827. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
  828. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
  829. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
  830. NSDateFormatter *formatter = [NSDateFormatter new];
  831. [formatter setDateFormat:@"yyyy"];
  832. NSString *yearString = [formatter stringFromDate:assetDate];
  833. [formatter setDateFormat:@"MM"];
  834. NSString *monthString = [formatter stringFromDate:assetDate];
  835. if (useSubFolder)
  836. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  837. else
  838. serverUrl = autoUploadPath;
  839. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  840. metadataNet.action = actionUploadAsset;
  841. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  842. if (assetsFull) {
  843. metadataNet.selector = selectorUploadAutomaticAll;
  844. metadataNet.selectorPost = selectorUploadRemovePhoto;
  845. metadataNet.priority = NSOperationQueuePriorityLow;
  846. } else {
  847. metadataNet.selector = selectorUploadAutomatic;
  848. metadataNet.selectorPost = nil;
  849. metadataNet.priority = NSOperationQueuePriorityNormal;
  850. }
  851. metadataNet.fileName = fileName;
  852. metadataNet.serverUrl = serverUrl;
  853. metadataNet.session = session;
  854. metadataNet.taskStatus = k_taskStatusResume;
  855. if (assetsFull)
  856. [self addDatabaseAutomaticUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  857. else
  858. [self writeAssetToSandbox:metadataNet];
  859. }
  860. // end loading
  861. [_hud hideHud];
  862. // Enable idle timer
  863. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  864. }
  865. - (void)writeAssetToSandbox:(CCMetadataNet *)metadataNet
  866. {
  867. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  868. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  869. PHAsset *asset = result[0];
  870. PHAssetMediaType assetMediaType = asset.mediaType;
  871. NSDate *assetDate = asset.creationDate;
  872. __block NSError *error = nil;
  873. // VIDEO
  874. if (assetMediaType == PHAssetMediaTypeVideo) {
  875. @autoreleasepool {
  876. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  877. options.networkAccessAllowed = true;
  878. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  879. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]])
  880. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] error:nil];
  881. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  882. if (exportSession) {
  883. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]];
  884. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  885. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  886. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  887. [self addDatabaseAutomaticUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  888. } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
  889. [[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];
  890. } else {
  891. NSLog(@"Export Session Status: %ld", (long)exportSession.status);
  892. }
  893. }];
  894. } else {
  895. [[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];
  896. }
  897. }];
  898. }
  899. }
  900. // IMAGE
  901. if (assetMediaType == PHAssetMediaTypeImage) {
  902. @autoreleasepool {
  903. PHImageRequestOptions *options = [PHImageRequestOptions new];
  904. options.synchronous = NO;
  905. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  906. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  907. if (error) {
  908. NSString *note = [NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description];
  909. [[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];
  910. [[NCManageDatabase sharedInstance] deleteAutomaticUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
  911. } else {
  912. [self addDatabaseAutomaticUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  913. }
  914. }];
  915. }
  916. }
  917. }
  918. - (void)addDatabaseAutomaticUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
  919. {
  920. if ([[NCManageDatabase sharedInstance] addAutomaticUploadWithMetadataNet:metadataNet]) {
  921. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutomaticUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Automatic Upload, Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  922. } else {
  923. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutomaticUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Automatic Upload [File already present in Table automatic Upload], Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  924. }
  925. dispatch_async(dispatch_get_main_queue(), ^{
  926. // Update Camera Upload data
  927. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  928. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:assetDate];
  929. // Update icon badge number
  930. [app updateApplicationIconBadgeNumber];
  931. });
  932. }
  933. @end