CCPhotosCameraUpload.m 55 KB

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