CCPhotosCameraUpload.m 53 KB

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