CCPhotosCameraUpload.m 51 KB

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