CCPhotosCameraUpload.m 51 KB

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