CCPhotosCameraUpload.m 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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 (_AutomaticCameraUploadInProgress)
  584. // return;
  585. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  586. [self setupCameraUpload];
  587. if([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount])
  588. [self checkIfLocationIsEnabled];
  589. } else {
  590. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  591. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  592. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  593. }
  594. }
  595. #pragma --------------------------------------------------------------------------------------------
  596. #pragma mark === Camera Upload & Full ===
  597. #pragma --------------------------------------------------------------------------------------------
  598. - (void)setupCameraUpload
  599. {
  600. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  601. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  602. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  603. [self uploadNewAssets];
  604. } else {
  605. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  606. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  607. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  608. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  609. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  610. delegate:nil
  611. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  612. otherButtonTitles:nil];
  613. [alert show];
  614. }
  615. }
  616. - (void)setupCameraUploadFull
  617. {
  618. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  619. self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
  620. [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
  621. [self uploadFullAssets];
  622. } else {
  623. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  624. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  625. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  626. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  627. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  628. delegate:nil
  629. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  630. otherButtonTitles:nil];
  631. [alert show];
  632. }
  633. }
  634. #pragma --------------------------------------------------------------------------------------------
  635. #pragma mark === Location ===
  636. #pragma --------------------------------------------------------------------------------------------
  637. - (BOOL)checkIfLocationIsEnabled
  638. {
  639. [CCManageLocation sharedSingleton].delegate = self;
  640. if ([CLLocationManager locationServicesEnabled]) {
  641. NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
  642. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
  643. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
  644. NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
  645. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  646. } else {
  647. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  648. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  649. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  650. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  651. delegate:nil
  652. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  653. otherButtonTitles:nil];
  654. [alert show];
  655. } else {
  656. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  657. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  658. delegate:nil
  659. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  660. otherButtonTitles:nil];
  661. [alert show];
  662. }
  663. }
  664. } else {
  665. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  666. [CCCoreData setCameraUploadBackground:YES activeAccount:app.activeAccount];
  667. [[CCManageLocation sharedSingleton] startSignificantChangeUpdates];
  668. } else {
  669. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  670. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  671. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  672. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  673. delegate:nil
  674. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  675. otherButtonTitles:nil];
  676. [alert show];
  677. }
  678. }
  679. } else {
  680. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  681. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  682. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  683. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  684. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  685. delegate:nil
  686. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  687. otherButtonTitles:nil];
  688. [alert show];
  689. } else {
  690. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  691. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  692. delegate:nil
  693. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  694. otherButtonTitles:nil];
  695. [alert show];
  696. }
  697. }
  698. return [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount];
  699. }
  700. - (void)statusAuthorizationLocationChanged
  701. {
  702. if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  703. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  704. ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
  705. [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
  706. usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  707. } failureBlock:^(NSError *error) {
  708. }];
  709. }
  710. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  711. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  712. if ([CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  713. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  714. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  715. }
  716. } else {
  717. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
  718. message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
  719. delegate:nil
  720. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  721. otherButtonTitles:nil];
  722. [alert show];
  723. }
  724. } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
  725. if ([CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount]) {
  726. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  727. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  728. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  729. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
  730. message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
  731. delegate:nil
  732. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  733. otherButtonTitles:nil];
  734. [alert show];
  735. } else {
  736. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
  737. message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
  738. delegate:nil
  739. cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
  740. otherButtonTitles:nil];
  741. [alert show];
  742. }
  743. }
  744. }
  745. if (![CCManageLocation sharedSingleton].firstChangeAuthorizationDone) {
  746. [CCManageLocation sharedSingleton].firstChangeAuthorizationDone = YES;
  747. }
  748. }
  749. }
  750. - (void)changedLocation
  751. {
  752. //Verifica
  753. [[CCNetworking sharedNetworking] automaticDownloadInError];
  754. [[CCNetworking sharedNetworking] automaticUploadInError];
  755. // solo in background
  756. if([CCCoreData getCameraUploadActiveAccount:app.activeAccount] && [CCCoreData getCameraUploadBackgroundActiveAccount:app.activeAccount ] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  757. if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
  758. //check location
  759. if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
  760. NSLog(@"[LOG] Changed Location call uploadNewAssets");
  761. [self uploadNewAssets];
  762. }
  763. } else {
  764. [CCCoreData setCameraUpload:NO activeAccount:app.activeAccount];
  765. [CCCoreData setCameraUploadBackground:NO activeAccount:app.activeAccount];
  766. [[CCManageLocation sharedSingleton] stopSignificantChangeUpdates];
  767. [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
  768. }
  769. }
  770. }
  771. #pragma --------------------------------------------------------------------------------------------
  772. #pragma mark ===== Upload Assets : NEW & FULL ====
  773. #pragma --------------------------------------------------------------------------------------------
  774. - (void)uploadNewAssets
  775. {
  776. [self uploadAssetsNewAndFull:NO];
  777. }
  778. - (void)uploadFullAssets
  779. {
  780. [self uploadAssetsNewAndFull:YES];
  781. }
  782. - (void)uploadAssetsNewAndFull:(BOOL)assetsFull
  783. {
  784. CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
  785. NSMutableArray *newItemsToUpload;
  786. // Check Asset : NEW or FULL
  787. if (assetsFull) {
  788. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
  789. } else {
  790. NSDate *databaseDateVideo = [CCCoreData getCameraUploadDateVideoActiveAccount:app.activeAccount];
  791. NSDate *databaseDatePhoto = [CCCoreData getCameraUploadDatePhotoActiveAccount:app.activeAccount];
  792. newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
  793. }
  794. // News Assets ? if no verify if blocked Table Automatic Upload -> Autostart
  795. if ([newItemsToUpload count] == 0)
  796. return;
  797. // Activity
  798. [CCCoreData addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutomaticUpload selector:@"" note:[NSString stringWithFormat:@"Number: %lu", (unsigned long)[newItemsToUpload count]] type:k_activityTypeInfo verbose:k_activityVerboseHigh account:app.activeAccount];
  799. // STOP new request : initStateCameraUpload
  800. //_AutomaticCameraUploadInProgress = YES;
  801. // Disable idle timer
  802. [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
  803. if (!_hud) _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  804. if (assetsFull)
  805. [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  806. else
  807. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  808. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  809. if (assetsFull)
  810. [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  811. else
  812. [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
  813. });
  814. }
  815. - (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  816. {
  817. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
  818. }
  819. - (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
  820. {
  821. [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
  822. }
  823. - (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
  824. {
  825. NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
  826. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  827. BOOL createSubfolders = [CCCoreData getCameraUploadCreateSubfolderActiveAccount:app.activeAccount];
  828. // Conversion from ALAsset -to-> PHAsset
  829. for (ALAsset *asset in newItemsToUpload) {
  830. NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
  831. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  832. PHAsset *asset = [fetchResult firstObject];
  833. [newItemsPHAssetToUpload addObject:asset];
  834. }
  835. // verify/create folder Camera Upload, if error exit
  836. if(![self automaticCreateFolder:folderPhotos]) {
  837. NSString *description = NSLocalizedStringFromTable(@"_not_possible_create_folder_", @"Error", nil);
  838. // Full Upload ?
  839. if (assetsFull)
  840. [app messageNotification:@"_error_" description:description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  841. // START new request : initStateCameraUpload
  842. //_AutomaticCameraUploadInProgress = NO;
  843. // Activity
  844. [CCCoreData addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutomaticUpload selector:@"" note:description type:k_activityTypeFailure verbose:k_activityVerboseDefault account:app.activeAccount];
  845. return;
  846. }
  847. // Use subfolders verify/create subfolder, if error exit
  848. if (createSubfolders) {
  849. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:newItemsPHAssetToUpload]) {
  850. if (![self automaticCreateFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  851. [self endLoadingAssets];
  852. if (assetsFull)
  853. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  854. // Activity
  855. [CCCoreData addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutomaticUpload selector:@"" note:NSLocalizedString(@"_error_createsubfolders_upload_",nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:app.activeAccount];
  856. return;
  857. }
  858. }
  859. }
  860. for (PHAsset *asset in newItemsPHAssetToUpload) {
  861. NSString *serverUrl;
  862. NSDate *assetDate = asset.creationDate;
  863. PHAssetMediaType assetMediaType = asset.mediaType;
  864. NSString *session;
  865. NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
  866. // Select type of session
  867. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  868. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount] == NO) session = k_upload_session;
  869. if (assetMediaType == PHAssetMediaTypeImage && [CCCoreData getCameraUploadWWanPhotoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  870. if (assetMediaType == PHAssetMediaTypeVideo && [CCCoreData getCameraUploadWWanVideoActiveAccount:app.activeAccount]) session = k_upload_session_wwan;
  871. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  872. [formatter setDateFormat:@"yyyy"];
  873. NSString *yearString = [formatter stringFromDate:assetDate];
  874. [formatter setDateFormat:@"MM"];
  875. NSString *monthString = [formatter stringFromDate:assetDate];
  876. if (createSubfolders)
  877. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  878. else
  879. serverUrl = folderPhotos;
  880. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  881. metadataNet.action = actionUploadAsset;
  882. metadataNet.identifier = asset.localIdentifier;
  883. if (assetsFull) {
  884. metadataNet.selector = selectorUploadAutomaticAll;
  885. metadataNet.selectorPost = selectorUploadRemovePhoto;
  886. metadataNet.priority = NSOperationQueuePriorityLow;
  887. } else {
  888. metadataNet.selector = selectorUploadAutomatic;
  889. metadataNet.selectorPost = nil;
  890. metadataNet.priority = NSOperationQueuePriorityNormal;
  891. }
  892. metadataNet.fileName = fileName;
  893. metadataNet.serverUrl = serverUrl;
  894. metadataNet.session = session;
  895. metadataNet.taskStatus = k_taskStatusResume;
  896. [CCCoreData addTableAutomaticUpload:metadataNet account:app.activeAccount];
  897. // Activity
  898. NSString *media = @"";
  899. if (assetMediaType == PHAssetMediaTypeImage) media = @"Image";
  900. if (assetMediaType == PHAssetMediaTypeVideo) media = @"Video";
  901. [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];
  902. // Upldate Camera Upload data
  903. if ([metadataNet.selector isEqualToString:selectorUploadAutomatic])
  904. [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:app.activeAccount];
  905. }
  906. // start upload
  907. if (assetsFull)
  908. [app loadTableAutomaticUploadForSelector:selectorUploadAutomaticAll];
  909. else
  910. [app loadTableAutomaticUploadForSelector:selectorUploadAutomatic];
  911. // end loading
  912. [self endLoadingAssets];
  913. // Update icon badge number
  914. [app updateApplicationIconBadgeNumber];
  915. }
  916. - (BOOL)automaticCreateFolder:(NSString *)folderPathName
  917. {
  918. OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
  919. __block BOOL noError = YES;
  920. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  921. [communication setCredentialsWithUser:app.activeUser andPassword:app.activePassword];
  922. [communication setUserAgent:[CCUtility getUserAgent]];
  923. [communication readFile:folderPathName onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) {
  924. dispatch_semaphore_signal(semaphore);
  925. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  926. [communication createFolder:folderPathName onCommunication:communication withForbiddenCharactersSupported:app.hasServerForbiddenCharactersSupport successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
  927. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:[CCUtility deletingLastPathComponentFromServerUrl:folderPathName] directoryID:nil];
  928. dispatch_semaphore_signal(semaphore);
  929. } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
  930. noError = NO;
  931. dispatch_semaphore_signal(semaphore);
  932. } errorBeforeRequest:^(NSError *error) {
  933. noError = NO;
  934. dispatch_semaphore_signal(semaphore);
  935. }];
  936. }];
  937. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  938. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_webdav]];
  939. return noError;
  940. }
  941. -(void)endLoadingAssets
  942. {
  943. [_hud hideHud];
  944. // START new request : initStateCameraUpload
  945. //_AutomaticCameraUploadInProgress = NO;
  946. // Enable idle timer
  947. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  948. }
  949. @end