CCPhotosCameraUpload.m 54 KB

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