CCPhotosCameraUpload.m 52 KB

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