CCPhotosCameraUpload.m 52 KB

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