CCPhotosCameraUpload.m 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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 (tableAccount.cameraUploadBackground)
  566. [self checkIfLocationIsEnabled];
  567. } else {
  568. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUpload" state:NO];
  569. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  570. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  571. }
  572. }
  573. #pragma --------------------------------------------------------------------------------------------
  574. #pragma mark === Camera Upload & Full ===
  575. #pragma --------------------------------------------------------------------------------------------
  576. - (void)setupCameraUpload
  577. {
  578. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  579. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  580. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  581. [self uploadNewAssets];
  582. } else {
  583. // [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  584. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUpload" state:NO];
  585. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  586. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  587. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  588. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  589. delegate:nil
  590. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  591. otherButtonTitles:nil];
  592. [alert show];
  593. }
  594. }
  595. - (void)setupCameraUploadFull
  596. {
  597. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  598. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  599. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  600. [self uploadFullAssets];
  601. } else {
  602. //[CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  603. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUpload" state:NO];
  604. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  605. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  606. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  607. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  608. delegate:nil
  609. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  610. otherButtonTitles:nil];
  611. [alert show];
  612. }
  613. }
  614. #pragma --------------------------------------------------------------------------------------------
  615. #pragma mark === Location ===
  616. #pragma --------------------------------------------------------------------------------------------
  617. - (BOOL)checkIfLocationIsEnabled
  618. {
  619. [CCManageLocation sharedInstance].delegate = self;
  620. if ([CLLocationManager locationServicesEnabled]) {
  621. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  622. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  623. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  624. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  625. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  626. } else {
  627. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  628. //[CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  629. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:NO];
  630. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  631. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  632. delegate:nil
  633. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  634. otherButtonTitles:nil];
  635. [alert show];
  636. } else {
  637. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  638. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  639. delegate:nil
  640. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  641. otherButtonTitles:nil];
  642. [alert show];
  643. }
  644. }
  645. } else {
  646. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  647. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:YES];
  648. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  649. } else {
  650. // [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  651. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:NO];
  652. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  653. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  654. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  655. delegate:nil
  656. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  657. otherButtonTitles:nil];
  658. [alert show];
  659. }
  660. }
  661. } else {
  662. //[CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  663. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:NO];
  664. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  665. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  666. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  667. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  668. delegate:nil
  669. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  670. otherButtonTitles:nil];
  671. [alert show];
  672. } else {
  673. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  674. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  675. delegate:nil
  676. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  677. otherButtonTitles:nil];
  678. [alert show];
  679. }
  680. }
  681. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  682. return tableAccount.cameraUploadBackground;
  683. }
  684. - (void)statusAuthorizationLocationChanged
  685. {
  686. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  687. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  688. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  689. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  690. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  691. } failureBlock:^(NSError *error) {
  692. }];
  693. }
  694. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  695. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  696. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  697. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:NO];
  698. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  699. }
  700. } else {
  701. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  702. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  703. delegate:nil
  704. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  705. otherButtonTitles:nil];
  706. [alert show];
  707. }
  708. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  709. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  710. if (tableAccount.cameraUploadBackground) {
  711. //if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  712. //[CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  713. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:NO];
  714. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  715. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  716. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  717. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  718. delegate:nil
  719. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  720. otherButtonTitles:nil];
  721. [alert show];
  722. } else {
  723. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  724. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  725. delegate:nil
  726. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  727. otherButtonTitles:nil];
  728. [alert show];
  729. }
  730. }
  731. }
  732. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  733. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  734. }
  735. }
  736. }
  737. - (void)changedLocation
  738. {
  739. [[CCNetworking sharedNetworking] automaticDownloadInError];
  740. [[CCNetworking sharedNetworking] automaticUploadInError];
  741. // Only in background
  742. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  743. if (tableAccount.cameraUpload && tableAccount.cameraUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  744. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  745. //check location
  746. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  747. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  748. [self uploadNewAssets];
  749. }
  750. } else {
  751. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUpload" state:NO];
  752. [[NCManageDatabase sharedInstance] setAccountCameraStateFiledWithField:@"cameraUploadBackground" state:NO];
  753. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  754. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  755. }
  756. }
  757. }
  758. #pragma --------------------------------------------------------------------------------------------
  759. #pragma mark ===== Upload Assets : NEW & FULL ====
  760. #pragma --------------------------------------------------------------------------------------------
  761. - (void)uploadNewAssets
  762. {
  763. [self uploadAssetsNewAndFull:NO];
  764. }
  765. - (void)uploadFullAssets
  766. {
  767. [self uploadAssetsNewAndFull:YES];
  768. }
  769. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  770. {
  771. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  772. NSMutableArray *newItemsToUpload;
  773. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  774. // Is loading new Asset ?
  775. if (app.automaticCheckAssetInProgress)
  776. return;
  777. // Check Asset : NEW or FULL
  778. if (assetsFull) {
  779. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  780. } else {
  781. NSDate *databaseDatePhoto = tableAccount.cameraUploadDatePhoto;
  782. NSDate *databaseDateVideo = tableAccount.cameraUploadDateVideo;
  783. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  784. }
  785. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  786. if ([newItemsToUpload count] == 0)
  787. return;
  788. // STOP
  789. app.automaticCheckAssetInProgress = YES;
  790. // Disable idle timer
  791. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  792. if (assetsFull) {
  793. if (!_hud)
  794. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  795. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  796. }
  797. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  798. if (assetsFull)
  799. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  800. else
  801. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  802. });
  803. }
  804. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  805. {
  806. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  807. }
  808. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  809. {
  810. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  811. }
  812. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  813. {
  814. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  815. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  816. NSString *folderPhotos = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  817. BOOL useSubFolder = tableAccount.cameraUploadCreateSubfolder;
  818. // Conversion from ALAsset -to-> PHAsset
  819. for (ALAsset *asset in newItemsToUpload) {
  820. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  821. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  822. PHAsset *asset = [fetchResult firstObject];
  823. [newItemsPHAssetToUpload addObject:asset];
  824. NSLog(@"Convert url %@", url);
  825. }
  826. // Create the folder for Photos & if request the subfolders
  827. if(![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutomaticAll]) {
  828. // end loading
  829. [_hud hideHud];
  830. // START
  831. app.automaticCheckAssetInProgress = NO;
  832. // Enable idle timer
  833. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  834. return;
  835. }
  836. for (PHAsset *asset in newItemsPHAssetToUpload) {
  837. NSString *serverUrl;
  838. NSDate *assetDate = asset.creationDate;
  839. PHAssetMediaType assetMediaType = asset.mediaType;
  840. NSString *session;
  841. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  842. // Select type of session
  843. /*
  844. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  845. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  846. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  847. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  848. */
  849. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.cameraUploadWWAnPhoto == NO) session = k_upload_session;
  850. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.cameraUploadWWAnVideo == NO) session = k_upload_session;
  851. if (assetMediaType == PHAssetMediaTypeImage && tableAccount.cameraUploadWWAnPhoto) session = k_upload_session_wwan;
  852. if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.cameraUploadWWAnVideo) session = k_upload_session_wwan;
  853. NSDateFormatter *formatter = [NSDateFormatter new];
  854. [formatter setDateFormat:@"yyyy"];
  855. NSString *yearString = [formatter stringFromDate:assetDate];
  856. [formatter setDateFormat:@"MM"];
  857. NSString *monthString = [formatter stringFromDate:assetDate];
  858. if (useSubFolder)
  859. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  860. else
  861. serverUrl = folderPhotos;
  862. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  863. metadataNet.action = actionUploadAsset;
  864. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  865. if (assetsFull) {
  866. metadataNet.selector = selectorUploadAutomaticAll;
  867. metadataNet.selectorPost = selectorUploadRemovePhoto;
  868. metadataNet.priority = NSOperationQueuePriorityLow;
  869. } else {
  870. metadataNet.selector = selectorUploadAutomatic;
  871. metadataNet.selectorPost = nil;
  872. metadataNet.priority = NSOperationQueuePriorityNormal;
  873. }
  874. metadataNet.fileName = fileName;
  875. metadataNet.serverUrl = serverUrl;
  876. metadataNet.session = session;
  877. metadataNet.taskStatus = k_taskStatusResume;
  878. if (assetsFull)
  879. [self addDatabaseAutomaticUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  880. else
  881. [self writeAssetToSandbox:metadataNet];
  882. }
  883. // end loading
  884. [_hud hideHud];
  885. // START
  886. app.automaticCheckAssetInProgress = NO;
  887. // Enable idle timer
  888. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  889. }
  890. - (void)writeAssetToSandbox:(CCMetadataNet *)metadataNet
  891. {
  892. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  893. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  894. PHAsset *asset = result[0];
  895. PHAssetMediaType assetMediaType = asset.mediaType;
  896. NSDate *assetDate = asset.creationDate;
  897. __block NSError *error = nil;
  898. // VIDEO
  899. if (assetMediaType == PHAssetMediaTypeVideo) {
  900. @autoreleasepool {
  901. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  902. options.networkAccessAllowed = true;
  903. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  904. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]])
  905. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] error:nil];
  906. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  907. if (exportSession) {
  908. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]];
  909. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  910. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  911. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  912. [self addDatabaseAutomaticUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  913. } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
  914. [[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];
  915. } else {
  916. NSLog(@"Export Session Status: %ld", (long)exportSession.status);
  917. }
  918. }];
  919. } else {
  920. [[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];
  921. }
  922. }];
  923. }
  924. }
  925. // IMAGE
  926. if (assetMediaType == PHAssetMediaTypeImage) {
  927. @autoreleasepool {
  928. PHImageRequestOptions *options = [PHImageRequestOptions new];
  929. options.synchronous = NO;
  930. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  931. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  932. if (error) {
  933. NSString *note = [NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description];
  934. [[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];
  935. [[NCManageDatabase sharedInstance] deleteAutomaticUploadForAccount:appDelegate.activeAccount assetLocalIdentifier:metadataNet.assetLocalIdentifier];
  936. } else {
  937. [self addDatabaseAutomaticUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
  938. }
  939. }];
  940. }
  941. }
  942. }
  943. - (void)addDatabaseAutomaticUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
  944. {
  945. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  946. if ([[NCManageDatabase sharedInstance] addAutomaticUpload:metadataNet account:appDelegate.activeAccount]) {
  947. [[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];
  948. } else {
  949. [[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];
  950. }
  951. dispatch_async(dispatch_get_main_queue(), ^{
  952. // Update Camera Upload data
  953. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  954. [[NCManageDatabase sharedInstance] setAccountsCameraUploadDateAssetTypeWithAssetMediaType:assetMediaType assetDate:assetDate];
  955. // Update icon badge number
  956. [app updateApplicationIconBadgeNumber];
  957. });
  958. }
  959. @end