CCPhotosCameraUpload.m 55 KB

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