CCPhotosCameraUpload.m 55 KB

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