CCPhotosCameraUpload.m 51 KB

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