CCPhotosCameraUpload.m 61 KB

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