CCPhotosCameraUpload.m 54 KB

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