CCPhotosCameraUpload.m 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. //
  2. // CCPhotosCameraUpload.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCPhotosCameraUpload.h"
  24. #import "AppDelegate.h"
  25. #ifdef CUSTOM_BUILD
  26. #import "CustomSwift.h"
  27. #else
  28. #import "Nextcloud-Swift.h"
  29. #endif
  30. @interface CCPhotosCameraUpload () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  31. {
  32. CCMetadata *_metadata;
  33. BOOL _cellEditing;
  34. NSMutableArray *_queueMetadatas;
  35. NSMutableArray *_selectedMetadatas;
  36. NSUInteger _numSelectedMetadatas;
  37. //BOOL _AutomaticCameraUploadInProgress; // START/STOP new request : initStateCameraUpload
  38. CCSectionDataSourceMetadata *_sectionDataSource;
  39. CCHud *_hud;
  40. }
  41. @end
  42. @implementation CCPhotosCameraUpload
  43. #pragma --------------------------------------------------------------------------------------------
  44. #pragma mark ===== Init =====
  45. #pragma --------------------------------------------------------------------------------------------
  46. - (id)initWithCoder:(NSCoder *)aDecoder
  47. {
  48. if (self = [super initWithCoder:aDecoder]) {
  49. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initStateCameraUpload:) name:@"initStateCameraUpload" object:nil];
  50. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCameraUploadFull) name:@"setupCameraUploadFull" object:nil];
  51. app.activePhotosCameraUpload = self;
  52. }
  53. return self;
  54. }
  55. #pragma --------------------------------------------------------------------------------------------
  56. #pragma mark ===== View =====
  57. #pragma --------------------------------------------------------------------------------------------
  58. - (void)viewDidLoad
  59. {
  60. [super viewDidLoad];
  61. _queueMetadatas = [[NSMutableArray alloc] init];
  62. _selectedMetadatas = [[NSMutableArray alloc] init];
  63. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  64. // empty Data Source
  65. self.collectionView.emptyDataSetDelegate = self;
  66. self.collectionView.emptyDataSetSource = self;
  67. }
  68. // Apparirà
  69. - (void)viewWillAppear:(BOOL)animated
  70. {
  71. [super viewWillAppear:animated];
  72. // Color
  73. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  74. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  75. // Plus Button
  76. [app plusButtonVisibile:true];
  77. [self reloadDatasource];
  78. }
  79. // E' arrivato
  80. - (void)viewDidAppear:(BOOL)animated
  81. {
  82. [super viewDidAppear:animated];
  83. [self.navigationController cancelCCProgress];
  84. }
  85. - (void)didReceiveMemoryWarning
  86. {
  87. [super didReceiveMemoryWarning];
  88. // Dispose of any resources that can be recreated.
  89. }
  90. #pragma --------------------------------------------------------------------------------------------
  91. #pragma mark ====== Photos ======
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== Gestione Grafica Window =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)setUINavigationBarDefault
  97. {
  98. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  99. // select
  100. UIImage *icon = [UIImage imageNamed:image_seleziona];
  101. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  102. if ([_sectionDataSource.allRecordsDataSource count] > 0) buttonSelect.enabled = true;
  103. else buttonSelect.enabled = false;
  104. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  105. self.navigationItem.leftBarButtonItem = nil;
  106. // Title
  107. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  108. }
  109. - (void)setUINavigationBarSelected
  110. {
  111. UIImage *icon;
  112. icon = [UIImage imageNamed:image_deleteSelectedFiles];
  113. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  114. icon = [UIImage imageNamed:image_openSelectedFiles];
  115. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  116. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  117. self.navigationItem.leftBarButtonItem = leftButton;
  118. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  119. // Title
  120. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  121. }
  122. - (void)collectionSelect:(BOOL)edit
  123. {
  124. [self.collectionView setAllowsMultipleSelection:edit];
  125. _cellEditing = edit;
  126. if (edit)
  127. [self setUINavigationBarSelected];
  128. else
  129. [self setUINavigationBarDefault];
  130. }
  131. - (void)collectionSelectYES
  132. {
  133. [self collectionSelect:YES];
  134. }
  135. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(CCMetadata *)metadata
  136. {
  137. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  138. UIVisualEffectView *effect = [cell viewWithTag:200];
  139. UIImageView *checked = [cell viewWithTag:300];
  140. if (select) {
  141. effect.hidden = NO;
  142. effect.alpha = 0.4;
  143. checked.hidden = NO;
  144. [_selectedMetadatas addObject:metadata];
  145. } else {
  146. effect.hidden = YES;
  147. checked.hidden = YES;
  148. [_selectedMetadatas removeObject:metadata];
  149. }
  150. // Title
  151. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  152. }
  153. - (void)scrollToTop
  154. {
  155. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  156. }
  157. - (void)getGeoLocationForSection:(NSInteger)section
  158. {
  159. NSString *addLocation = @"";
  160. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  161. for (NSString *fileID in fileIDsForKey) {
  162. TableLocalFile *localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  163. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  164. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  165. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  166. }
  167. }
  168. }
  169. #pragma --------------------------------------------------------------------------------------------
  170. #pragma mark ==== Photo Library Change Observer ====
  171. #pragma --------------------------------------------------------------------------------------------
  172. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  173. {
  174. /*
  175. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  176. if (collectionChanges) {
  177. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  178. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  179. [self uploadNewAssets];
  180. });
  181. }
  182. */
  183. }
  184. #pragma --------------------------------------------------------------------------------------------
  185. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  186. #pragma --------------------------------------------------------------------------------------------
  187. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  188. {
  189. return YES;
  190. }
  191. /*
  192. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  193. {
  194. return YES;
  195. }
  196. */
  197. - (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
  198. {
  199. return 0.0f;
  200. }
  201. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  202. {
  203. return - self.navigationController.navigationBar.frame.size.height;
  204. }
  205. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  206. {
  207. return [UIColor whiteColor];
  208. }
  209. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  210. {
  211. return [UIImage imageNamed:image_brandBackgroundLite];
  212. }
  213. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  214. {
  215. NSString *text = [NSString stringWithFormat:@"%@", @""];
  216. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:COLOR_BRAND};
  217. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  218. }
  219. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  220. {
  221. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  222. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  223. paragraph.alignment = NSTextAlignmentCenter;
  224. NSString *text;
  225. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount])
  226. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  227. else
  228. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_camera_upload_view_", nil)];
  229. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  230. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  231. }
  232. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  233. {
  234. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount] == NO) {
  235. /*
  236. NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
  237. if ([language isEqualToString:@"it"]) return [UIImage imageNamed:image_activeCameraUpload_it];
  238. else return [UIImage imageNamed:image_activeCameraUpload_en];
  239. */
  240. UIImage *imageButton = [UIImage imageNamed:image_activeCameraUpload];
  241. UIImage *image = [CCUtility drawText:NSLocalizedString(@"_activate_camera_upload_", nil) inImage:imageButton];
  242. return image;
  243. } else return nil;
  244. }
  245. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  246. {
  247. CCManageCameraUpload *viewController = [[CCManageCameraUpload alloc] initWithNibName:nil bundle:nil];
  248. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  249. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  250. [self presentViewController:navigationController animated:YES completion:nil];
  251. }
  252. #pragma --------------------------------------------------------------------------------------------
  253. #pragma mark ===== openSelectedFiles =====
  254. #pragma--------------------------------------------------------------------------------------------
  255. - (void)openSelectedFiles
  256. {
  257. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  258. for (CCMetadata *metadata in _selectedMetadatas) {
  259. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  260. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  261. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  262. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  263. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  264. [dataToShare addObject:data];
  265. }
  266. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  267. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  268. }
  269. }
  270. }
  271. if ([dataToShare count] > 0) {
  272. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  273. // iPad
  274. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  275. self.navigationItem.leftBarButtonItem.enabled = NO;
  276. self.navigationItem.rightBarButtonItem.enabled = NO;
  277. [self presentViewController:activityViewController animated:YES completion:^{
  278. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  279. self.navigationItem.leftBarButtonItem.enabled = YES;
  280. self.navigationItem.rightBarButtonItem.enabled = YES;
  281. if (completed) {
  282. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  283. if ([obj isKindOfClass:[UIImage class]])
  284. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  285. if ([obj isKindOfClass:[NSURL class]])
  286. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  287. }];
  288. [self performSelector:@selector(reloadCollection) withObject:nil];
  289. }
  290. }];
  291. }];
  292. }
  293. }
  294. #pragma --------------------------------------------------------------------------------------------
  295. #pragma mark ===== Download =====
  296. #pragma--------------------------------------------------------------------------------------------
  297. - (void)downloadFileFailure:(NSInteger)errorCode
  298. {
  299. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  300. }
  301. - (void)downloadFileSuccess:(CCMetadata *)metadata
  302. {
  303. NSIndexPath *indexPath;
  304. BOOL existsIcon = NO;
  305. if (metadata.fileID) {
  306. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  307. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  308. }
  309. if (indexPath && existsIcon) {
  310. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  311. if (cell) {
  312. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  313. UIVisualEffectView *effect = [cell viewWithTag:200];
  314. UIImageView *checked = [cell viewWithTag:300];
  315. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  316. effect.hidden = YES;
  317. checked.hidden = YES;
  318. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  319. }
  320. }
  321. }
  322. #pragma --------------------------------------------------------------------------------------------
  323. #pragma mark ===== Delete =====
  324. #pragma--------------------------------------------------------------------------------------------
  325. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  326. {
  327. [self deleteFileOrFolderSuccess:metadataNet];
  328. }
  329. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  330. {
  331. [_queueMetadatas removeObject:metadataNet.selector];
  332. if ([_queueMetadatas count] == 0) {
  333. [_hud hideHud];
  334. if ([_selectedMetadatas count] > 0) {
  335. [_selectedMetadatas removeObjectAtIndex:0];
  336. if ([_selectedMetadatas count] > 0) {
  337. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  338. } else {
  339. [self reloadDatasource];
  340. }
  341. } else {
  342. [self reloadDatasource];
  343. }
  344. }
  345. }
  346. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  347. {
  348. if (metadata.cryptated) {
  349. [_queueMetadatas addObject:selectorDeleteCrypto];
  350. [_queueMetadatas addObject:selectorDeletePlist];
  351. } else {
  352. [_queueMetadatas addObject:selectorDelete];
  353. }
  354. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  355. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  356. }
  357. - (void)deleteSelectedFiles
  358. {
  359. [_queueMetadatas removeAllObjects];
  360. _numSelectedMetadatas = [_selectedMetadatas count];
  361. if ([_selectedMetadatas count] == 0)
  362. return;
  363. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  364. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  365. style:UIAlertActionStyleDestructive
  366. handler:^(UIAlertAction *action) {
  367. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  368. }]];
  369. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  370. style:UIAlertActionStyleCancel
  371. handler:^(UIAlertAction *action) {
  372. [alertController dismissViewControllerAnimated:YES completion:nil];
  373. }]];
  374. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  375. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  376. [alertController.view layoutIfNeeded];
  377. [self presentViewController:alertController animated:YES completion:NULL];
  378. }
  379. #pragma --------------------------------------------------------------------------------------------
  380. #pragma mark ==== Download Thumbnail Delegate ====
  381. #pragma --------------------------------------------------------------------------------------------
  382. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  383. {
  384. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  385. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  386. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ==== Collection ====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)reloadDatasourceForced
  392. {
  393. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  394. [self reloadDatasource];
  395. }
  396. - (void)reloadDatasource
  397. {
  398. // test
  399. if (app.activeAccount.length == 0)
  400. return;
  401. NSString *serverUrl = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  402. if (_sectionDataSource) {
  403. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  404. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  405. dispatch_async(dispatch_get_main_queue(), ^{
  406. [self reloadCollection];
  407. });
  408. });
  409. } else {
  410. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  411. [self reloadCollection];
  412. }
  413. }
  414. - (void)reloadCollection
  415. {
  416. [self.collectionView reloadData];
  417. [_selectedMetadatas removeAllObjects];
  418. [self collectionSelect:NO];
  419. }
  420. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  421. {
  422. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  423. }
  424. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  425. {
  426. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  427. }
  428. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  429. {
  430. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  431. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  432. return CGSizeMake(collectionView.frame.size.width / 5.3f, collectionView.frame.size.width / 5.3f);
  433. else
  434. return CGSizeMake(collectionView.frame.size.width / 7.3f, collectionView.frame.size.width / 7.3f);
  435. }
  436. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  437. {
  438. if ([_sectionDataSource.sections count] - 1 == section)
  439. return CGSizeMake(collectionView.frame.size.width, 50);
  440. return CGSizeZero;
  441. }
  442. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  443. {
  444. if (kind == UICollectionElementKindSectionHeader) {
  445. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  446. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  447. [self getGeoLocationForSection:indexPath.section];
  448. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  449. titleLabel.textColor = COLOR_TEXT_ANTHRACITE;
  450. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  451. return headerView;
  452. }
  453. if (kind == UICollectionElementKindSectionFooter) {
  454. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  455. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  456. titleLabel.textColor = [UIColor grayColor];
  457. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  458. return footerView;
  459. }
  460. return nil;
  461. }
  462. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  463. {
  464. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  465. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  466. UIVisualEffectView *effect = [cell viewWithTag:200];
  467. UIImageView *checked = [cell viewWithTag:300];
  468. checked.image = [UIImage imageNamed:image_checked];
  469. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  470. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  471. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  472. // Image
  473. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  474. imageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  475. if (imageView.image == nil) {
  476. // insert Image
  477. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  478. imageView.image = image;
  479. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  480. }
  481. } else {
  482. // Thumbnail not present
  483. imageView.image = [UIImage imageNamed:image_photosDownload];
  484. if (metadata.thumbnailExists)
  485. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  486. }
  487. // Cheched
  488. if (cell.selected) {
  489. checked.hidden = NO;
  490. effect.hidden = NO;
  491. effect.alpha = 0.4;
  492. } else {
  493. checked.hidden = YES;
  494. effect.hidden = YES;
  495. }
  496. return cell;
  497. }
  498. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  499. {
  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. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  504. if (_cellEditing) {
  505. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  506. } else {
  507. if ([self shouldPerformSegue])
  508. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  509. }
  510. }
  511. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  512. {
  513. if (_cellEditing == NO)
  514. return;
  515. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  516. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  517. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  518. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  519. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  520. }
  521. #pragma --------------------------------------------------------------------------------------------
  522. #pragma mark ===== Navigation ====
  523. #pragma --------------------------------------------------------------------------------------------
  524. - (BOOL)shouldPerformSegue
  525. {
  526. // Test
  527. // Background ? exit
  528. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  529. return NO;
  530. // Not in first plain ? exit
  531. if (self.view.window == NO)
  532. return NO;
  533. // Collapsed but in first plain in detail exit
  534. if (self.splitViewController.isCollapsed)
  535. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  536. return NO;
  537. // Video running exit
  538. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  539. return NO;
  540. // ok perform segue
  541. return YES;
  542. }
  543. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  544. {
  545. id controller = segue.destinationViewController;
  546. if ([controller isKindOfClass:[UINavigationController class]]) {
  547. UINavigationController *navigationController = controller;
  548. self.detailViewController = (CCDetail *)navigationController.topViewController;
  549. } else {
  550. self.detailViewController = segue.destinationViewController;
  551. }
  552. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  553. for (NSString *fileID in _sectionDataSource.allFileID) {
  554. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  555. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  556. [allRecordsDataSourceImagesVideos addObject:metadata];
  557. }
  558. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  559. self.detailViewController.metadataDetail = _metadata;
  560. self.detailViewController.dateFilterQuery = _metadata.date;
  561. self.detailViewController.isCameraUpload = YES;
  562. [self.detailViewController setTitle:_metadata.fileNamePrint];
  563. }
  564. #pragma --------------------------------------------------------------------------------------------
  565. #pragma mark ====== --- Camera Upload --- ======
  566. #pragma --------------------------------------------------------------------------------------------
  567. #pragma --------------------------------------------------------------------------------------------
  568. #pragma mark === initStateCameraUpload ===
  569. #pragma --------------------------------------------------------------------------------------------
  570. - (void)initStateCameraUpload:(NSNotification *)notification
  571. {
  572. int afterDelay = 0;
  573. if (notification.object)
  574. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  575. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  576. }
  577. - (void)initStateCameraUpload
  578. {
  579. //if (_AutomaticCameraUploadInProgress)
  580. // return;
  581. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  582. [self setupCameraUpload];
  583. if([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount])
  584. [self checkIfLocationIsEnabled];
  585. } else {
  586. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  587. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  588. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  589. }
  590. }
  591. #pragma --------------------------------------------------------------------------------------------
  592. #pragma mark === Camera Upload & Full ===
  593. #pragma --------------------------------------------------------------------------------------------
  594. - (void)setupCameraUpload
  595. {
  596. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  597. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  598. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  599. [self uploadNewAssets];
  600. } else {
  601. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  602. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  603. [[CCManageLocation sharedSingleton] 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. - (void)setupCameraUploadFull
  613. {
  614. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  615. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  616. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  617. [self uploadFullAssets];
  618. } else {
  619. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  620. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  621. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  622. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  623. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  624. delegate:nil
  625. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  626. otherButtonTitles:nil];
  627. [alert show];
  628. }
  629. }
  630. #pragma --------------------------------------------------------------------------------------------
  631. #pragma mark === Location ===
  632. #pragma --------------------------------------------------------------------------------------------
  633. - (BOOL)checkIfLocationIsEnabled
  634. {
  635. [CCManageLocation sharedSingleton].delegate = self;
  636. if ([CLLocationManager locationServicesEnabled]) {
  637. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  638. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  639. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  640. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  641. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  642. } else {
  643. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  644. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  645. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  646. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  647. delegate:nil
  648. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  649. otherButtonTitles:nil];
  650. [alert show];
  651. } else {
  652. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  653. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  654. delegate:nil
  655. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  656. otherButtonTitles:nil];
  657. [alert show];
  658. }
  659. }
  660. } else {
  661. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  662. [CCCoreData setCameraUploadBackground:YES activeAccount:app.activeAccount];
  663. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  664. } else {
  665. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  666. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  667. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  668. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  669. delegate:nil
  670. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  671. otherButtonTitles:nil];
  672. [alert show];
  673. }
  674. }
  675. } else {
  676. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  677. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  678. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  679. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  680. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  681. delegate:nil
  682. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  683. otherButtonTitles:nil];
  684. [alert show];
  685. } else {
  686. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  687. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  688. delegate:nil
  689. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  690. otherButtonTitles:nil];
  691. [alert show];
  692. }
  693. }
  694. return [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount];
  695. }
  696. - (void)statusAuthorizationLocationChanged
  697. {
  698. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  699. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  700. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  701. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  702. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  703. } failureBlock:^(NSError *error) {
  704. }];
  705. }
  706. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  707. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  708. if ([CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  709. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  710. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  711. }
  712. } else {
  713. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  714. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  715. delegate:nil
  716. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  717. otherButtonTitles:nil];
  718. [alert show];
  719. }
  720. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  721. if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  722. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  723. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  724. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  725. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  726. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  727. delegate:nil
  728. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  729. otherButtonTitles:nil];
  730. [alert show];
  731. } else {
  732. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  733. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  734. delegate:nil
  735. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  736. otherButtonTitles:nil];
  737. [alert show];
  738. }
  739. }
  740. }
  741. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  742. [CCManageLocation sharedSingleton].firstChangeAuthorizationDone = YES;
  743. }
  744. }
  745. }
  746. - (void)changedLocation
  747. {
  748. //Verifica
  749. [[CCNetworking sharedNetworking] automaticDownloadInError];
  750. [[CCNetworking sharedNetworking] automaticUploadInError];
  751. // solo in background
  752. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount] && [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount ] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  753. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  754. //check location
  755. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  756. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  757. [self uploadNewAssets];
  758. }
  759. } else {
  760. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  761. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  762. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  763. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  764. }
  765. }
  766. }
  767. #pragma --------------------------------------------------------------------------------------------
  768. #pragma mark ===== Upload Assets : NEW & FULL ====
  769. #pragma --------------------------------------------------------------------------------------------
  770. - (void)uploadNewAssets
  771. {
  772. [self uploadAssetsNewAndFull:NO];
  773. }
  774. - (void)uploadFullAssets
  775. {
  776. [self uploadAssetsNewAndFull:YES];
  777. }
  778. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  779. {
  780. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  781. NSMutableArray *newItemsToUpload;
  782. // Check Asset : NEW or FULL
  783. if (assetsFull) {
  784. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  785. } else {
  786. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  787. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  788. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  789. }
  790. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  791. if ([newItemsToUpload count] == 0)
  792. return;
  793. // Activity
  794. [CCCoreData addActivityFile:@"" action:k_activityDebugActionAutomaticUpload note:[NSString stringWithFormat:@"Number : %lu", [newItemsToUpload count]] type:k_activityTypeInfo verbose:k_activityVerboseDebug account:app.activeAccount];
  795. // STOP new request : initStateCameraUpload
  796. //_AutomaticCameraUploadInProgress = YES;
  797. // Disable idle timer
  798. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  799. if (!_hud) _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  800. if (assetsFull)
  801. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  802. else
  803. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  804. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  805. if (assetsFull)
  806. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  807. else
  808. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  809. });
  810. }
  811. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  812. {
  813. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  814. }
  815. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  816. {
  817. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  818. }
  819. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  820. {
  821. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  822. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  823. BOOL createSubfolders = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  824. // Conversion from ALAsset -to-> PHAsset
  825. for (ALAsset *asset in newItemsToUpload) {
  826. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  827. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  828. PHAsset *asset = [fetchResult firstObject];
  829. [newItemsPHAssetToUpload addObject:asset];
  830. }
  831. // verify/create folder Camera Upload, if error exit
  832. if(![self automaticCreateFolder:folderPhotos]) {
  833. NSString *description = NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil);
  834. // Full Upload ?
  835. if (assetsFull)
  836. [app messageNotification:@"_error_" description:description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  837. // START new request : initStateCameraUpload
  838. //_AutomaticCameraUploadInProgress = NO;
  839. // Activity
  840. [CCCoreData addActivityFile:@"" action:k_activityDebugActionAutomaticUpload note:description type:k_activityTypeFailure verbose:k_activityVerboseDebug account:app.activeAccount];
  841. return;
  842. }
  843. // Use subfolders verify/create subfolder, if error exit
  844. if (createSubfolders) {
  845. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:newItemsPHAssetToUpload]) {
  846. if (![self automaticCreateFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  847. [self endLoadingAssets];
  848. if (assetsFull)
  849. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  850. // Activity
  851. [CCCoreData addActivityFile:@"" action:k_activityDebugActionAutomaticUpload note:NSLocalizedString(@"_error_createsubfolders_upload_",nil) type:k_activityTypeFailure verbose:k_activityVerboseDebug account:app.activeAccount];
  852. return;
  853. }
  854. }
  855. }
  856. for (PHAsset *asset in newItemsPHAssetToUpload) {
  857. NSString *serverUrl;
  858. NSDate *assetDate = asset.creationDate;
  859. PHAssetMediaType assetMediaType = asset.mediaType;
  860. NSString *session;
  861. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  862. // Select type of session
  863. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  864. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  865. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  866. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  867. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  868. [formatter setDateFormat:@"yyyy"];
  869. NSString *yearString = [formatter stringFromDate:assetDate];
  870. [formatter setDateFormat:@"MM"];
  871. NSString *monthString = [formatter stringFromDate:assetDate];
  872. if (createSubfolders)
  873. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  874. else
  875. serverUrl = folderPhotos;
  876. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  877. metadataNet.action = actionUploadAsset;
  878. metadataNet.identifier = asset.localIdentifier;
  879. if (assetsFull) {
  880. metadataNet.selector = selectorUploadAutomaticAll;
  881. metadataNet.selectorPost = selectorUploadRemovePhoto;
  882. metadataNet.priority = NSOperationQueuePriorityLow;
  883. } else {
  884. metadataNet.selector = selectorUploadAutomatic;
  885. metadataNet.selectorPost = nil;
  886. metadataNet.priority = NSOperationQueuePriorityNormal;
  887. }
  888. metadataNet.fileName = fileName;
  889. metadataNet.serverUrl = serverUrl;
  890. metadataNet.session = session;
  891. metadataNet.taskStatus = k_taskStatusResume;
  892. [CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount];
  893. // Activity
  894. NSString *media = @"";
  895. if (assetMediaType == PHAssetMediaTypeImage) media = @"Image";
  896. if (assetMediaType == PHAssetMediaTypeVideo) media = @"Video";
  897. [CCCoreData addActivityFile:fileName action:k_activityDebugActionAutomaticUpload note:[NSString stringWithFormat:@"Add TableAutomaticUpload on Session : %@, Set Data asset %@", session, media] type:k_activityTypeInfo verbose:k_activityVerboseDebug account:app.activeAccount];
  898. // Upldate Camera Upload data
  899. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  900. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  901. }
  902. // start upload
  903. if (assetsFull)
  904. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  905. else
  906. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  907. // end loading
  908. [self endLoadingAssets];
  909. // Update icon badge number
  910. [app updateApplicationIconBadgeNumber];
  911. }
  912. - (BOOL)automaticCreateFolder:(NSString *)folderPathName
  913. {
  914. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  915. __block BOOL noError = YES;
  916. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  917. [communication setCredentialsWithUser:app.activeUser andPassword:app.activePassword];
  918. [communication setUserAgent:[CCUtility getUserAgent]];
  919. [communication readFile:folderPathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  920. dispatch_semaphore_signal(semaphore);
  921. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  922. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:app.hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  923. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:[CCUtility deletingLastPathComponentFromServerUrl:folderPathName] directoryID:nil];
  924. dispatch_semaphore_signal(semaphore);
  925. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  926. noError = NO;
  927. dispatch_semaphore_signal(semaphore);
  928. } errorBeforeRequest:^(NSError *error) {
  929. noError = NO;
  930. dispatch_semaphore_signal(semaphore);
  931. }];
  932. }];
  933. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  934. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  935. return noError;
  936. }
  937. -(void)endLoadingAssets
  938. {
  939. [_hud hideHud];
  940. // START new request : initStateCameraUpload
  941. //_AutomaticCameraUploadInProgress = NO;
  942. // Enable idle timer
  943. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  944. }
  945. @end