CCPhotosCameraUpload.m 57 KB

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