CCPhotosCameraUpload.m 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. UIImage *imageButton = [UIImage imageNamed:image_activeCameraUpload];
  229. UIImage *image = [CCUtility drawText:NSLocalizedString(@"_activate_camera_upload_", nil) inImage:imageButton];
  230. return image;
  231. } else return nil;
  232. }
  233. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  234. {
  235. CCManageCameraUpload *viewController = [[CCManageCameraUpload alloc] initWithNibName:nil bundle:nil];
  236. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  237. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  238. [self presentViewController:navigationController animated:YES completion:nil];
  239. }
  240. #pragma --------------------------------------------------------------------------------------------
  241. #pragma mark ===== openSelectedFiles =====
  242. #pragma--------------------------------------------------------------------------------------------
  243. - (void)openSelectedFiles
  244. {
  245. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  246. for (CCMetadata *metadata in _selectedMetadatas) {
  247. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  248. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  249. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  250. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  251. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  252. [dataToShare addObject:data];
  253. }
  254. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  255. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  256. }
  257. }
  258. }
  259. if ([dataToShare count] > 0) {
  260. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  261. // iPad
  262. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  263. self.navigationItem.leftBarButtonItem.enabled = NO;
  264. self.navigationItem.rightBarButtonItem.enabled = NO;
  265. [self presentViewController:activityViewController animated:YES completion:^{
  266. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  267. self.navigationItem.leftBarButtonItem.enabled = YES;
  268. self.navigationItem.rightBarButtonItem.enabled = YES;
  269. if (completed) {
  270. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  271. if ([obj isKindOfClass:[UIImage class]])
  272. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  273. if ([obj isKindOfClass:[NSURL class]])
  274. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  275. }];
  276. [self performSelector:@selector(reloadCollection) withObject:nil];
  277. }
  278. }];
  279. }];
  280. }
  281. }
  282. #pragma --------------------------------------------------------------------------------------------
  283. #pragma mark ===== Download =====
  284. #pragma--------------------------------------------------------------------------------------------
  285. - (void)downloadFileFailure:(NSInteger)errorCode
  286. {
  287. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  288. }
  289. - (void)downloadFileSuccess:(CCMetadata *)metadata
  290. {
  291. NSIndexPath *indexPath;
  292. BOOL existsIcon = NO;
  293. if (metadata.fileID) {
  294. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  295. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  296. }
  297. if (indexPath && existsIcon) {
  298. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  299. if (cell) {
  300. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  301. UIVisualEffectView *effect = [cell viewWithTag:200];
  302. UIImageView *checked = [cell viewWithTag:300];
  303. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  304. effect.hidden = YES;
  305. checked.hidden = YES;
  306. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  307. }
  308. }
  309. }
  310. #pragma --------------------------------------------------------------------------------------------
  311. #pragma mark ===== Delete =====
  312. #pragma--------------------------------------------------------------------------------------------
  313. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  314. {
  315. [self deleteFileOrFolderSuccess:metadataNet];
  316. }
  317. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  318. {
  319. [_queueMetadatas removeObject:metadataNet.selector];
  320. if ([_queueMetadatas count] == 0) {
  321. [_hud hideHud];
  322. if ([_selectedMetadatas count] > 0) {
  323. [_selectedMetadatas removeObjectAtIndex:0];
  324. if ([_selectedMetadatas count] > 0) {
  325. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  326. } else {
  327. [self reloadDatasource];
  328. }
  329. } else {
  330. [self reloadDatasource];
  331. }
  332. }
  333. }
  334. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  335. {
  336. if (metadata.cryptated) {
  337. [_queueMetadatas addObject:selectorDeleteCrypto];
  338. [_queueMetadatas addObject:selectorDeletePlist];
  339. } else {
  340. [_queueMetadatas addObject:selectorDelete];
  341. }
  342. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  343. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  344. }
  345. - (void)deleteSelectedFiles
  346. {
  347. [_queueMetadatas removeAllObjects];
  348. _numSelectedMetadatas = [_selectedMetadatas count];
  349. if ([_selectedMetadatas count] == 0)
  350. return;
  351. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  352. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  353. style:UIAlertActionStyleDestructive
  354. handler:^(UIAlertAction *action) {
  355. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  356. }]];
  357. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  358. style:UIAlertActionStyleCancel
  359. handler:^(UIAlertAction *action) {
  360. [alertController dismissViewControllerAnimated:YES completion:nil];
  361. }]];
  362. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  363. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  364. [alertController.view layoutIfNeeded];
  365. [self presentViewController:alertController animated:YES completion:NULL];
  366. }
  367. #pragma --------------------------------------------------------------------------------------------
  368. #pragma mark ==== Download Thumbnail Delegate ====
  369. #pragma --------------------------------------------------------------------------------------------
  370. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  371. {
  372. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  373. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  374. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  375. }
  376. - (void)triggerProgressTask:(NSNotification *)notification
  377. {
  378. NSDictionary *dict = notification.userInfo;
  379. float progress = [[dict valueForKey:@"progress"] floatValue];
  380. if (progress == 0)
  381. [self.navigationController cancelCCProgress];
  382. else
  383. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:COLOR_NAVIGATIONBAR_PROGRESS];
  384. }
  385. #pragma --------------------------------------------------------------------------------------------
  386. #pragma mark ==== Collection ====
  387. #pragma --------------------------------------------------------------------------------------------
  388. - (void)reloadDatasourceForced
  389. {
  390. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  391. [self reloadDatasource];
  392. }
  393. - (void)reloadDatasource
  394. {
  395. // test
  396. if (app.activeAccount.length == 0)
  397. return;
  398. NSString *serverUrl = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  399. if (_sectionDataSource) {
  400. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  401. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  402. dispatch_async(dispatch_get_main_queue(), ^{
  403. [self reloadCollection];
  404. });
  405. });
  406. } else {
  407. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  408. [self reloadCollection];
  409. }
  410. }
  411. - (void)reloadCollection
  412. {
  413. [self.collectionView reloadData];
  414. [_selectedMetadatas removeAllObjects];
  415. [self collectionSelect:NO];
  416. }
  417. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  418. {
  419. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  420. }
  421. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  422. {
  423. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  424. }
  425. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  426. {
  427. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  428. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  429. return CGSizeMake(collectionView.frame.size.width / 5.3f, collectionView.frame.size.width / 5.3f);
  430. else
  431. return CGSizeMake(collectionView.frame.size.width / 7.3f, collectionView.frame.size.width / 7.3f);
  432. }
  433. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  434. {
  435. if ([_sectionDataSource.sections count] - 1 == section)
  436. return CGSizeMake(collectionView.frame.size.width, 50);
  437. return CGSizeZero;
  438. }
  439. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  440. {
  441. if (kind == UICollectionElementKindSectionHeader) {
  442. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  443. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  444. [self getGeoLocationForSection:indexPath.section];
  445. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  446. titleLabel.textColor = COLOR_TEXT_ANTHRACITE;
  447. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  448. return headerView;
  449. }
  450. if (kind == UICollectionElementKindSectionFooter) {
  451. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  452. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  453. titleLabel.textColor = [UIColor grayColor];
  454. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  455. return footerView;
  456. }
  457. return nil;
  458. }
  459. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  460. {
  461. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  462. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  463. UIVisualEffectView *effect = [cell viewWithTag:200];
  464. UIImageView *checked = [cell viewWithTag:300];
  465. checked.image = [UIImage imageNamed:image_checked];
  466. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  467. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  468. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  469. // Image
  470. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  471. imageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  472. if (imageView.image == nil) {
  473. // insert Image
  474. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  475. imageView.image = image;
  476. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  477. }
  478. } else {
  479. // Thumbnail not present
  480. imageView.image = [UIImage imageNamed:image_file_photo];
  481. if (metadata.thumbnailExists)
  482. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  483. }
  484. // Cheched
  485. if (cell.selected) {
  486. checked.hidden = NO;
  487. effect.hidden = NO;
  488. effect.alpha = 0.4;
  489. } else {
  490. checked.hidden = YES;
  491. effect.hidden = YES;
  492. }
  493. return cell;
  494. }
  495. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  496. {
  497. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  498. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  499. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  500. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  501. if (_cellEditing) {
  502. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  503. } else {
  504. if ([self shouldPerformSegue])
  505. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  506. }
  507. }
  508. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  509. {
  510. if (_cellEditing == NO)
  511. return;
  512. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  513. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  514. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  515. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  516. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  517. }
  518. #pragma --------------------------------------------------------------------------------------------
  519. #pragma mark ===== Navigation ====
  520. #pragma --------------------------------------------------------------------------------------------
  521. - (BOOL)shouldPerformSegue
  522. {
  523. // Test
  524. // Background ? exit
  525. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  526. return NO;
  527. // Not in first plain ? exit
  528. if (self.view.window == NO)
  529. return NO;
  530. // Collapsed but in first plain in detail exit
  531. if (self.splitViewController.isCollapsed)
  532. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  533. return NO;
  534. // Video running exit
  535. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  536. return NO;
  537. // ok perform segue
  538. return YES;
  539. }
  540. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  541. {
  542. id controller = segue.destinationViewController;
  543. if ([controller isKindOfClass:[UINavigationController class]]) {
  544. UINavigationController *navigationController = controller;
  545. self.detailViewController = (CCDetail *)navigationController.topViewController;
  546. } else {
  547. self.detailViewController = segue.destinationViewController;
  548. }
  549. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  550. for (NSString *fileID in _sectionDataSource.allFileID) {
  551. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  552. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  553. [allRecordsDataSourceImagesVideos addObject:metadata];
  554. }
  555. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  556. self.detailViewController.metadataDetail = _metadata;
  557. self.detailViewController.dateFilterQuery = _metadata.date;
  558. self.detailViewController.isCameraUpload = YES;
  559. [self.detailViewController setTitle:_metadata.fileNamePrint];
  560. }
  561. #pragma --------------------------------------------------------------------------------------------
  562. #pragma mark === initStateCameraUpload ===
  563. #pragma --------------------------------------------------------------------------------------------
  564. - (void)initStateCameraUpload:(NSNotification *)notification
  565. {
  566. int afterDelay = 0;
  567. if (notification.object)
  568. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  569. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  570. }
  571. - (void)initStateCameraUpload
  572. {
  573. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  574. [self setupCameraUpload];
  575. if([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount])
  576. [self checkIfLocationIsEnabled];
  577. } else {
  578. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  579. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  580. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  581. }
  582. }
  583. #pragma --------------------------------------------------------------------------------------------
  584. #pragma mark === Camera Upload & Full ===
  585. #pragma --------------------------------------------------------------------------------------------
  586. - (void)setupCameraUpload
  587. {
  588. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  589. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  590. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  591. [self uploadNewAssets];
  592. } else {
  593. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  594. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  595. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  596. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  597. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  598. delegate:nil
  599. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  600. otherButtonTitles:nil];
  601. [alert show];
  602. }
  603. }
  604. - (void)setupCameraUploadFull
  605. {
  606. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  607. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  608. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  609. [self uploadFullAssets];
  610. } else {
  611. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  612. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  613. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  614. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  615. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  616. delegate:nil
  617. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  618. otherButtonTitles:nil];
  619. [alert show];
  620. }
  621. }
  622. #pragma --------------------------------------------------------------------------------------------
  623. #pragma mark === Location ===
  624. #pragma --------------------------------------------------------------------------------------------
  625. - (BOOL)checkIfLocationIsEnabled
  626. {
  627. [CCManageLocation sharedSingleton].delegate = self;
  628. if ([CLLocationManager locationServicesEnabled]) {
  629. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  630. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  631. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  632. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  633. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  634. } else {
  635. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  636. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  637. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  638. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  639. delegate:nil
  640. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  641. otherButtonTitles:nil];
  642. [alert show];
  643. } else {
  644. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  645. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  646. delegate:nil
  647. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  648. otherButtonTitles:nil];
  649. [alert show];
  650. }
  651. }
  652. } else {
  653. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  654. [CCCoreData setCameraUploadBackground:YES activeAccount:app.activeAccount];
  655. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  656. } else {
  657. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  658. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  659. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  660. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  661. delegate:nil
  662. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  663. otherButtonTitles:nil];
  664. [alert show];
  665. }
  666. }
  667. } else {
  668. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  669. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  670. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  671. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  672. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  673. delegate:nil
  674. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  675. otherButtonTitles:nil];
  676. [alert show];
  677. } else {
  678. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  679. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  680. delegate:nil
  681. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  682. otherButtonTitles:nil];
  683. [alert show];
  684. }
  685. }
  686. return [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount];
  687. }
  688. - (void)statusAuthorizationLocationChanged
  689. {
  690. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  691. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  692. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  693. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  694. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  695. } failureBlock:^(NSError *error) {
  696. }];
  697. }
  698. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  699. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  700. if ([CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  701. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  702. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  703. }
  704. } else {
  705. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  706. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  707. delegate:nil
  708. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  709. otherButtonTitles:nil];
  710. [alert show];
  711. }
  712. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  713. if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  714. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  715. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  716. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  717. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  718. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  719. delegate:nil
  720. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  721. otherButtonTitles:nil];
  722. [alert show];
  723. } else {
  724. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  725. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  726. delegate:nil
  727. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  728. otherButtonTitles:nil];
  729. [alert show];
  730. }
  731. }
  732. }
  733. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  734. [CCManageLocation sharedSingleton].firstChangeAuthorizationDone = YES;
  735. }
  736. }
  737. }
  738. - (void)changedLocation
  739. {
  740. //Verifica
  741. [[CCNetworking sharedNetworking] automaticDownloadInError];
  742. [[CCNetworking sharedNetworking] automaticUploadInError];
  743. // solo in background
  744. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount] && [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount ] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  745. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  746. //check location
  747. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  748. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  749. [self uploadNewAssets];
  750. }
  751. } else {
  752. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  753. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  754. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  755. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  756. }
  757. }
  758. }
  759. #pragma --------------------------------------------------------------------------------------------
  760. #pragma mark ===== Upload Assets : NEW & FULL ====
  761. #pragma --------------------------------------------------------------------------------------------
  762. - (void)uploadNewAssets
  763. {
  764. [self uploadAssetsNewAndFull:NO];
  765. }
  766. - (void)uploadFullAssets
  767. {
  768. [self uploadAssetsNewAndFull:YES];
  769. }
  770. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  771. {
  772. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  773. NSMutableArray *newItemsToUpload;
  774. // CHECK : initStateCameraUpload
  775. if (_AutomaticCameraUploadInProgress)
  776. return;
  777. // Check Asset : NEW or FULL
  778. if (assetsFull) {
  779. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  780. } else {
  781. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  782. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  783. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  784. }
  785. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  786. if ([newItemsToUpload count] == 0)
  787. return;
  788. // STOP new request : initStateCameraUpload
  789. _AutomaticCameraUploadInProgress = YES;
  790. // Disable idle timer
  791. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  792. if (assetsFull) {
  793. if (!_hud)
  794. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  795. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  796. }
  797. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  798. if (assetsFull)
  799. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  800. else
  801. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  802. });
  803. }
  804. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  805. {
  806. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  807. }
  808. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  809. {
  810. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  811. }
  812. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  813. {
  814. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  815. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  816. BOOL useSubFolder = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  817. // Conversion from ALAsset -to-> PHAsset
  818. for (ALAsset *asset in newItemsToUpload) {
  819. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  820. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  821. PHAsset *asset = [fetchResult firstObject];
  822. [newItemsPHAssetToUpload addObject:asset];
  823. NSLog(@"Convert url %@", url);
  824. }
  825. // selectorUploadAutomaticAll : create the folder for Photos & if request the subfolders
  826. if (assetsFull) {
  827. if(![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutomaticAll]) {
  828. [self endLoadingAssets];
  829. return;
  830. }
  831. }
  832. for (PHAsset *asset in newItemsPHAssetToUpload) {
  833. NSString *serverUrl;
  834. NSDate *assetDate = asset.creationDate;
  835. PHAssetMediaType assetMediaType = asset.mediaType;
  836. NSString *session;
  837. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  838. // Select type of session
  839. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  840. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  841. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  842. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  843. NSDateFormatter *formatter = [NSDateFormatter new];
  844. [formatter setDateFormat:@"yyyy"];
  845. NSString *yearString = [formatter stringFromDate:assetDate];
  846. [formatter setDateFormat:@"MM"];
  847. NSString *monthString = [formatter stringFromDate:assetDate];
  848. if (useSubFolder)
  849. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  850. else
  851. serverUrl = folderPhotos;
  852. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  853. metadataNet.action = actionUploadAsset;
  854. metadataNet.identifier = asset.localIdentifier;
  855. if (assetsFull) {
  856. metadataNet.selector = selectorUploadAutomaticAll;
  857. metadataNet.selectorPost = selectorUploadRemovePhoto;
  858. metadataNet.priority = NSOperationQueuePriorityLow;
  859. } else {
  860. metadataNet.selector = selectorUploadAutomatic;
  861. metadataNet.selectorPost = nil;
  862. metadataNet.priority = NSOperationQueuePriorityNormal;
  863. }
  864. metadataNet.fileName = fileName;
  865. metadataNet.serverUrl = serverUrl;
  866. metadataNet.session = session;
  867. metadataNet.taskStatus = k_taskStatusResume;
  868. if (![CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount]) {
  869. [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];
  870. [self endLoadingAssets];
  871. return;
  872. }
  873. // Activity
  874. NSString *media = @"";
  875. if (assetMediaType == PHAssetMediaTypeImage) media = @"Image";
  876. if (assetMediaType == PHAssetMediaTypeVideo) media = @"Video";
  877. [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];
  878. // Upldate Camera Upload data
  879. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  880. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  881. }
  882. // start upload
  883. if (assetsFull)
  884. [app performSelectorOnMainThread:@selector(loadTableAutomaticUploadForSelector:) withObject:selectorUploadAutomaticAll waitUntilDone:NO];
  885. else
  886. [app performSelectorOnMainThread:@selector(loadTableAutomaticUploadForSelector:) withObject:selectorUploadAutomatic waitUntilDone:NO];
  887. // end loading
  888. [self endLoadingAssets];
  889. // Update icon badge number
  890. [app updateApplicationIconBadgeNumber];
  891. }
  892. -(void)endLoadingAssets
  893. {
  894. [_hud hideHud];
  895. // START new request : initStateCameraUpload
  896. _AutomaticCameraUploadInProgress = NO;
  897. // Enable idle timer
  898. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  899. }
  900. @end