CCPhotosCameraUpload.m 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  52. app.activePhotosCameraUpload = self;
  53. }
  54. return self;
  55. }
  56. #pragma --------------------------------------------------------------------------------------------
  57. #pragma mark ===== View =====
  58. #pragma --------------------------------------------------------------------------------------------
  59. - (void)viewDidLoad
  60. {
  61. [super viewDidLoad];
  62. _queueMetadatas = [[NSMutableArray alloc] init];
  63. _selectedMetadatas = [[NSMutableArray alloc] init];
  64. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  65. // empty Data Source
  66. self.collectionView.emptyDataSetDelegate = self;
  67. self.collectionView.emptyDataSetSource = self;
  68. [self reloadDatasource];
  69. }
  70. // Apparirà
  71. - (void)viewWillAppear:(BOOL)animated
  72. {
  73. [super viewWillAppear:animated];
  74. // Color
  75. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  76. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  77. // Plus Button
  78. [app plusButtonVisibile:true];
  79. }
  80. // E' arrivato
  81. - (void)viewDidAppear:(BOOL)animated
  82. {
  83. [super viewDidAppear:animated];
  84. [self reloadDatasource];
  85. }
  86. - (void)changeTheming
  87. {
  88. if (self.isViewLoaded && self.view.window)
  89. [app changeTheming:self];
  90. [self.collectionView reloadData];
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== Gestione Grafica Window =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)setUINavigationBarDefault
  96. {
  97. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  98. // select
  99. UIImage *icon = [UIImage imageNamed:image_seleziona];
  100. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  101. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  102. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  103. } else {
  104. self.navigationItem.rightBarButtonItems = nil;
  105. }
  106. self.navigationItem.leftBarButtonItem = nil;
  107. // Title
  108. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  109. }
  110. - (void)setUINavigationBarSelected
  111. {
  112. UIImage *icon;
  113. icon = [UIImage imageNamed:image_deleteSelectedFiles];
  114. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  115. icon = [UIImage imageNamed:image_openSelectedFiles];
  116. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  117. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  118. self.navigationItem.leftBarButtonItem = leftButton;
  119. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  120. // Title
  121. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  122. }
  123. - (void)collectionSelect:(BOOL)edit
  124. {
  125. [self.collectionView setAllowsMultipleSelection:edit];
  126. _cellEditing = edit;
  127. if (edit)
  128. [self setUINavigationBarSelected];
  129. else
  130. [self setUINavigationBarDefault];
  131. }
  132. - (void)collectionSelectYES
  133. {
  134. [self collectionSelect:YES];
  135. }
  136. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(CCMetadata *)metadata
  137. {
  138. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  139. UIVisualEffectView *effect = [cell viewWithTag:200];
  140. UIImageView *checked = [cell viewWithTag:300];
  141. if (select) {
  142. effect.hidden = NO;
  143. effect.alpha = 0.4;
  144. checked.hidden = NO;
  145. [_selectedMetadatas addObject:metadata];
  146. } else {
  147. effect.hidden = YES;
  148. checked.hidden = YES;
  149. [_selectedMetadatas removeObject:metadata];
  150. }
  151. // Title
  152. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  153. }
  154. - (void)scrollToTop
  155. {
  156. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  157. }
  158. - (void)getGeoLocationForSection:(NSInteger)section
  159. {
  160. NSString *addLocation = @"";
  161. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  162. for (NSString *fileID in fileIDsForKey) {
  163. TableLocalFile *localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  164. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  165. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  166. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  167. }
  168. }
  169. }
  170. #pragma --------------------------------------------------------------------------------------------
  171. #pragma mark ==== Photo Library Change Observer ====
  172. #pragma --------------------------------------------------------------------------------------------
  173. - (void)photoLibraryDidChange:(PHChange *)changeInfo
  174. {
  175. /*
  176. PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
  177. if (collectionChanges) {
  178. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  179. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  180. [self uploadNewAssets];
  181. });
  182. }
  183. */
  184. }
  185. #pragma --------------------------------------------------------------------------------------------
  186. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  187. #pragma --------------------------------------------------------------------------------------------
  188. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  189. {
  190. return [UIColor whiteColor];
  191. }
  192. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  193. {
  194. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_photosNoRecord] color:[NCBrandColor sharedInstance].brand];
  195. }
  196. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  197. {
  198. NSString *text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  199. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  200. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  201. }
  202. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  203. {
  204. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  205. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  206. paragraph.alignment = NSTextAlignmentCenter;
  207. NSString *text;
  208. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount])
  209. text = [NSString stringWithFormat:@"%@", @"\n\n\n\n"];
  210. else
  211. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_camera_upload_view_", nil)];
  212. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  213. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  214. }
  215. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  216. {
  217. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount] == NO) {
  218. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_button] color:[NCBrandColor sharedInstance].brand];
  219. return [CCUtility drawText:NSLocalizedString(@"_activate_camera_upload_", nil) inImage:buttonImage colorText:[UIColor whiteColor]];
  220. } else return nil;
  221. }
  222. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  223. {
  224. CCManageCameraUpload *viewController = [[CCManageCameraUpload alloc] initWithNibName:nil bundle:nil];
  225. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  226. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  227. [self presentViewController:navigationController animated:YES completion:nil];
  228. }
  229. #pragma --------------------------------------------------------------------------------------------
  230. #pragma mark ===== openSelectedFiles =====
  231. #pragma--------------------------------------------------------------------------------------------
  232. - (void)openSelectedFiles
  233. {
  234. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  235. for (CCMetadata *metadata in _selectedMetadatas) {
  236. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  237. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  238. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  239. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  240. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  241. [dataToShare addObject:data];
  242. }
  243. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  244. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  245. }
  246. }
  247. }
  248. if ([dataToShare count] > 0) {
  249. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  250. // iPad
  251. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  252. self.navigationItem.leftBarButtonItem.enabled = NO;
  253. self.navigationItem.rightBarButtonItem.enabled = NO;
  254. [self presentViewController:activityViewController animated:YES completion:^{
  255. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  256. self.navigationItem.leftBarButtonItem.enabled = YES;
  257. self.navigationItem.rightBarButtonItem.enabled = YES;
  258. if (completed) {
  259. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  260. if ([obj isKindOfClass:[UIImage class]])
  261. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  262. if ([obj isKindOfClass:[NSURL class]])
  263. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  264. }];
  265. [self performSelector:@selector(reloadCollection) withObject:nil];
  266. }
  267. }];
  268. }];
  269. }
  270. }
  271. #pragma --------------------------------------------------------------------------------------------
  272. #pragma mark ===== Download =====
  273. #pragma--------------------------------------------------------------------------------------------
  274. - (void)downloadFileFailure:(NSInteger)errorCode
  275. {
  276. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  277. }
  278. - (void)downloadFileSuccess:(CCMetadata *)metadata
  279. {
  280. NSIndexPath *indexPath;
  281. BOOL existsIcon = NO;
  282. if (metadata.fileID) {
  283. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  284. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  285. }
  286. if (indexPath && existsIcon) {
  287. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  288. if (cell) {
  289. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  290. UIVisualEffectView *effect = [cell viewWithTag:200];
  291. UIImageView *checked = [cell viewWithTag:300];
  292. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  293. effect.hidden = YES;
  294. checked.hidden = YES;
  295. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  296. }
  297. }
  298. }
  299. #pragma --------------------------------------------------------------------------------------------
  300. #pragma mark ===== Delete =====
  301. #pragma--------------------------------------------------------------------------------------------
  302. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  303. {
  304. [self deleteFileOrFolderSuccess:metadataNet];
  305. }
  306. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  307. {
  308. [_queueMetadatas removeObject:metadataNet.selector];
  309. if ([_queueMetadatas count] == 0) {
  310. [_hud hideHud];
  311. if ([_selectedMetadatas count] > 0) {
  312. [_selectedMetadatas removeObjectAtIndex:0];
  313. if ([_selectedMetadatas count] > 0) {
  314. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  315. } else {
  316. [self reloadDatasource];
  317. }
  318. } else {
  319. [self reloadDatasource];
  320. }
  321. }
  322. }
  323. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  324. {
  325. if (metadata.cryptated) {
  326. [_queueMetadatas addObject:selectorDeleteCrypto];
  327. [_queueMetadatas addObject:selectorDeletePlist];
  328. } else {
  329. [_queueMetadatas addObject:selectorDelete];
  330. }
  331. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  332. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  333. }
  334. - (void)deleteSelectedFiles
  335. {
  336. [_queueMetadatas removeAllObjects];
  337. _numSelectedMetadatas = [_selectedMetadatas count];
  338. if ([_selectedMetadatas count] == 0)
  339. return;
  340. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  341. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  342. style:UIAlertActionStyleDestructive
  343. handler:^(UIAlertAction *action) {
  344. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  345. }]];
  346. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  347. style:UIAlertActionStyleCancel
  348. handler:^(UIAlertAction *action) {
  349. [alertController dismissViewControllerAnimated:YES completion:nil];
  350. }]];
  351. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  352. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  353. [alertController.view layoutIfNeeded];
  354. [self presentViewController:alertController animated:YES completion:NULL];
  355. }
  356. #pragma --------------------------------------------------------------------------------------------
  357. #pragma mark ==== Download Thumbnail Delegate ====
  358. #pragma --------------------------------------------------------------------------------------------
  359. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  360. {
  361. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  362. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  363. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  364. }
  365. - (void)triggerProgressTask:(NSNotification *)notification
  366. {
  367. NSDictionary *dict = notification.userInfo;
  368. float progress = [[dict valueForKey:@"progress"] floatValue];
  369. if (progress == 0)
  370. [self.navigationController cancelCCProgress];
  371. else
  372. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:[NCBrandColor sharedInstance].navigationBarProgress];
  373. }
  374. #pragma --------------------------------------------------------------------------------------------
  375. #pragma mark ==== Collection ====
  376. #pragma --------------------------------------------------------------------------------------------
  377. - (void)reloadDatasourceForced
  378. {
  379. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  380. [self reloadDatasource];
  381. }
  382. - (void)reloadDatasource
  383. {
  384. // test
  385. if (app.activeAccount.length == 0)
  386. return;
  387. NSString *serverUrl = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  388. if (_sectionDataSource) {
  389. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  390. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  391. dispatch_async(dispatch_get_main_queue(), ^{
  392. [self reloadCollection];
  393. });
  394. });
  395. } else {
  396. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  397. [self reloadCollection];
  398. }
  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 = [UIColor blackColor];
  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_file_photo];
  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. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  492. } else {
  493. if ([self shouldPerformSegue])
  494. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  495. }
  496. }
  497. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  498. {
  499. if (_cellEditing == NO)
  500. return;
  501. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  502. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  503. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  504. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  505. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  506. }
  507. #pragma --------------------------------------------------------------------------------------------
  508. #pragma mark ===== Navigation ====
  509. #pragma --------------------------------------------------------------------------------------------
  510. - (BOOL)shouldPerformSegue
  511. {
  512. // Test
  513. // Background ? exit
  514. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  515. return NO;
  516. // Not in first plain ? exit
  517. if (self.view.window == NO)
  518. return NO;
  519. // Collapsed but in first plain in detail exit
  520. if (self.splitViewController.isCollapsed)
  521. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  522. return NO;
  523. // Video running exit
  524. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  525. return NO;
  526. // ok perform segue
  527. return YES;
  528. }
  529. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  530. {
  531. id controller = segue.destinationViewController;
  532. if ([controller isKindOfClass:[UINavigationController class]]) {
  533. UINavigationController *navigationController = controller;
  534. self.detailViewController = (CCDetail *)navigationController.topViewController;
  535. } else {
  536. self.detailViewController = segue.destinationViewController;
  537. }
  538. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  539. for (NSString *fileID in _sectionDataSource.allFileID) {
  540. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  541. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  542. [allRecordsDataSourceImagesVideos addObject:metadata];
  543. }
  544. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  545. self.detailViewController.metadataDetail = _metadata;
  546. self.detailViewController.dateFilterQuery = _metadata.date;
  547. self.detailViewController.isCameraUpload = YES;
  548. [self.detailViewController setTitle:_metadata.fileNamePrint];
  549. }
  550. #pragma --------------------------------------------------------------------------------------------
  551. #pragma mark === initStateCameraUpload ===
  552. #pragma --------------------------------------------------------------------------------------------
  553. - (void)initStateCameraUpload:(NSNotification *)notification
  554. {
  555. int afterDelay = 0;
  556. if (notification.object)
  557. afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
  558. [self performSelector:@selector(initStateCameraUpload) withObject:nil afterDelay:afterDelay];
  559. }
  560. - (void)initStateCameraUpload
  561. {
  562. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  563. [self setupCameraUpload];
  564. if([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount])
  565. [self checkIfLocationIsEnabled];
  566. } else {
  567. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  568. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  569. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  570. }
  571. }
  572. #pragma --------------------------------------------------------------------------------------------
  573. #pragma mark === Camera Upload & Full ===
  574. #pragma --------------------------------------------------------------------------------------------
  575. - (void)setupCameraUpload
  576. {
  577. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  578. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  579. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  580. [self uploadNewAssets];
  581. } else {
  582. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  583. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  584. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  585. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  586. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  587. delegate:nil
  588. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  589. otherButtonTitles:nil];
  590. [alert show];
  591. }
  592. }
  593. - (void)setupCameraUploadFull
  594. {
  595. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  596. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  597. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  598. [self uploadFullAssets];
  599. } else {
  600. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  601. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  602. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  603. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  604. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  605. delegate:nil
  606. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  607. otherButtonTitles:nil];
  608. [alert show];
  609. }
  610. }
  611. #pragma --------------------------------------------------------------------------------------------
  612. #pragma mark === Location ===
  613. #pragma --------------------------------------------------------------------------------------------
  614. - (BOOL)checkIfLocationIsEnabled
  615. {
  616. [CCManageLocation sharedSingleton].delegate = self;
  617. if ([CLLocationManager locationServicesEnabled]) {
  618. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  619. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  620. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  621. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  622. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  623. } else {
  624. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  625. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  626. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  627. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  628. delegate:nil
  629. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  630. otherButtonTitles:nil];
  631. [alert show];
  632. } else {
  633. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  634. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  635. delegate:nil
  636. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  637. otherButtonTitles:nil];
  638. [alert show];
  639. }
  640. }
  641. } else {
  642. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  643. [CCCoreData setCameraUploadBackground:YES activeAccount:app.activeAccount];
  644. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  645. } else {
  646. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  647. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  648. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  649. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  650. delegate:nil
  651. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  652. otherButtonTitles:nil];
  653. [alert show];
  654. }
  655. }
  656. } else {
  657. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  658. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  659. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  660. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  661. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  662. delegate:nil
  663. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  664. otherButtonTitles:nil];
  665. [alert show];
  666. } else {
  667. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  668. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  669. delegate:nil
  670. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  671. otherButtonTitles:nil];
  672. [alert show];
  673. }
  674. }
  675. return [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount];
  676. }
  677. - (void)statusAuthorizationLocationChanged
  678. {
  679. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  680. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  681. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  682. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  683. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  684. } failureBlock:^(NSError *error) {
  685. }];
  686. }
  687. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  688. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  689. if ([CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  690. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  691. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  692. }
  693. } else {
  694. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  695. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  696. delegate:nil
  697. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  698. otherButtonTitles:nil];
  699. [alert show];
  700. }
  701. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  702. if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  703. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  704. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  705. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  706. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  707. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  708. delegate:nil
  709. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  710. otherButtonTitles:nil];
  711. [alert show];
  712. } else {
  713. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  714. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  715. delegate:nil
  716. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  717. otherButtonTitles:nil];
  718. [alert show];
  719. }
  720. }
  721. }
  722. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  723. [CCManageLocation sharedSingleton].firstChangeAuthorizationDone = YES;
  724. }
  725. }
  726. }
  727. - (void)changedLocation
  728. {
  729. //Verifica
  730. [[CCNetworking sharedNetworking] automaticDownloadInError];
  731. [[CCNetworking sharedNetworking] automaticUploadInError];
  732. // solo in background
  733. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount] && [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount ] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  734. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  735. //check location
  736. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  737. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  738. [self uploadNewAssets];
  739. }
  740. } else {
  741. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  742. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  743. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  744. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  745. }
  746. }
  747. }
  748. #pragma --------------------------------------------------------------------------------------------
  749. #pragma mark ===== Upload Assets : NEW & FULL ====
  750. #pragma --------------------------------------------------------------------------------------------
  751. - (void)uploadNewAssets
  752. {
  753. [self uploadAssetsNewAndFull:NO];
  754. }
  755. - (void)uploadFullAssets
  756. {
  757. [self uploadAssetsNewAndFull:YES];
  758. }
  759. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  760. {
  761. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  762. NSMutableArray *newItemsToUpload;
  763. // Is loading new Asset ?
  764. if (app.automaticCheckAssetInProgress)
  765. return;
  766. // Check Asset : NEW or FULL
  767. if (assetsFull) {
  768. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  769. } else {
  770. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  771. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  772. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  773. }
  774. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  775. if ([newItemsToUpload count] == 0)
  776. return;
  777. // STOP
  778. app.automaticCheckAssetInProgress = YES;
  779. // Disable idle timer
  780. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  781. if (assetsFull) {
  782. if (!_hud)
  783. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  784. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  785. }
  786. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  787. if (assetsFull)
  788. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  789. else
  790. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  791. });
  792. }
  793. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  794. {
  795. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  796. }
  797. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  798. {
  799. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  800. }
  801. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  802. {
  803. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  804. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  805. BOOL useSubFolder = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  806. // Conversion from ALAsset -to-> PHAsset
  807. for (ALAsset *asset in newItemsToUpload) {
  808. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  809. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  810. PHAsset *asset = [fetchResult firstObject];
  811. [newItemsPHAssetToUpload addObject:asset];
  812. NSLog(@"Convert url %@", url);
  813. }
  814. // Create the folder for Photos & if request the subfolders
  815. if(![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutomaticAll]) {
  816. [self endLoadingAssets];
  817. return;
  818. }
  819. for (PHAsset *asset in newItemsPHAssetToUpload) {
  820. NSString *serverUrl;
  821. NSDate *assetDate = asset.creationDate;
  822. PHAssetMediaType assetMediaType = asset.mediaType;
  823. NSString *session;
  824. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  825. // Select type of session
  826. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  827. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  828. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  829. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  830. NSDateFormatter *formatter = [NSDateFormatter new];
  831. [formatter setDateFormat:@"yyyy"];
  832. NSString *yearString = [formatter stringFromDate:assetDate];
  833. [formatter setDateFormat:@"MM"];
  834. NSString *monthString = [formatter stringFromDate:assetDate];
  835. if (useSubFolder)
  836. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  837. else
  838. serverUrl = folderPhotos;
  839. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  840. metadataNet.action = actionUploadAsset;
  841. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  842. if (assetsFull) {
  843. metadataNet.selector = selectorUploadAutomaticAll;
  844. metadataNet.selectorPost = selectorUploadRemovePhoto;
  845. metadataNet.priority = NSOperationQueuePriorityLow;
  846. } else {
  847. metadataNet.selector = selectorUploadAutomatic;
  848. metadataNet.selectorPost = nil;
  849. metadataNet.priority = NSOperationQueuePriorityNormal;
  850. }
  851. metadataNet.fileName = fileName;
  852. metadataNet.serverUrl = serverUrl;
  853. metadataNet.session = session;
  854. metadataNet.taskStatus = k_taskStatusResume;
  855. if (![CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount]) {
  856. [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];
  857. [self endLoadingAssets];
  858. return;
  859. }
  860. // Activity
  861. NSString *media = @"";
  862. if (assetMediaType == PHAssetMediaTypeImage) media = @"Image";
  863. if (assetMediaType == PHAssetMediaTypeVideo) media = @"Video";
  864. [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];
  865. // Upldate Camera Upload data
  866. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  867. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  868. }
  869. // end loading
  870. [self endLoadingAssets];
  871. // Update icon badge number
  872. [app updateApplicationIconBadgeNumber];
  873. }
  874. -(void)endLoadingAssets
  875. {
  876. [_hud hideHud];
  877. // START
  878. app.automaticCheckAssetInProgress = NO;
  879. // Enable idle timer
  880. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  881. }
  882. @end