CCPhotosCameraUpload.m 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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.sourceDirectory = sorceDirectoryAccount;
  571. [self.detailViewController setTitle:_metadata.fileNamePrint];
  572. }
  573. #pragma --------------------------------------------------------------------------------------------
  574. #pragma mark ====== --- Camera Upload --- ======
  575. #pragma --------------------------------------------------------------------------------------------
  576. #pragma --------------------------------------------------------------------------------------------
  577. #pragma mark === initStateCameraUpload ===
  578. #pragma --------------------------------------------------------------------------------------------
  579. - (void)initStateCameraUpload:(NSNotification *)notification
  580. {
  581. int afterDelay = 0;
  582. if (notification.object)
  583. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  584. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  585. }
  586. - (void)initStateCameraUpload
  587. {
  588. if (_AutomaticCameraUploadInProgress)
  589. return;
  590. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  591. [self setupCameraUpload];
  592. if([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount])
  593. [self checkIfLocationIsEnabled];
  594. } else {
  595. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  596. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  597. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  598. }
  599. }
  600. #pragma --------------------------------------------------------------------------------------------
  601. #pragma mark === Camera Upload & Full ===
  602. #pragma --------------------------------------------------------------------------------------------
  603. - (void)setupCameraUpload
  604. {
  605. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  606. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  607. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  608. [self uploadNewAssets];
  609. } else {
  610. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  611. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  612. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  613. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  614. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  615. delegate:nil
  616. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  617. otherButtonTitles:nil];
  618. [alert show];
  619. }
  620. }
  621. - (void)setupCameraUploadFull
  622. {
  623. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  624. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  625. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  626. [self uploadFullAssets];
  627. } else {
  628. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  629. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  630. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  631. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  632. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  633. delegate:nil
  634. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  635. otherButtonTitles:nil];
  636. [alert show];
  637. }
  638. }
  639. #pragma --------------------------------------------------------------------------------------------
  640. #pragma mark === Location ===
  641. #pragma --------------------------------------------------------------------------------------------
  642. - (BOOL)checkIfLocationIsEnabled
  643. {
  644. [CCManageLocation sharedSingleton].delegate = self;
  645. if ([CLLocationManager locationServicesEnabled]) {
  646. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  647. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  648. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  649. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  650. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  651. } else {
  652. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  653. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  654. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  655. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  656. delegate:nil
  657. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  658. otherButtonTitles:nil];
  659. [alert show];
  660. } else {
  661. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  662. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  663. delegate:nil
  664. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  665. otherButtonTitles:nil];
  666. [alert show];
  667. }
  668. }
  669. } else {
  670. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  671. [CCCoreData setCameraUploadBackground:YES activeAccount:app.activeAccount];
  672. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  673. } else {
  674. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  675. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  676. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  677. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  678. delegate:nil
  679. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  680. otherButtonTitles:nil];
  681. [alert show];
  682. }
  683. }
  684. } else {
  685. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  686. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  687. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  688. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  689. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  690. delegate:nil
  691. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  692. otherButtonTitles:nil];
  693. [alert show];
  694. } else {
  695. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  696. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  697. delegate:nil
  698. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  699. otherButtonTitles:nil];
  700. [alert show];
  701. }
  702. }
  703. return [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount];
  704. }
  705. - (void)statusAuthorizationLocationChanged
  706. {
  707. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  708. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  709. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  710. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  711. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  712. } failureBlock:^(NSError *error) {
  713. }];
  714. }
  715. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  716. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  717. if ([CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  718. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  719. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  720. }
  721. } else {
  722. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  723. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  724. delegate:nil
  725. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  726. otherButtonTitles:nil];
  727. [alert show];
  728. }
  729. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  730. if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  731. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  732. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  733. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  734. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  735. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  736. delegate:nil
  737. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  738. otherButtonTitles:nil];
  739. [alert show];
  740. } else {
  741. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  742. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  743. delegate:nil
  744. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  745. otherButtonTitles:nil];
  746. [alert show];
  747. }
  748. }
  749. }
  750. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  751. [CCManageLocation sharedSingleton].firstChangeAuthorizationDone = YES;
  752. }
  753. }
  754. }
  755. - (void)changedLocation
  756. {
  757. //Verifica
  758. [[CCNetworking sharedNetworking] automaticDownloadInError];
  759. [[CCNetworking sharedNetworking] automaticUploadInError];
  760. // solo in background
  761. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount] && [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount ] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  762. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  763. //check location
  764. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  765. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  766. [self uploadNewAssets];
  767. }
  768. } else {
  769. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  770. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  771. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  772. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  773. }
  774. }
  775. }
  776. #pragma --------------------------------------------------------------------------------------------
  777. #pragma mark ===== Upload Assets : NEW & FULL ====
  778. #pragma --------------------------------------------------------------------------------------------
  779. - (void)uploadNewAssets
  780. {
  781. [self uploadAssetsNewAndFull:NO];
  782. }
  783. - (void)uploadFullAssets
  784. {
  785. [self uploadAssetsNewAndFull:YES];
  786. }
  787. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  788. {
  789. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  790. NSMutableArray *newItemsToUpload;
  791. // Check Asset : NEW or FULL
  792. if (assetsFull) {
  793. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  794. } else {
  795. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  796. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  797. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  798. }
  799. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  800. if ([newItemsToUpload count] == 0)
  801. return;
  802. // STOP new request : initStateCameraUpload
  803. _AutomaticCameraUploadInProgress = YES;
  804. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  805. // verify/create folder Camera Upload, if error exit
  806. if(![self createFolder:folderPhotos]) {
  807. // Full Upload ?
  808. if (assetsFull)
  809. [app messageNotification:@"_error_" description:NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil) visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  810. // START new request : initStateCameraUpload
  811. _AutomaticCameraUploadInProgress = NO;
  812. return;
  813. }
  814. // Disable idle timer
  815. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  816. if (!_hud) _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  817. if (assetsFull)
  818. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  819. else
  820. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  821. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  822. if (assetsFull)
  823. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  824. else
  825. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  826. });
  827. }
  828. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  829. {
  830. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  831. }
  832. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  833. {
  834. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  835. }
  836. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  837. {
  838. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  839. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  840. BOOL createSubfolders = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  841. // Conversion from ALAsset -to-> PHAsset
  842. for (ALAsset *asset in newItemsToUpload) {
  843. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  844. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  845. PHAsset *asset = [fetchResult firstObject];
  846. [newItemsPHAssetToUpload addObject:asset];
  847. }
  848. // Use subfolders
  849. if (createSubfolders) {
  850. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:newItemsPHAssetToUpload]) {
  851. if (![self createFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  852. [self endLoadingAssets];
  853. if (assetsFull)
  854. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  855. return;
  856. }
  857. }
  858. }
  859. for (PHAsset *asset in newItemsPHAssetToUpload) {
  860. NSString *serverUrl;
  861. NSDate *assetDate = asset.creationDate;
  862. PHAssetMediaType assetMediaType = asset.mediaType;
  863. NSString *session;
  864. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  865. // Select type of session
  866. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = upload_session;
  867. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = upload_session;
  868. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = upload_session_wwan;
  869. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = upload_session_wwan;
  870. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  871. [formatter setDateFormat:@"yyyy"];
  872. NSString *yearString = [formatter stringFromDate:assetDate];
  873. [formatter setDateFormat:@"MM"];
  874. NSString *monthString = [formatter stringFromDate:assetDate];
  875. if (createSubfolders)
  876. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  877. else
  878. serverUrl = folderPhotos;
  879. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  880. metadataNet.action = actionUploadAsset;
  881. metadataNet.identifier = asset.localIdentifier;
  882. if (assetsFull) {
  883. metadataNet.selector = selectorUploadAutomaticAll;
  884. metadataNet.selectorPost = selectorUploadRemovePhoto;
  885. metadataNet.priority = NSOperationQueuePriorityLow;
  886. } else {
  887. metadataNet.selector = selectorUploadAutomatic;
  888. metadataNet.selectorPost = nil;
  889. metadataNet.priority = NSOperationQueuePriorityHigh;
  890. }
  891. metadataNet.fileName = fileName;
  892. metadataNet.serverUrl = serverUrl;
  893. metadataNet.session = session;
  894. metadataNet.taskStatus = taskStatusResume;
  895. [CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount context:nil];
  896. // Upldate Camera Upload data
  897. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  898. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  899. }
  900. // start upload
  901. if (assetsFull)
  902. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  903. else
  904. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  905. // end loading
  906. [self endLoadingAssets];
  907. // Update icon badge number
  908. [app updateApplicationIconBadgeNumber];
  909. }
  910. - (BOOL)createFolder:(NSString *)folderPathName
  911. {
  912. OCnetworking *ocNet;
  913. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  914. NSError *error;
  915. ocNet = [[OCnetworking alloc] initWithDelegate:self metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl withTypeCloud:app.typeCloud activityIndicator:NO];
  916. error = [ocNet readFileSync:folderPathName];
  917. if(!error)
  918. return YES;
  919. error = [ocNet createFolderSync:folderPathName];
  920. if (!error) {
  921. [CCCoreData clearDateReadDirectory:[CCUtility deletingLastPathComponentFromServerUrl:folderPathName] activeAccount:app.activeAccount];
  922. return YES;
  923. }
  924. }
  925. return NO;
  926. }
  927. -(void)endLoadingAssets
  928. {
  929. [_hud hideHud];
  930. // START new request : initStateCameraUpload
  931. _AutomaticCameraUploadInProgress = NO;
  932. // Enable idle timer
  933. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  934. // START new request : initStateCameraUpload
  935. _AutomaticCameraUploadInProgress = NO;
  936. }
  937. @end