CCPhotosCameraUpload.m 53 KB

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