CCPhotosCameraUpload.m 51 KB

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