CCPhotosCameraUpload.m 55 KB

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