CCPhotosCameraUpload.m 60 KB

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