CCPhotosCameraUpload.m 53 KB

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