CCPhotosCameraUpload.m 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. //
  2. // CCPhotosCameraUpload.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCPhotosCameraUpload.h"
  24. #import "AppDelegate.h"
  25. #ifdef CUSTOM_BUILD
  26. #import "CustomSwift.h"
  27. #else
  28. #import "Nextcloud-Swift.h"
  29. #endif
  30. @interface CCPhotosCameraUpload () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  31. {
  32. CCMetadata *_metadata;
  33. BOOL _cellEditing;
  34. NSMutableArray *_queueMetadatas;
  35. NSMutableArray *_selectedMetadatas;
  36. NSUInteger _numSelectedMetadatas;
  37. CCSectionDataSourceMetadata *_sectionDataSource;
  38. CCHud *_hud;
  39. }
  40. @end
  41. @implementation CCPhotosCameraUpload
  42. #pragma --------------------------------------------------------------------------------------------
  43. #pragma mark ===== Init =====
  44. #pragma --------------------------------------------------------------------------------------------
  45. - (id)initWithCoder:(NSCoder *)aDecoder
  46. {
  47. if (self = [super initWithCoder:aDecoder]) {
  48. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initStateCameraUpload:) name:@"initStateCameraUpload" object:nil];
  49. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCameraUploadFull) name:@"setupCameraUploadFull" object:nil];
  50. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  51. app.activePhotosCameraUpload = self;
  52. }
  53. return self;
  54. }
  55. #pragma --------------------------------------------------------------------------------------------
  56. #pragma mark ===== View =====
  57. #pragma --------------------------------------------------------------------------------------------
  58. - (void)viewDidLoad
  59. {
  60. [super viewDidLoad];
  61. _queueMetadatas = [[NSMutableArray alloc] init];
  62. _selectedMetadatas = [[NSMutableArray alloc] init];
  63. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  64. // empty Data Source
  65. self.collectionView.emptyDataSetDelegate = self;
  66. self.collectionView.emptyDataSetSource = self;
  67. [self reloadDatasource];
  68. }
  69. // Apparirà
  70. - (void)viewWillAppear:(BOOL)animated
  71. {
  72. [super viewWillAppear:animated];
  73. // Color
  74. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  75. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  76. // Plus Button
  77. [app plusButtonVisibile:true];
  78. }
  79. // E' arrivato
  80. - (void)viewDidAppear:(BOOL)animated
  81. {
  82. [super viewDidAppear:animated];
  83. [self reloadDatasource];
  84. }
  85. - (void)didReceiveMemoryWarning
  86. {
  87. [super didReceiveMemoryWarning];
  88. // Dispose of any resources that can be recreated.
  89. }
  90. #pragma --------------------------------------------------------------------------------------------
  91. #pragma mark ====== Photos ======
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== Gestione Grafica Window =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)setUINavigationBarDefault
  97. {
  98. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  99. // select
  100. UIImage *icon = [UIImage imageNamed:image_seleziona];
  101. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  102. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  103. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  104. } else {
  105. self.navigationItem.rightBarButtonItems = nil;
  106. }
  107. self.navigationItem.leftBarButtonItem = nil;
  108. // Title
  109. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  110. }
  111. - (void)setUINavigationBarSelected
  112. {
  113. UIImage *icon;
  114. icon = [UIImage imageNamed:image_deleteSelectedFiles];
  115. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  116. icon = [UIImage imageNamed:image_openSelectedFiles];
  117. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  118. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  119. self.navigationItem.leftBarButtonItem = leftButton;
  120. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  121. // Title
  122. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  123. }
  124. - (void)collectionSelect:(BOOL)edit
  125. {
  126. [self.collectionView setAllowsMultipleSelection:edit];
  127. _cellEditing = edit;
  128. if (edit)
  129. [self setUINavigationBarSelected];
  130. else
  131. [self setUINavigationBarDefault];
  132. }
  133. - (void)collectionSelectYES
  134. {
  135. [self collectionSelect:YES];
  136. }
  137. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(CCMetadata *)metadata
  138. {
  139. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  140. UIVisualEffectView *effect = [cell viewWithTag:200];
  141. UIImageView *checked = [cell viewWithTag:300];
  142. if (select) {
  143. effect.hidden = NO;
  144. effect.alpha = 0.4;
  145. checked.hidden = NO;
  146. [_selectedMetadatas addObject:metadata];
  147. } else {
  148. effect.hidden = YES;
  149. checked.hidden = YES;
  150. [_selectedMetadatas removeObject:metadata];
  151. }
  152. // Title
  153. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  154. }
  155. - (void)scrollToTop
  156. {
  157. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  158. }
  159. - (void)getGeoLocationForSection:(NSInteger)section
  160. {
  161. NSString *addLocation = @"";
  162. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  163. for (NSString *fileID in fileIDsForKey) {
  164. TableLocalFile *localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  165. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  166. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  167. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  168. }
  169. }
  170. }
  171. #pragma --------------------------------------------------------------------------------------------
  172. #pragma mark ==== Photo Library Change Observer ====
  173. #pragma --------------------------------------------------------------------------------------------
  174. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  175. {
  176. /*
  177. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  178. if (collectionChanges) {
  179. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  180. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  181. [self uploadNewAssets];
  182. });
  183. }
  184. */
  185. }
  186. #pragma --------------------------------------------------------------------------------------------
  187. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  188. #pragma --------------------------------------------------------------------------------------------
  189. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  190. {
  191. return YES;
  192. }
  193. - (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
  194. {
  195. return 0.0f;
  196. }
  197. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  198. {
  199. return [UIColor whiteColor];
  200. }
  201. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  202. {
  203. return [UIImage imageNamed:image_brandBackgroundLite];
  204. }
  205. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  206. {
  207. NSString *text = [NSString stringWithFormat:@"%@", @""];
  208. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:COLOR_BRAND};
  209. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  210. }
  211. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  212. {
  213. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  214. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  215. paragraph.alignment = NSTextAlignmentCenter;
  216. NSString *text;
  217. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount])
  218. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  219. else
  220. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_camera_upload_view_", nil)];
  221. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  222. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  223. }
  224. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  225. {
  226. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount] == NO) {
  227. return [CCUtility drawText:NSLocalizedString(@"_activate_camera_upload_", nil) inImage:[UIImage imageNamed:image_buttonBlu] colorText:[UIColor whiteColor]];
  228. } else return nil;
  229. }
  230. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  231. {
  232. CCManageCameraUpload *viewController = [[CCManageCameraUpload alloc] initWithNibName:nil bundle:nil];
  233. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  234. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  235. [self presentViewController:navigationController animated:YES completion:nil];
  236. }
  237. #pragma --------------------------------------------------------------------------------------------
  238. #pragma mark ===== openSelectedFiles =====
  239. #pragma--------------------------------------------------------------------------------------------
  240. - (void)openSelectedFiles
  241. {
  242. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  243. for (CCMetadata *metadata in _selectedMetadatas) {
  244. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  245. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  246. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  247. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  248. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  249. [dataToShare addObject:data];
  250. }
  251. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  252. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  253. }
  254. }
  255. }
  256. if ([dataToShare count] > 0) {
  257. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  258. // iPad
  259. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  260. self.navigationItem.leftBarButtonItem.enabled = NO;
  261. self.navigationItem.rightBarButtonItem.enabled = NO;
  262. [self presentViewController:activityViewController animated:YES completion:^{
  263. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  264. self.navigationItem.leftBarButtonItem.enabled = YES;
  265. self.navigationItem.rightBarButtonItem.enabled = YES;
  266. if (completed) {
  267. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  268. if ([obj isKindOfClass:[UIImage class]])
  269. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  270. if ([obj isKindOfClass:[NSURL class]])
  271. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  272. }];
  273. [self performSelector:@selector(reloadCollection) withObject:nil];
  274. }
  275. }];
  276. }];
  277. }
  278. }
  279. #pragma --------------------------------------------------------------------------------------------
  280. #pragma mark ===== Download =====
  281. #pragma--------------------------------------------------------------------------------------------
  282. - (void)downloadFileFailure:(NSInteger)errorCode
  283. {
  284. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  285. }
  286. - (void)downloadFileSuccess:(CCMetadata *)metadata
  287. {
  288. NSIndexPath *indexPath;
  289. BOOL existsIcon = NO;
  290. if (metadata.fileID) {
  291. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  292. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  293. }
  294. if (indexPath && existsIcon) {
  295. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  296. if (cell) {
  297. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  298. UIVisualEffectView *effect = [cell viewWithTag:200];
  299. UIImageView *checked = [cell viewWithTag:300];
  300. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  301. effect.hidden = YES;
  302. checked.hidden = YES;
  303. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  304. }
  305. }
  306. }
  307. #pragma --------------------------------------------------------------------------------------------
  308. #pragma mark ===== Delete =====
  309. #pragma--------------------------------------------------------------------------------------------
  310. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  311. {
  312. [self deleteFileOrFolderSuccess:metadataNet];
  313. }
  314. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  315. {
  316. [_queueMetadatas removeObject:metadataNet.selector];
  317. if ([_queueMetadatas count] == 0) {
  318. [_hud hideHud];
  319. if ([_selectedMetadatas count] > 0) {
  320. [_selectedMetadatas removeObjectAtIndex:0];
  321. if ([_selectedMetadatas count] > 0) {
  322. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  323. } else {
  324. [self reloadDatasource];
  325. }
  326. } else {
  327. [self reloadDatasource];
  328. }
  329. }
  330. }
  331. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  332. {
  333. if (metadata.cryptated) {
  334. [_queueMetadatas addObject:selectorDeleteCrypto];
  335. [_queueMetadatas addObject:selectorDeletePlist];
  336. } else {
  337. [_queueMetadatas addObject:selectorDelete];
  338. }
  339. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  340. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  341. }
  342. - (void)deleteSelectedFiles
  343. {
  344. [_queueMetadatas removeAllObjects];
  345. _numSelectedMetadatas = [_selectedMetadatas count];
  346. if ([_selectedMetadatas count] == 0)
  347. return;
  348. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  349. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  350. style:UIAlertActionStyleDestructive
  351. handler:^(UIAlertAction *action) {
  352. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  353. }]];
  354. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  355. style:UIAlertActionStyleCancel
  356. handler:^(UIAlertAction *action) {
  357. [alertController dismissViewControllerAnimated:YES completion:nil];
  358. }]];
  359. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  360. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  361. [alertController.view layoutIfNeeded];
  362. [self presentViewController:alertController animated:YES completion:NULL];
  363. }
  364. #pragma --------------------------------------------------------------------------------------------
  365. #pragma mark ==== Download Thumbnail Delegate ====
  366. #pragma --------------------------------------------------------------------------------------------
  367. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  368. {
  369. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  370. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  371. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  372. }
  373. - (void)triggerProgressTask:(NSNotification *)notification
  374. {
  375. NSDictionary *dict = notification.userInfo;
  376. float progress = [[dict valueForKey:@"progress"] floatValue];
  377. if (progress == 0)
  378. [self.navigationController cancelCCProgress];
  379. else
  380. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:COLOR_NAVIGATIONBAR_PROGRESS];
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ==== Collection ====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)reloadDatasourceForced
  386. {
  387. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  388. [self reloadDatasource];
  389. }
  390. - (void)reloadDatasource
  391. {
  392. // test
  393. if (app.activeAccount.length == 0)
  394. return;
  395. NSString *serverUrl = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  396. if (_sectionDataSource) {
  397. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  398. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  399. dispatch_async(dispatch_get_main_queue(), ^{
  400. [self reloadCollection];
  401. });
  402. });
  403. } else {
  404. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  405. [self reloadCollection];
  406. }
  407. }
  408. - (void)reloadCollection
  409. {
  410. [self.collectionView reloadData];
  411. [_selectedMetadatas removeAllObjects];
  412. [self collectionSelect:NO];
  413. }
  414. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  415. {
  416. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  417. }
  418. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  419. {
  420. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  421. }
  422. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  423. {
  424. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  425. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  426. return CGSizeMake(collectionView.frame.size.width / 5.3f, collectionView.frame.size.width / 5.3f);
  427. else
  428. return CGSizeMake(collectionView.frame.size.width / 7.3f, collectionView.frame.size.width / 7.3f);
  429. }
  430. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  431. {
  432. if ([_sectionDataSource.sections count] - 1 == section)
  433. return CGSizeMake(collectionView.frame.size.width, 50);
  434. return CGSizeZero;
  435. }
  436. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  437. {
  438. if (kind == UICollectionElementKindSectionHeader) {
  439. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  440. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  441. [self getGeoLocationForSection:indexPath.section];
  442. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  443. titleLabel.textColor = COLOR_TEXT_ANTHRACITE;
  444. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  445. return headerView;
  446. }
  447. if (kind == UICollectionElementKindSectionFooter) {
  448. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  449. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  450. titleLabel.textColor = [UIColor grayColor];
  451. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  452. return footerView;
  453. }
  454. return nil;
  455. }
  456. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  457. {
  458. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  459. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  460. UIVisualEffectView *effect = [cell viewWithTag:200];
  461. UIImageView *checked = [cell viewWithTag:300];
  462. checked.image = [UIImage imageNamed:image_checked];
  463. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  464. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  465. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  466. // Image
  467. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  468. imageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  469. if (imageView.image == nil) {
  470. // insert Image
  471. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  472. imageView.image = image;
  473. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  474. }
  475. } else {
  476. // Thumbnail not present
  477. imageView.image = [UIImage imageNamed:image_file_photo];
  478. if (metadata.thumbnailExists)
  479. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  480. }
  481. // Cheched
  482. if (cell.selected) {
  483. checked.hidden = NO;
  484. effect.hidden = NO;
  485. effect.alpha = 0.4;
  486. } else {
  487. checked.hidden = YES;
  488. effect.hidden = YES;
  489. }
  490. return cell;
  491. }
  492. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  493. {
  494. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  495. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  496. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  497. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  498. if (_cellEditing) {
  499. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  500. } else {
  501. if ([self shouldPerformSegue])
  502. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  503. }
  504. }
  505. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  506. {
  507. if (_cellEditing == NO)
  508. return;
  509. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  510. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  511. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  512. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  513. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  514. }
  515. #pragma --------------------------------------------------------------------------------------------
  516. #pragma mark ===== Navigation ====
  517. #pragma --------------------------------------------------------------------------------------------
  518. - (BOOL)shouldPerformSegue
  519. {
  520. // Test
  521. // Background ? exit
  522. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  523. return NO;
  524. // Not in first plain ? exit
  525. if (self.view.window == NO)
  526. return NO;
  527. // Collapsed but in first plain in detail exit
  528. if (self.splitViewController.isCollapsed)
  529. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  530. return NO;
  531. // Video running exit
  532. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  533. return NO;
  534. // ok perform segue
  535. return YES;
  536. }
  537. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  538. {
  539. id controller = segue.destinationViewController;
  540. if ([controller isKindOfClass:[UINavigationController class]]) {
  541. UINavigationController *navigationController = controller;
  542. self.detailViewController = (CCDetail *)navigationController.topViewController;
  543. } else {
  544. self.detailViewController = segue.destinationViewController;
  545. }
  546. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  547. for (NSString *fileID in _sectionDataSource.allFileID) {
  548. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  549. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  550. [allRecordsDataSourceImagesVideos addObject:metadata];
  551. }
  552. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  553. self.detailViewController.metadataDetail = _metadata;
  554. self.detailViewController.dateFilterQuery = _metadata.date;
  555. self.detailViewController.isCameraUpload = YES;
  556. [self.detailViewController setTitle:_metadata.fileNamePrint];
  557. }
  558. #pragma --------------------------------------------------------------------------------------------
  559. #pragma mark === initStateCameraUpload ===
  560. #pragma --------------------------------------------------------------------------------------------
  561. - (void)initStateCameraUpload:(NSNotification *)notification
  562. {
  563. int afterDelay = 0;
  564. if (notification.object)
  565. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  566. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  567. }
  568. - (void)initStateCameraUpload
  569. {
  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. // Is loading new Asset ?
  772. if (app.automaticCheckAssetInProgress)
  773. return;
  774. // Check Asset : NEW or FULL
  775. if (assetsFull) {
  776. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  777. } else {
  778. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  779. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  780. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  781. }
  782. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  783. if ([newItemsToUpload count] == 0)
  784. return;
  785. // STOP
  786. app.automaticCheckAssetInProgress = YES;
  787. // Disable idle timer
  788. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  789. if (assetsFull) {
  790. if (!_hud)
  791. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  792. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  793. }
  794. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  795. if (assetsFull)
  796. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  797. else
  798. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  799. });
  800. }
  801. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  802. {
  803. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  804. }
  805. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  806. {
  807. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  808. }
  809. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  810. {
  811. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  812. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  813. BOOL useSubFolder = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  814. // Conversion from ALAsset -to-> PHAsset
  815. for (ALAsset *asset in newItemsToUpload) {
  816. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  817. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  818. PHAsset *asset = [fetchResult firstObject];
  819. [newItemsPHAssetToUpload addObject:asset];
  820. NSLog(@"Convert url %@", url);
  821. }
  822. // Create the folder for Photos & if request the subfolders
  823. if(![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutomaticAll]) {
  824. [self endLoadingAssets];
  825. return;
  826. }
  827. for (PHAsset *asset in newItemsPHAssetToUpload) {
  828. NSString *serverUrl;
  829. NSDate *assetDate = asset.creationDate;
  830. PHAssetMediaType assetMediaType = asset.mediaType;
  831. NSString *session;
  832. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  833. // Select type of session
  834. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  835. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  836. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  837. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  838. NSDateFormatter *formatter = [NSDateFormatter new];
  839. [formatter setDateFormat:@"yyyy"];
  840. NSString *yearString = [formatter stringFromDate:assetDate];
  841. [formatter setDateFormat:@"MM"];
  842. NSString *monthString = [formatter stringFromDate:assetDate];
  843. if (useSubFolder)
  844. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  845. else
  846. serverUrl = folderPhotos;
  847. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  848. metadataNet.action = actionUploadAsset;
  849. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  850. if (assetsFull) {
  851. metadataNet.selector = selectorUploadAutomaticAll;
  852. metadataNet.selectorPost = selectorUploadRemovePhoto;
  853. metadataNet.priority = NSOperationQueuePriorityLow;
  854. } else {
  855. metadataNet.selector = selectorUploadAutomatic;
  856. metadataNet.selectorPost = nil;
  857. metadataNet.priority = NSOperationQueuePriorityNormal;
  858. }
  859. metadataNet.fileName = fileName;
  860. metadataNet.serverUrl = serverUrl;
  861. metadataNet.session = session;
  862. metadataNet.taskStatus = k_taskStatusResume;
  863. if (![CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount]) {
  864. [CCCoreData addActivityClient:fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutomaticUpload selector:metadataNet.selector note:@"File already present in Table automatic Upload" type:k_activityTypeInfo verbose:k_activityVerboseHigh account:app.activeAccount activeUrl:app.activeUrl];
  865. [self endLoadingAssets];
  866. return;
  867. }
  868. // Activity
  869. NSString *media = @"";
  870. if (assetMediaType == PHAssetMediaTypeImage) media = @"Image";
  871. if (assetMediaType == PHAssetMediaTypeVideo) media = @"Video";
  872. [CCCoreData addActivityClient:fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutomaticUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Automatic Upload on Session: %@, Media Type: %@, Asset Data: %@", session, media, [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh account:app.activeAccount activeUrl:app.activeUrl];
  873. // Upldate Camera Upload data
  874. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  875. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  876. }
  877. // end loading
  878. [self endLoadingAssets];
  879. // Update icon badge number
  880. [app updateApplicationIconBadgeNumber];
  881. }
  882. -(void)endLoadingAssets
  883. {
  884. [_hud hideHud];
  885. // START
  886. app.automaticCheckAssetInProgress = NO;
  887. // Enable idle timer
  888. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  889. }
  890. @end