CCPhotosCameraUpload.m 54 KB

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