CCPhotosCameraUpload.m 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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. UIImage *imageButton = [UIImage imageNamed:image_activeCameraUpload];
  236. UIImage *image = [CCUtility drawText:NSLocalizedString(@"_activate_camera_upload_", nil) inImage:imageButton];
  237. return image;
  238. } else return nil;
  239. }
  240. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  241. {
  242. CCManageCameraUpload *viewController = [[CCManageCameraUpload alloc] initWithNibName:nil bundle:nil];
  243. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  244. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  245. [self presentViewController:navigationController animated:YES completion:nil];
  246. }
  247. #pragma --------------------------------------------------------------------------------------------
  248. #pragma mark ===== openSelectedFiles =====
  249. #pragma--------------------------------------------------------------------------------------------
  250. - (void)openSelectedFiles
  251. {
  252. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  253. for (CCMetadata *metadata in _selectedMetadatas) {
  254. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  255. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  256. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  257. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  258. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  259. [dataToShare addObject:data];
  260. }
  261. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  262. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  263. }
  264. }
  265. }
  266. if ([dataToShare count] > 0) {
  267. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  268. // iPad
  269. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  270. self.navigationItem.leftBarButtonItem.enabled = NO;
  271. self.navigationItem.rightBarButtonItem.enabled = NO;
  272. [self presentViewController:activityViewController animated:YES completion:^{
  273. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  274. self.navigationItem.leftBarButtonItem.enabled = YES;
  275. self.navigationItem.rightBarButtonItem.enabled = YES;
  276. if (completed) {
  277. [dataToShare enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  278. if ([obj isKindOfClass:[UIImage class]])
  279. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  280. if ([obj isKindOfClass:[NSURL class]])
  281. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  282. }];
  283. [self performSelector:@selector(reloadCollection) withObject:nil];
  284. }
  285. }];
  286. }];
  287. }
  288. }
  289. #pragma --------------------------------------------------------------------------------------------
  290. #pragma mark ===== Download =====
  291. #pragma--------------------------------------------------------------------------------------------
  292. - (void)downloadFileFailure:(NSInteger)errorCode
  293. {
  294. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  295. }
  296. - (void)downloadFileSuccess:(CCMetadata *)metadata
  297. {
  298. NSIndexPath *indexPath;
  299. BOOL existsIcon = NO;
  300. if (metadata.fileID) {
  301. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  302. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  303. }
  304. if (indexPath && existsIcon) {
  305. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  306. if (cell) {
  307. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  308. UIVisualEffectView *effect = [cell viewWithTag:200];
  309. UIImageView *checked = [cell viewWithTag:300];
  310. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  311. effect.hidden = YES;
  312. checked.hidden = YES;
  313. [app.icoImagesCache setObject:imageView.image forKey:metadata.fileID];
  314. }
  315. }
  316. }
  317. #pragma --------------------------------------------------------------------------------------------
  318. #pragma mark ===== Delete =====
  319. #pragma--------------------------------------------------------------------------------------------
  320. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  321. {
  322. [self deleteFileOrFolderSuccess:metadataNet];
  323. }
  324. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  325. {
  326. [_queueMetadatas removeObject:metadataNet.selector];
  327. if ([_queueMetadatas count] == 0) {
  328. [_hud hideHud];
  329. if ([_selectedMetadatas count] > 0) {
  330. [_selectedMetadatas removeObjectAtIndex:0];
  331. if ([_selectedMetadatas count] > 0) {
  332. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  333. } else {
  334. [self reloadDatasource];
  335. }
  336. } else {
  337. [self reloadDatasource];
  338. }
  339. }
  340. }
  341. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  342. {
  343. if (metadata.cryptated) {
  344. [_queueMetadatas addObject:selectorDeleteCrypto];
  345. [_queueMetadatas addObject:selectorDeletePlist];
  346. } else {
  347. [_queueMetadatas addObject:selectorDelete];
  348. }
  349. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  350. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  351. }
  352. - (void)deleteSelectedFiles
  353. {
  354. [_queueMetadatas removeAllObjects];
  355. _numSelectedMetadatas = [_selectedMetadatas count];
  356. if ([_selectedMetadatas count] == 0)
  357. return;
  358. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  359. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  360. style:UIAlertActionStyleDestructive
  361. handler:^(UIAlertAction *action) {
  362. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  363. }]];
  364. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  365. style:UIAlertActionStyleCancel
  366. handler:^(UIAlertAction *action) {
  367. [alertController dismissViewControllerAnimated:YES completion:nil];
  368. }]];
  369. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  370. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  371. [alertController.view layoutIfNeeded];
  372. [self presentViewController:alertController animated:YES completion:NULL];
  373. }
  374. #pragma --------------------------------------------------------------------------------------------
  375. #pragma mark ==== Download Thumbnail Delegate ====
  376. #pragma --------------------------------------------------------------------------------------------
  377. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  378. {
  379. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  380. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  381. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  382. }
  383. - (void)triggerProgressTask:(NSNotification *)notification
  384. {
  385. NSDictionary *dict = notification.userInfo;
  386. float progress = [[dict valueForKey:@"progress"] floatValue];
  387. if (progress == 0)
  388. [self.navigationController cancelCCProgress];
  389. else
  390. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:COLOR_NAVIGATIONBAR_PROGRESS];
  391. }
  392. #pragma --------------------------------------------------------------------------------------------
  393. #pragma mark ==== Collection ====
  394. #pragma --------------------------------------------------------------------------------------------
  395. - (void)reloadDatasourceForced
  396. {
  397. [CCSectionMetadata removeAllObjectsSectionDataSource:_sectionDataSource];
  398. [self reloadDatasource];
  399. }
  400. - (void)reloadDatasource
  401. {
  402. // test
  403. if (app.activeAccount.length == 0)
  404. return;
  405. NSString *serverUrl = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  406. if (_sectionDataSource) {
  407. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  408. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  409. dispatch_async(dispatch_get_main_queue(), ^{
  410. [self reloadCollection];
  411. });
  412. });
  413. } else {
  414. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:[CCCoreData getRecordsTableMetadataPhotosCameraUpload:serverUrl activeAccount:app.activeAccount] listProgressMetadata:nil groupByField:@"date" replaceDateToExifDate:YES activeAccount:app.activeAccount];
  415. [self reloadCollection];
  416. }
  417. }
  418. - (void)reloadCollection
  419. {
  420. [self.collectionView reloadData];
  421. [_selectedMetadatas removeAllObjects];
  422. [self collectionSelect:NO];
  423. }
  424. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  425. {
  426. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  427. }
  428. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  429. {
  430. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  431. }
  432. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  433. {
  434. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  435. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  436. return CGSizeMake(collectionView.frame.size.width / 5.3f, collectionView.frame.size.width / 5.3f);
  437. else
  438. return CGSizeMake(collectionView.frame.size.width / 7.3f, collectionView.frame.size.width / 7.3f);
  439. }
  440. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  441. {
  442. if ([_sectionDataSource.sections count] - 1 == section)
  443. return CGSizeMake(collectionView.frame.size.width, 50);
  444. return CGSizeZero;
  445. }
  446. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  447. {
  448. if (kind == UICollectionElementKindSectionHeader) {
  449. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  450. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  451. [self getGeoLocationForSection:indexPath.section];
  452. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  453. titleLabel.textColor = COLOR_TEXT_ANTHRACITE;
  454. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  455. return headerView;
  456. }
  457. if (kind == UICollectionElementKindSectionFooter) {
  458. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  459. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  460. titleLabel.textColor = [UIColor grayColor];
  461. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  462. return footerView;
  463. }
  464. return nil;
  465. }
  466. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  467. {
  468. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  469. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  470. UIVisualEffectView *effect = [cell viewWithTag:200];
  471. UIImageView *checked = [cell viewWithTag:300];
  472. checked.image = [UIImage imageNamed:image_checked];
  473. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  474. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  475. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  476. // Image
  477. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  478. imageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  479. if (imageView.image == nil) {
  480. // insert Image
  481. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  482. imageView.image = image;
  483. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  484. }
  485. } else {
  486. // Thumbnail not present
  487. imageView.image = [UIImage imageNamed:image_photosDownload];
  488. if (metadata.thumbnailExists)
  489. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  490. }
  491. // Cheched
  492. if (cell.selected) {
  493. checked.hidden = NO;
  494. effect.hidden = NO;
  495. effect.alpha = 0.4;
  496. } else {
  497. checked.hidden = YES;
  498. effect.hidden = YES;
  499. }
  500. return cell;
  501. }
  502. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  503. {
  504. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  505. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  506. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  507. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  508. if (_cellEditing) {
  509. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  510. } else {
  511. if ([self shouldPerformSegue])
  512. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  513. }
  514. }
  515. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  516. {
  517. if (_cellEditing == NO)
  518. return;
  519. //UICollectionViewCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
  520. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  521. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  522. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  523. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  524. }
  525. #pragma --------------------------------------------------------------------------------------------
  526. #pragma mark ===== Navigation ====
  527. #pragma --------------------------------------------------------------------------------------------
  528. - (BOOL)shouldPerformSegue
  529. {
  530. // Test
  531. // Background ? exit
  532. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  533. return NO;
  534. // Not in first plain ? exit
  535. if (self.view.window == NO)
  536. return NO;
  537. // Collapsed but in first plain in detail exit
  538. if (self.splitViewController.isCollapsed)
  539. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  540. return NO;
  541. // Video running exit
  542. if (self.detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && self.detailViewController.photoBrowser.currentVideoPlayerViewController.view.window)
  543. return NO;
  544. // ok perform segue
  545. return YES;
  546. }
  547. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  548. {
  549. id controller = segue.destinationViewController;
  550. if ([controller isKindOfClass:[UINavigationController class]]) {
  551. UINavigationController *navigationController = controller;
  552. self.detailViewController = (CCDetail *)navigationController.topViewController;
  553. } else {
  554. self.detailViewController = segue.destinationViewController;
  555. }
  556. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  557. for (NSString *fileID in _sectionDataSource.allFileID) {
  558. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  559. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  560. [allRecordsDataSourceImagesVideos addObject:metadata];
  561. }
  562. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  563. self.detailViewController.metadataDetail = _metadata;
  564. self.detailViewController.dateFilterQuery = _metadata.date;
  565. self.detailViewController.isCameraUpload = YES;
  566. [self.detailViewController setTitle:_metadata.fileNamePrint];
  567. }
  568. #pragma --------------------------------------------------------------------------------------------
  569. #pragma mark ====== --- Camera Upload --- ======
  570. #pragma --------------------------------------------------------------------------------------------
  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 addActivityFile:@"" action:k_activityDebugActionAutomaticUpload selector:@"" note:[NSString stringWithFormat:@"Number: %lu", [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 addActivityFile:@"" 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 addActivityFile:@"" 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 addActivityFile:fileName 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