CCPhotosCameraUpload.m 55 KB

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