CCPhotosCameraUpload.m 52 KB

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