CCPhotosCameraUpload.m 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. //
  2. // CCPhotosCameraUpload.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCPhotosCameraUpload.h"
  24. #import "AppDelegate.h"
  25. #ifdef CUSTOM_BUILD
  26. #import "Custom.h"
  27. #else
  28. #import "Nextcloud-Swift.h"
  29. #endif
  30. @interface CCPhotosCameraUpload () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  31. {
  32. CCMetadata *_metadata;
  33. BOOL _cellEditing;
  34. NSMutableArray *_queueMetadatas;
  35. NSMutableArray *_selectedMetadatas;
  36. NSUInteger _numSelectedMetadatas;
  37. //BOOL _AutomaticCameraUploadInProgress; // START/STOP new request : initStateCameraUpload
  38. CCSectionDataSourceMetadata *_sectionDataSource;
  39. CCHud *_hud;
  40. }
  41. @end
  42. @implementation CCPhotosCameraUpload
  43. #pragma --------------------------------------------------------------------------------------------
  44. #pragma mark ===== Init =====
  45. #pragma --------------------------------------------------------------------------------------------
  46. - (id)initWithCoder:(NSCoder *)aDecoder
  47. {
  48. if (self = [super initWithCoder:aDecoder]) {
  49. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initStateCameraUpload:) name:@"initStateCameraUpload" object:nil];
  50. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCameraUploadFull) name:@"setupCameraUploadFull" object:nil];
  51. app.activePhotosCameraUpload = self;
  52. }
  53. return self;
  54. }
  55. #pragma --------------------------------------------------------------------------------------------
  56. #pragma mark ===== View =====
  57. #pragma --------------------------------------------------------------------------------------------
  58. - (void)viewDidLoad
  59. {
  60. [super viewDidLoad];
  61. _queueMetadatas = [[NSMutableArray alloc] init];
  62. _selectedMetadatas = [[NSMutableArray alloc] init];
  63. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  64. // empty Data Source
  65. self.collectionView.emptyDataSetDelegate = self;
  66. self.collectionView.emptyDataSetSource = self;
  67. }
  68. // Apparirà
  69. - (void)viewWillAppear:(BOOL)animated
  70. {
  71. [super viewWillAppear:animated];
  72. // Color
  73. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  74. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  75. // Plus Button
  76. [app plusButtonVisibile:true];
  77. [self reloadDatasource];
  78. }
  79. // E' arrivato
  80. - (void)viewDidAppear:(BOOL)animated
  81. {
  82. [super viewDidAppear:animated];
  83. [self.navigationController cancelCCProgress];
  84. }
  85. - (void)didReceiveMemoryWarning
  86. {
  87. [super didReceiveMemoryWarning];
  88. // Dispose of any resources that can be recreated.
  89. }
  90. #pragma --------------------------------------------------------------------------------------------
  91. #pragma mark ====== Photos ======
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== Gestione Grafica Window =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)setUINavigationBarDefault
  97. {
  98. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  99. // select
  100. UIImage *icon = [UIImage imageNamed:image_seleziona];
  101. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  102. if ([_sectionDataSource.allRecordsDataSource count] > 0) buttonSelect.enabled = true;
  103. else buttonSelect.enabled = false;
  104. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  105. self.navigationItem.leftBarButtonItem = nil;
  106. // Title
  107. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  108. }
  109. - (void)setUINavigationBarSelected
  110. {
  111. UIImage *icon;
  112. icon = [UIImage imageNamed:image_deleteSelectedFiles];
  113. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  114. icon = [UIImage imageNamed:image_openSelectedFiles];
  115. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  116. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  117. self.navigationItem.leftBarButtonItem = leftButton;
  118. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  119. // Title
  120. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  121. }
  122. - (void)collectionSelect:(BOOL)edit
  123. {
  124. [self.collectionView setAllowsMultipleSelection:edit];
  125. _cellEditing = edit;
  126. if (edit)
  127. [self setUINavigationBarSelected];
  128. else
  129. [self setUINavigationBarDefault];
  130. }
  131. - (void)collectionSelectYES
  132. {
  133. [self collectionSelect:YES];
  134. }
  135. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(CCMetadata *)metadata
  136. {
  137. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  138. UIVisualEffectView *effect = [cell viewWithTag:200];
  139. UIImageView *checked = [cell viewWithTag:300];
  140. if (select) {
  141. effect.hidden = NO;
  142. effect.alpha = 0.4;
  143. checked.hidden = NO;
  144. [_selectedMetadatas addObject:metadata];
  145. } else {
  146. effect.hidden = YES;
  147. checked.hidden = YES;
  148. [_selectedMetadatas removeObject:metadata];
  149. }
  150. // Title
  151. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  152. }
  153. - (void)scrollToTop
  154. {
  155. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  156. }
  157. - (void)getGeoLocationForSection:(NSInteger)section
  158. {
  159. NSString *addLocation = @"";
  160. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  161. for (NSString *fileID in fileIDsForKey) {
  162. TableLocalFile *localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  163. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  164. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  165. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  166. }
  167. }
  168. }
  169. #pragma --------------------------------------------------------------------------------------------
  170. #pragma mark ==== Photo Library Change Observer ====
  171. #pragma --------------------------------------------------------------------------------------------
  172. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  173. {
  174. /*
  175. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  176. if (collectionChanges) {
  177. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  178. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  179. [self uploadNewAssets];
  180. });
  181. }
  182. */
  183. }
  184. #pragma --------------------------------------------------------------------------------------------
  185. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  186. #pragma --------------------------------------------------------------------------------------------
  187. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  188. {
  189. return YES;
  190. }
  191. /*
  192. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  193. {
  194. return YES;
  195. }
  196. */
  197. - (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
  198. {
  199. return 0.0f;
  200. }
  201. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  202. {
  203. return - self.navigationController.navigationBar.frame.size.height;
  204. }
  205. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  206. {
  207. return [UIColor whiteColor];
  208. }
  209. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  210. {
  211. return [UIImage imageNamed:image_brandBackgroundLite];
  212. }
  213. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  214. {
  215. NSString *text = [NSString stringWithFormat:@"%@", @""];
  216. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:COLOR_BRAND};
  217. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  218. }
  219. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  220. {
  221. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  222. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  223. paragraph.alignment = NSTextAlignmentCenter;
  224. NSString *text;
  225. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount])
  226. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  227. else
  228. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_camera_upload_view_", nil)];
  229. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  230. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  231. }
  232. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  233. {
  234. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount] == NO) {
  235. /*
  236. NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
  237. if ([language isEqualToString:@"it"]) return [UIImage imageNamed:image_activeCameraUpload_it];
  238. else return [UIImage imageNamed:image_activeCameraUpload_en];
  239. */
  240. UIImage *imageButton = [UIImage imageNamed:image_activeCameraUpload];
  241. UIImage *image = [CCUtility drawText:NSLocalizedString(@"_activate_camera_upload_", nil) inImage:imageButton];
  242. return image;
  243. } else return nil;
  244. }
  245. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  246. {
  247. CCManageCameraUpload *viewController = [[CCManageCameraUpload alloc] initWithNibName:nil bundle:nil];
  248. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  249. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  250. [self presentViewController:navigationController animated:YES completion:nil];
  251. }
  252. #pragma --------------------------------------------------------------------------------------------
  253. #pragma mark ===== openSelectedFiles =====
  254. #pragma--------------------------------------------------------------------------------------------
  255. - (void)openSelectedFiles
  256. {
  257. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  258. for (CCMetadata *metadata in _selectedMetadatas) {
  259. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  260. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  261. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  262. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  263. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  264. [dataToShare addObject:data];
  265. }
  266. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  267. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  268. }
  269. }
  270. }
  271. if ([dataToShare count] > 0) {
  272. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  273. // iPad
  274. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  275. self.navigationItem.leftBarButtonItem.enabled = NO;
  276. self.navigationItem.rightBarButtonItem.enabled = NO;
  277. [self presentViewController:activityViewController animated:YES completion:^{
  278. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  279. self.navigationItem.leftBarButtonItem.enabled = YES;
  280. self.navigationItem.rightBarButtonItem.enabled = YES;
  281. if (completed) {
  282. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  283. if ([obj isKindOfClass:[UIImage class]])
  284. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  285. if ([obj isKindOfClass:[NSURL class]])
  286. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  287. }];
  288. [self performSelector:@selector(reloadCollection) withObject:nil];
  289. }
  290. }];
  291. }];
  292. }
  293. }
  294. #pragma --------------------------------------------------------------------------------------------
  295. #pragma mark ===== Download =====
  296. #pragma--------------------------------------------------------------------------------------------
  297. - (void)downloadFileFailure:(NSInteger)errorCode
  298. {
  299. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  300. }
  301. - (void)downloadFileSuccess:(CCMetadata *)metadata
  302. {
  303. NSIndexPath *indexPath;
  304. BOOL existsIcon = NO;
  305. if (metadata.fileID) {
  306. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  307. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  308. }
  309. if (indexPath && existsIcon) {
  310. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  311. if (cell) {
  312. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  313. UIVisualEffectView *effect = [cell viewWithTag:200];
  314. UIImageView *checked = [cell viewWithTag:300];
  315. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  316. effect.hidden = YES;
  317. checked.hidden = YES;
  318. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  319. }
  320. }
  321. }
  322. #pragma --------------------------------------------------------------------------------------------
  323. #pragma mark ===== Delete =====
  324. #pragma--------------------------------------------------------------------------------------------
  325. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  326. {
  327. [self deleteFileOrFolderSuccess:metadataNet];
  328. }
  329. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  330. {
  331. [_queueMetadatas removeObject:metadataNet.selector];
  332. if ([_queueMetadatas count] == 0) {
  333. [_hud hideHud];
  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) {
  349. [_queueMetadatas addObject:selectorDeleteCrypto];
  350. [_queueMetadatas addObject:selectorDeletePlist];
  351. } else {
  352. [_queueMetadatas addObject:selectorDelete];
  353. }
  354. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  355. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  356. }
  357. - (void)deleteSelectedFiles
  358. {
  359. [_queueMetadatas removeAllObjects];
  360. _numSelectedMetadatas = [_selectedMetadatas count];
  361. if ([_selectedMetadatas count] == 0)
  362. return;
  363. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  364. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  365. style:UIAlertActionStyleDestructive
  366. handler:^(UIAlertAction *action) {
  367. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  368. }]];
  369. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  370. style:UIAlertActionStyleCancel
  371. handler:^(UIAlertAction *action) {
  372. [alertController dismissViewControllerAnimated:YES completion:nil];
  373. }]];
  374. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  375. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  376. [alertController.view layoutIfNeeded];
  377. [self presentViewController:alertController animated:YES completion:NULL];
  378. }
  379. #pragma --------------------------------------------------------------------------------------------
  380. #pragma mark ==== Download Thumbnail Delegate ====
  381. #pragma --------------------------------------------------------------------------------------------
  382. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  383. {
  384. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  385. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  386. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ==== Collection ====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)reloadDatasourceForced
  392. {
  393. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  394. [self reloadDatasource];
  395. }
  396. - (void)reloadDatasource
  397. {
  398. // test
  399. if (app.activeAccount.length == 0)
  400. return;
  401. NSString *serverUrl = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  402. if (_sectionDataSource) {
  403. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  404. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  405. dispatch_async(dispatch_get_main_queue(), ^{
  406. [self reloadCollection];
  407. });
  408. });
  409. } else {
  410. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  411. [self reloadCollection];
  412. }
  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_TEXT_ANTHRACITE;
  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. // Thumbnail not present
  483. imageView.image = [UIImage imageNamed:image_photosDownload];
  484. if (metadata.thumbnailExists)
  485. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  486. }
  487. // Cheched
  488. if (cell.selected) {
  489. checked.hidden = NO;
  490. effect.hidden = NO;
  491. effect.alpha = 0.4;
  492. } else {
  493. checked.hidden = YES;
  494. effect.hidden = YES;
  495. }
  496. return cell;
  497. }
  498. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  499. {
  500. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  501. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  502. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  503. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  504. if (_cellEditing) {
  505. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  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: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  556. [allRecordsDataSourceImagesVideos addObject:metadata];
  557. }
  558. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  559. self.detailViewController.metadataDetail = _metadata;
  560. self.detailViewController.dateFilterQuery = _metadata.date;
  561. self.detailViewController.isCameraUpload = YES;
  562. [self.detailViewController setTitle:_metadata.fileNamePrint];
  563. }
  564. #pragma --------------------------------------------------------------------------------------------
  565. #pragma mark ====== --- Camera Upload --- ======
  566. #pragma --------------------------------------------------------------------------------------------
  567. #pragma --------------------------------------------------------------------------------------------
  568. #pragma mark === initStateCameraUpload ===
  569. #pragma --------------------------------------------------------------------------------------------
  570. - (void)initStateCameraUpload:(NSNotification *)notification
  571. {
  572. int afterDelay = 0;
  573. if (notification.object)
  574. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  575. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  576. }
  577. - (void)initStateCameraUpload
  578. {
  579. //if (_AutomaticCameraUploadInProgress)
  580. // return;
  581. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  582. [self setupCameraUpload];
  583. if([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount])
  584. [self checkIfLocationIsEnabled];
  585. } else {
  586. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  587. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  588. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  589. }
  590. }
  591. #pragma --------------------------------------------------------------------------------------------
  592. #pragma mark === Camera Upload & Full ===
  593. #pragma --------------------------------------------------------------------------------------------
  594. - (void)setupCameraUpload
  595. {
  596. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  597. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  598. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  599. [self uploadNewAssets];
  600. } else {
  601. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  602. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  603. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  604. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  605. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  606. delegate:nil
  607. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  608. otherButtonTitles:nil];
  609. [alert show];
  610. }
  611. }
  612. - (void)setupCameraUploadFull
  613. {
  614. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  615. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  616. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  617. [self uploadFullAssets];
  618. } else {
  619. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  620. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  621. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  622. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  623. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  624. delegate:nil
  625. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  626. otherButtonTitles:nil];
  627. [alert show];
  628. }
  629. }
  630. #pragma --------------------------------------------------------------------------------------------
  631. #pragma mark === Location ===
  632. #pragma --------------------------------------------------------------------------------------------
  633. - (BOOL)checkIfLocationIsEnabled
  634. {
  635. [CCManageLocation sharedSingleton].delegate = self;
  636. if ([CLLocationManager locationServicesEnabled]) {
  637. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  638. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  639. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  640. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  641. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  642. } else {
  643. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  644. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  645. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  646. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  647. delegate:nil
  648. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  649. otherButtonTitles:nil];
  650. [alert show];
  651. } else {
  652. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  653. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  654. delegate:nil
  655. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  656. otherButtonTitles:nil];
  657. [alert show];
  658. }
  659. }
  660. } else {
  661. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  662. [CCCoreData setCameraUploadBackground:YES activeAccount:app.activeAccount];
  663. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  664. } else {
  665. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  666. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  667. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  668. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  669. delegate:nil
  670. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  671. otherButtonTitles:nil];
  672. [alert show];
  673. }
  674. }
  675. } else {
  676. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  677. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  678. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  679. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  680. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  681. delegate:nil
  682. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  683. otherButtonTitles:nil];
  684. [alert show];
  685. } else {
  686. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  687. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  688. delegate:nil
  689. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  690. otherButtonTitles:nil];
  691. [alert show];
  692. }
  693. }
  694. return [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount];
  695. }
  696. - (void)statusAuthorizationLocationChanged
  697. {
  698. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  699. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  700. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  701. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  702. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  703. } failureBlock:^(NSError *error) {
  704. }];
  705. }
  706. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  707. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  708. if ([CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  709. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  710. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  711. }
  712. } else {
  713. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  714. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  715. delegate:nil
  716. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  717. otherButtonTitles:nil];
  718. [alert show];
  719. }
  720. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  721. if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  722. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  723. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  724. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  725. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  726. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  727. delegate:nil
  728. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  729. otherButtonTitles:nil];
  730. [alert show];
  731. } else {
  732. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  733. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  734. delegate:nil
  735. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  736. otherButtonTitles:nil];
  737. [alert show];
  738. }
  739. }
  740. }
  741. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  742. [CCManageLocation sharedSingleton].firstChangeAuthorizationDone = YES;
  743. }
  744. }
  745. }
  746. - (void)changedLocation
  747. {
  748. //Verifica
  749. [[CCNetworking sharedNetworking] automaticDownloadInError];
  750. [[CCNetworking sharedNetworking] automaticUploadInError];
  751. // solo in background
  752. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount] && [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount ] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  753. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  754. //check location
  755. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  756. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  757. [self uploadNewAssets];
  758. }
  759. } else {
  760. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  761. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  762. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  763. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  764. }
  765. }
  766. }
  767. #pragma --------------------------------------------------------------------------------------------
  768. #pragma mark ===== Upload Assets : NEW & FULL ====
  769. #pragma --------------------------------------------------------------------------------------------
  770. - (void)uploadNewAssets
  771. {
  772. [self uploadAssetsNewAndFull:NO];
  773. }
  774. - (void)uploadFullAssets
  775. {
  776. [self uploadAssetsNewAndFull:YES];
  777. }
  778. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  779. {
  780. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  781. NSMutableArray *newItemsToUpload;
  782. // Check Asset : NEW or FULL
  783. if (assetsFull) {
  784. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  785. } else {
  786. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  787. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  788. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  789. }
  790. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  791. if ([newItemsToUpload count] == 0)
  792. return;
  793. // STOP new request : initStateCameraUpload
  794. //_AutomaticCameraUploadInProgress = YES;
  795. // Disable idle timer
  796. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  797. if (!_hud) _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  798. if (assetsFull)
  799. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  800. else
  801. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  802. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  803. if (assetsFull)
  804. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  805. else
  806. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  807. });
  808. }
  809. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  810. {
  811. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  812. }
  813. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  814. {
  815. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  816. }
  817. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  818. {
  819. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  820. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  821. BOOL createSubfolders = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  822. // Conversion from ALAsset -to-> PHAsset
  823. for (ALAsset *asset in newItemsToUpload) {
  824. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  825. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  826. PHAsset *asset = [fetchResult firstObject];
  827. [newItemsPHAssetToUpload addObject:asset];
  828. }
  829. // verify/create folder Camera Upload, if error exit
  830. if(![self automaticCreateFolder:folderPhotos]) {
  831. // Full Upload ?
  832. if (assetsFull)
  833. [app messageNotification:@"_error_" description:NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil) visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  834. // START new request : initStateCameraUpload
  835. //_AutomaticCameraUploadInProgress = NO;
  836. return;
  837. }
  838. // Use subfolders verify/create subfolder, if error exit
  839. if (createSubfolders) {
  840. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:newItemsPHAssetToUpload]) {
  841. if (![self automaticCreateFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  842. [self endLoadingAssets];
  843. if (assetsFull)
  844. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  845. return;
  846. }
  847. }
  848. }
  849. for (PHAsset *asset in newItemsPHAssetToUpload) {
  850. NSString *serverUrl;
  851. NSDate *assetDate = asset.creationDate;
  852. PHAssetMediaType assetMediaType = asset.mediaType;
  853. NSString *session;
  854. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  855. // Select type of session
  856. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  857. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  858. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  859. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  860. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  861. [formatter setDateFormat:@"yyyy"];
  862. NSString *yearString = [formatter stringFromDate:assetDate];
  863. [formatter setDateFormat:@"MM"];
  864. NSString *monthString = [formatter stringFromDate:assetDate];
  865. if (createSubfolders)
  866. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  867. else
  868. serverUrl = folderPhotos;
  869. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  870. metadataNet.action = actionUploadAsset;
  871. metadataNet.identifier = asset.localIdentifier;
  872. if (assetsFull) {
  873. metadataNet.selector = selectorUploadAutomaticAll;
  874. metadataNet.selectorPost = selectorUploadRemovePhoto;
  875. metadataNet.priority = NSOperationQueuePriorityLow;
  876. } else {
  877. metadataNet.selector = selectorUploadAutomatic;
  878. metadataNet.selectorPost = nil;
  879. metadataNet.priority = NSOperationQueuePriorityNormal;
  880. }
  881. metadataNet.fileName = fileName;
  882. metadataNet.serverUrl = serverUrl;
  883. metadataNet.session = session;
  884. metadataNet.taskStatus = k_taskStatusResume;
  885. [CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount context:nil];
  886. // Upldate Camera Upload data
  887. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  888. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  889. }
  890. // start upload
  891. if (assetsFull)
  892. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  893. else
  894. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  895. // end loading
  896. [self endLoadingAssets];
  897. // Update icon badge number
  898. [app updateApplicationIconBadgeNumber];
  899. }
  900. - (BOOL)automaticCreateFolder:(NSString *)folderPathName
  901. {
  902. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  903. __block BOOL noError = YES;
  904. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  905. [communication setCredentialsWithUser:app.activeUser andPassword:app.activePassword];
  906. [communication setUserAgent:[CCUtility getUserAgent]];
  907. [communication readFile:folderPathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  908. dispatch_semaphore_signal(semaphore);
  909. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  910. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:app.hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  911. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:[CCUtility deletingLastPathComponentFromServerUrl:folderPathName] directoryID:nil];
  912. dispatch_semaphore_signal(semaphore);
  913. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  914. noError = NO;
  915. dispatch_semaphore_signal(semaphore);
  916. } errorBeforeRequest:^(NSError *error) {
  917. noError = NO;
  918. dispatch_semaphore_signal(semaphore);
  919. }];
  920. }];
  921. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  922. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  923. return noError;
  924. }
  925. -(void)endLoadingAssets
  926. {
  927. [_hud hideHud];
  928. // START new request : initStateCameraUpload
  929. //_AutomaticCameraUploadInProgress = NO;
  930. // Enable idle timer
  931. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  932. }
  933. @end