CCPhotosCameraUpload.m 59 KB

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