CCPhotosCameraUpload.m 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  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. tableMetadata *_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:(tableMetadata *)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 *etagsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  158. for (NSString *etag in etagsForKey) {
  159. TableLocalFile *localFile = [CCCoreData getLocalFileWithEtag:etag 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 (tableMetadata *metadata in _selectedMetadatas) {
  234. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  235. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.etag] 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:(tableMetadata *)metadata
  277. {
  278. NSIndexPath *indexPath;
  279. BOOL existsIcon = NO;
  280. if (metadata.etag) {
  281. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.etag]];
  282. indexPath = [_sectionDataSource.etagIndexPath objectForKey:metadata.etag];
  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.etag]];
  291. effect.hidden = YES;
  292. checked.hidden = YES;
  293. [app.icoImagesCache setObject:imageView.image forKey:metadata.etag];
  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:(tableMetadata *)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.etagIndexPath objectForKey:metadataNet.etag];
  360. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.etag]])
  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. NSArray *results = [[NCManageDatabase sharedInstance] getRecordsTableMetadataPhotosCameraUpload:serverUrl];
  389. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:results listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  390. dispatch_async(dispatch_get_main_queue(), ^{
  391. [self reloadCollection];
  392. });
  393. });
  394. } else {
  395. NSArray *results = [[NCManageDatabase sharedInstance] getRecordsTableMetadataPhotosCameraUpload:serverUrl];
  396. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:results listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  397. [self reloadCollection];
  398. }
  399. }
  400. - (void)reloadCollection
  401. {
  402. [self.collectionView reloadData];
  403. [_selectedMetadatas removeAllObjects];
  404. [self collectionSelect:NO];
  405. }
  406. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  407. {
  408. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  409. }
  410. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  411. {
  412. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  413. }
  414. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  415. {
  416. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  417. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  418. return CGSizeMake(collectionView.frame.size.width / 5.3f, collectionView.frame.size.width / 5.3f);
  419. else
  420. return CGSizeMake(collectionView.frame.size.width / 7.3f, collectionView.frame.size.width / 7.3f);
  421. }
  422. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  423. {
  424. if ([_sectionDataSource.sections count] - 1 == section)
  425. return CGSizeMake(collectionView.frame.size.width, 50);
  426. return CGSizeZero;
  427. }
  428. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  429. {
  430. if (kind == UICollectionElementKindSectionHeader) {
  431. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  432. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  433. [self getGeoLocationForSection:indexPath.section];
  434. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  435. titleLabel.textColor = [UIColor blackColor];
  436. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  437. return headerView;
  438. }
  439. if (kind == UICollectionElementKindSectionFooter) {
  440. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  441. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  442. titleLabel.textColor = [UIColor grayColor];
  443. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  444. return footerView;
  445. }
  446. return nil;
  447. }
  448. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  449. {
  450. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  451. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  452. UIVisualEffectView *effect = [cell viewWithTag:200];
  453. UIImageView *checked = [cell viewWithTag:300];
  454. checked.image = [UIImage imageNamed:@"checked"];
  455. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  456. NSString *etag = [metadatasForKey objectAtIndex:indexPath.row];
  457. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:etag];
  458. // Image
  459. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.etag]]) {
  460. imageView.image = [app.icoImagesCache objectForKey:metadata.etag];
  461. if (imageView.image == nil) {
  462. // insert Image
  463. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.etag]];
  464. imageView.image = image;
  465. [app.icoImagesCache setObject:image forKey:metadata.etag];
  466. }
  467. } else {
  468. // Thumbnail not present
  469. imageView.image = [UIImage imageNamed:@"file_photo"];
  470. if (metadata.thumbnailExists)
  471. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  472. }
  473. // Cheched
  474. if (cell.selected) {
  475. checked.hidden = NO;
  476. effect.hidden = NO;
  477. effect.alpha = 0.4;
  478. } else {
  479. checked.hidden = YES;
  480. effect.hidden = YES;
  481. }
  482. return cell;
  483. }
  484. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  485. {
  486. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  487. NSString *etag = [metadatasForKey objectAtIndex:indexPath.row];
  488. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:etag];
  489. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  490. if (_cellEditing) {
  491. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  492. } else {
  493. if ([self shouldPerformSegue])
  494. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  495. }
  496. }
  497. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  498. {
  499. if (_cellEditing == NO)
  500. return;
  501. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  502. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  503. NSString *etag = [metadatasForKey objectAtIndex:indexPath.row];
  504. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:etag];
  505. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  506. }
  507. #pragma --------------------------------------------------------------------------------------------
  508. #pragma mark ===== Navigation ====
  509. #pragma --------------------------------------------------------------------------------------------
  510. - (BOOL)shouldPerformSegue
  511. {
  512. // Test
  513. // Background ? exit
  514. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  515. return NO;
  516. // Not in first plain ? exit
  517. if (self.view.window == NO)
  518. return NO;
  519. // Collapsed but in first plain in detail exit
  520. if (self.splitViewController.isCollapsed)
  521. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  522. return NO;
  523. // Video running exit
  524. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  525. return NO;
  526. // ok perform segue
  527. return YES;
  528. }
  529. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  530. {
  531. id controller = segue.destinationViewController;
  532. if ([controller isKindOfClass:[UINavigationController class]]) {
  533. UINavigationController *navigationController = controller;
  534. self.detailViewController = (CCDetail *)navigationController.topViewController;
  535. } else {
  536. self.detailViewController = segue.destinationViewController;
  537. }
  538. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  539. for (NSString *etag in _sectionDataSource.allEtag) {
  540. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:etag];
  541. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  542. [allRecordsDataSourceImagesVideos addObject:metadata];
  543. }
  544. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  545. self.detailViewController.metadataDetail = _metadata;
  546. self.detailViewController.dateFilterQuery = _metadata.date;
  547. self.detailViewController.isCameraUpload = YES;
  548. [self.detailViewController setTitle:_metadata.fileNamePrint];
  549. }
  550. #pragma --------------------------------------------------------------------------------------------
  551. #pragma mark === initStateCameraUpload ===
  552. #pragma --------------------------------------------------------------------------------------------
  553. - (void)initStateCameraUpload:(NSNotification *)notification
  554. {
  555. int afterDelay = 0;
  556. if (notification.object)
  557. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  558. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  559. }
  560. - (void)initStateCameraUpload
  561. {
  562. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  563. if (tableAccount.cameraUpload) {
  564. [self setupCameraUpload];
  565. if (tableAccount.cameraUploadBackground)
  566. [self checkIfLocationIsEnabled];
  567. } else {
  568. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUpload" state:NO];
  569. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  570. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  571. }
  572. }
  573. #pragma --------------------------------------------------------------------------------------------
  574. #pragma mark === Camera Upload & Full ===
  575. #pragma --------------------------------------------------------------------------------------------
  576. - (void)setupCameraUpload
  577. {
  578. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  579. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  580. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  581. [self uploadNewAssets];
  582. } else {
  583. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUpload" state:NO];
  584. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  585. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  586. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  587. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  588. delegate:nil
  589. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  590. otherButtonTitles:nil];
  591. [alert show];
  592. }
  593. }
  594. - (void)setupCameraUploadFull
  595. {
  596. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  597. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  598. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  599. [self uploadFullAssets];
  600. } else {
  601. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUpload" state:NO];
  602. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  603. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  604. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  605. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  606. delegate:nil
  607. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  608. otherButtonTitles:nil];
  609. [alert show];
  610. }
  611. }
  612. #pragma --------------------------------------------------------------------------------------------
  613. #pragma mark === Location ===
  614. #pragma --------------------------------------------------------------------------------------------
  615. - (BOOL)checkIfLocationIsEnabled
  616. {
  617. [CCManageLocation sharedInstance].delegate = self;
  618. if ([CLLocationManager locationServicesEnabled]) {
  619. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  620. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  621. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  622. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  623. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  624. } else {
  625. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  626. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUploadBackground" state:NO];
  627. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  628. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  629. delegate:nil
  630. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  631. otherButtonTitles:nil];
  632. [alert show];
  633. } else {
  634. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  635. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  636. delegate:nil
  637. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  638. otherButtonTitles:nil];
  639. [alert show];
  640. }
  641. }
  642. } else {
  643. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  644. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUploadBackground" state:YES];
  645. [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
  646. } else {
  647. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUploadBackground" state:NO];
  648. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  649. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  650. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  651. delegate:nil
  652. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  653. otherButtonTitles:nil];
  654. [alert show];
  655. }
  656. }
  657. } else {
  658. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUploadBackground" state:NO];
  659. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  660. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  661. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  662. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  663. delegate:nil
  664. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  665. otherButtonTitles:nil];
  666. [alert show];
  667. } else {
  668. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  669. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  670. delegate:nil
  671. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  672. otherButtonTitles:nil];
  673. [alert show];
  674. }
  675. }
  676. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  677. return tableAccount.cameraUploadBackground;
  678. }
  679. - (void)statusAuthorizationLocationChanged
  680. {
  681. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  682. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  683. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  684. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  685. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  686. } failureBlock:^(NSError *error) {
  687. }];
  688. }
  689. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  690. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  691. if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  692. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUploadBackground" state:NO];
  693. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  694. }
  695. } else {
  696. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  697. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  698. delegate:nil
  699. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  700. otherButtonTitles:nil];
  701. [alert show];
  702. }
  703. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  704. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  705. if (tableAccount.cameraUploadBackground) {
  706. [[NCManageDatabase sharedInstance] setAccountCameraStateFiled:@"cameraUploadBackground" state:NO];
  707. [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
  708. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  709. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  710. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  711. delegate:nil
  712. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  713. otherButtonTitles:nil];
  714. [alert show];
  715. } else {
  716. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  717. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  718. delegate:nil
  719. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  720. otherButtonTitles:nil];
  721. [alert show];
  722. }
  723. }
  724. }
  725. if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
  726. [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
  727. }
  728. }
  729. }
  730. - (void)changedLocation
  731. {
  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 etag: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 etag: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 etag: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 etag: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 etag: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