CCPhotosCameraUpload.m 51 KB

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