CCMain.m 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225
  1. //
  2. // CCMain.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCSynchronize.h"
  26. #import "OCActivity.h"
  27. #import "OCNotifications.h"
  28. #import "OCNotificationsAction.h"
  29. #import "OCFrameworkConstants.h"
  30. #import "OCCapabilities.h"
  31. #import "NCAutoUpload.h"
  32. #import "NCBridgeSwift.h"
  33. #import "NCNetworkingEndToEnd.h"
  34. #import "PKDownloadButton.h"
  35. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, NCSelectDelegate, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate>
  36. {
  37. AppDelegate *appDelegate;
  38. BOOL _isRoot;
  39. BOOL _isViewDidLoad;
  40. NSMutableDictionary *_selectedocIdsMetadatas;
  41. NSUInteger _numSelectedocIdsMetadatas;
  42. UIImageView *_imageTitleHome;
  43. NSUInteger _failedAttempts;
  44. NSDate *_lockUntilDate;
  45. NCMainRefreshControl *refreshControl;
  46. CCHud *_hud;
  47. // Datasource
  48. CCSectionDataSourceMetadata *sectionDataSource;
  49. NSDate *_dateReadDataSource;
  50. // Search
  51. NSString *_searchFileName;
  52. NSMutableArray *_searchResultMetadatas;
  53. NSString *_noFilesSearchTitle;
  54. NSString *_noFilesSearchDescription;
  55. NSTimer *_timerWaitInput;
  56. // Automatic Upload Folder
  57. NSString *_autoUploadFileName;
  58. NSString *_autoUploadDirectory;
  59. // Folder
  60. BOOL _loadingFolder;
  61. tableMetadata *_metadataFolder;
  62. CGFloat heightRichWorkspace;
  63. CGFloat heightSearchBar;
  64. }
  65. @end
  66. @implementation CCMain
  67. #pragma --------------------------------------------------------------------------------------------
  68. #pragma mark ===== Init =====
  69. #pragma --------------------------------------------------------------------------------------------
  70. - (id)initWithCoder:(NSCoder *)aDecoder
  71. {
  72. if (self = [super initWithCoder:aDecoder]) {
  73. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  74. appDelegate.activeMain = self;
  75. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  76. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  77. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  78. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  79. }
  80. return self;
  81. }
  82. #pragma --------------------------------------------------------------------------------------------
  83. #pragma mark ===== View =====
  84. #pragma --------------------------------------------------------------------------------------------
  85. - (void)viewDidLoad
  86. {
  87. [super viewDidLoad];
  88. // init object
  89. self.metadata = [tableMetadata new];
  90. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  91. _selectedocIdsMetadatas = [NSMutableDictionary new];
  92. _isViewDidLoad = YES;
  93. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  94. _searchResultMetadatas = [NSMutableArray new];
  95. _searchFileName = @"";
  96. _noFilesSearchTitle = @"";
  97. _noFilesSearchDescription = @"";
  98. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  99. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  100. // delegate
  101. self.tableView.delegate = self;
  102. self.tableView.tableFooterView = [UIView new];
  103. self.tableView.emptyDataSetDelegate = self;
  104. self.tableView.emptyDataSetSource = self;
  105. self.searchController.delegate = self;
  106. self.searchController.searchBar.delegate = self;
  107. // Search
  108. self.definesPresentationContext = YES;
  109. self.searchController.searchResultsUpdater = self;
  110. self.searchController.dimsBackgroundDuringPresentation = NO;
  111. self.searchController.searchBar.translucent = NO;
  112. [self.searchController.searchBar sizeToFit];
  113. self.searchController.searchBar.delegate = self;
  114. self.searchController.searchBar.barTintColor = NCBrandColor.sharedInstance.brand;
  115. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.brand;
  116. self.searchController.searchBar.backgroundImage = [UIImage new];
  117. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  118. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  119. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandText forState:UIControlStateNormal];
  120. }
  121. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  122. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  123. searchTextView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  124. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  125. }
  126. heightSearchBar = self.searchController.searchBar.frame.size.height;
  127. // Load Rich Workspace
  128. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  129. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  130. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  131. viewRichWorkspaceTapped.delegate = self;
  132. [self.viewRichWorkspace addGestureRecognizer:viewRichWorkspaceTapped];
  133. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height/4 + heightSearchBar;
  134. self.viewRichWorkspace.textViewTopConstraint.constant = heightSearchBar;
  135. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  136. // Table Header View
  137. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  138. [self.tableView.tableHeaderView addSubview:self.searchController.searchBar];
  139. // Register cell
  140. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  141. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  142. // long press recognizer TableView
  143. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  144. [self.tableView addGestureRecognizer:longPressRecognizer];
  145. // Pull-to-Refresh
  146. [self createRefreshControl];
  147. // Register for 3D Touch Previewing if available
  148. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  149. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  150. }
  151. // reMenu Background
  152. _reMenuBackgroundView = [UIView new];
  153. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  154. // if this is not Main (the Main uses inizializeMain)
  155. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  156. // Read (File) Folder
  157. [self readFileReloadFolder];
  158. }
  159. // Title
  160. [self setTitle];
  161. // changeTheming
  162. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  163. [self changeTheming];
  164. }
  165. - (void)viewWillAppear:(BOOL)animated
  166. {
  167. [super viewWillAppear:animated];
  168. // test
  169. if (appDelegate.activeAccount.length == 0)
  170. return;
  171. if (_isSelectedMode)
  172. [self setUINavigationBarSelected];
  173. else
  174. [self setUINavigationBarDefault];
  175. // If not editing mode remove _selectedocIds
  176. if (!self.tableView.editing)
  177. [_selectedocIdsMetadatas removeAllObjects];
  178. // Get Shares
  179. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.activeAccount serverUrl:self.serverUrl];
  180. // Get RichWorkspace
  181. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  182. self.richWorkspaceText = directory.richWorkspace;
  183. // Query data source
  184. if (self.searchController.isActive == false) {
  185. [self queryDatasourceWithReloadData:YES serverUrl:self.serverUrl];
  186. }
  187. }
  188. - (void)viewDidAppear:(BOOL)animated
  189. {
  190. [super viewDidAppear:animated];
  191. // Active Main
  192. appDelegate.activeMain = self;
  193. // Test viewDidLoad
  194. if (_isViewDidLoad) {
  195. _isViewDidLoad = NO;
  196. } else {
  197. if (appDelegate.activeAccount.length > 0 && [_selectedocIdsMetadatas count] == 0) {
  198. // Read (file) Folder
  199. [self readFileReloadFolder];
  200. // TEST
  201. /*
  202. NSString *directoryPath = [CCUtility returnPathfromServerUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  203. [[NCCommunication sharedInstance] searchReadFolderWithServerUrl:appDelegate.activeUrl user:appDelegate.activeUserID directoryPath:directoryPath lastFileName:@"" limit:100 account:appDelegate.activeAccount completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *message) {
  204. }];
  205. */
  206. }
  207. }
  208. // Title
  209. [self setTitle];
  210. }
  211. - (void)viewWillDisappear:(BOOL)animated
  212. {
  213. [super viewWillDisappear:animated];
  214. [self closeAllMenu];
  215. }
  216. - (void) viewDidLayoutSubviews
  217. {
  218. [super viewDidLayoutSubviews];
  219. [self setTableViewHeader];
  220. }
  221. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  222. {
  223. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  224. [self closeAllMenu];
  225. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  226. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  227. // Portrait
  228. } else {
  229. // Landscape
  230. }
  231. [self setTableViewHeader];
  232. }];
  233. }
  234. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  235. {
  236. [self viewDidAppear:true];
  237. }
  238. - (BOOL)prefersStatusBarHidden
  239. {
  240. return NO;
  241. }
  242. // detect scroll for remove keyboard in search mode
  243. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  244. {
  245. if (self.searchController.isActive && scrollView == self.tableView) {
  246. [self.searchController.searchBar endEditing:YES];
  247. }
  248. }
  249. - (void)changeTheming
  250. {
  251. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  252. // createImagesThemingColor
  253. [[NCMainCommon sharedInstance] createImagesThemingColor];
  254. // Refresh control
  255. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText;
  256. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand;
  257. // color searchbar
  258. self.searchController.searchBar.barTintColor = NCBrandColor.sharedInstance.brand;
  259. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.brand;
  260. // color searchbbar button text (cancel)
  261. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  262. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  263. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandText forState:UIControlStateNormal];
  264. }
  265. // color textview searchbbar
  266. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  267. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  268. searchTextView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  269. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  270. }
  271. // Rich Workspace
  272. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  273. // Title
  274. [self setTitle];
  275. // Reload Table View
  276. [self tableViewReloadData];
  277. }
  278. #pragma --------------------------------------------------------------------------------------------
  279. #pragma mark ===== Initialization =====
  280. #pragma --------------------------------------------------------------------------------------------
  281. //
  282. // Callers :
  283. //
  284. // ChangeDefaultAccount (delegate)
  285. // Split : inizialize
  286. // Settings Advanced : removeAllFiles
  287. //
  288. - (void)initializeMain:(NSNotification *)notification
  289. {
  290. _dateReadDataSource = nil;
  291. // test
  292. if (appDelegate.activeAccount.length == 0)
  293. return;
  294. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  295. // This is Root home main add list
  296. appDelegate.homeMain = self;
  297. _isRoot = YES;
  298. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  299. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  300. // go Home
  301. [self.navigationController popToRootViewControllerAnimated:NO];
  302. // Remove search mode
  303. [self cancelSearchBar];
  304. // Clear error certificate
  305. [CCUtility setCertificateError:appDelegate.activeAccount error:NO];
  306. // Setting Theming
  307. [appDelegate settingThemingColorBrand];
  308. // Detail
  309. // If AVPlayer in play -> Stop
  310. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  311. [appDelegate.player pause];
  312. }
  313. for (UIView *view in [appDelegate.activeDetail.view subviews]) {
  314. if ([view isKindOfClass:[UIImageView class]] == NO) { // View Image Nextcloud
  315. [view removeFromSuperview];
  316. }
  317. }
  318. appDelegate.activeDetail.title = nil;
  319. // remove all Notification Messages
  320. [appDelegate.listOfNotifications removeAllObjects];
  321. // Not Photos Video in library ? then align and Init Auto Upload
  322. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  323. if ([recordsPhotoLibrary count] == 0) {
  324. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  325. }
  326. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  327. NSLog(@"[LOG] Request Service Server Nextcloud");
  328. [[NCService sharedInstance] startRequestServicesServer];
  329. // Clear datasorce
  330. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  331. // Read this folder
  332. [self readFileReloadFolder];
  333. } else {
  334. // reload datasource
  335. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  336. }
  337. // Registeration push notification
  338. [appDelegate pushNotification];
  339. // Registeration domain File Provider
  340. if (@available(iOS 11, *) ) {
  341. if (k_fileProvider_domain) {
  342. [FileProviderDomain.sharedInstance registerDomain];
  343. } else {
  344. [FileProviderDomain.sharedInstance removeAllDomain];
  345. }
  346. }
  347. }
  348. #pragma --------------------------------------------------------------------------------------------
  349. #pragma mark ==== DZNEmptyDataSetSource ====
  350. #pragma --------------------------------------------------------------------------------------------
  351. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  352. {
  353. if (_loadingFolder)
  354. return NO;
  355. else
  356. return YES;
  357. }
  358. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  359. {
  360. return NCBrandColor.sharedInstance.backgroundView;
  361. }
  362. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  363. {
  364. if (self.searchController.isActive)
  365. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  366. else
  367. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  368. }
  369. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  370. {
  371. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  372. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  373. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  374. activityView.color = NCBrandColor.sharedInstance.brandElement;
  375. [activityView startAnimating];
  376. return activityView;
  377. }
  378. return nil;
  379. }
  380. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  381. {
  382. NSString *text;
  383. if (self.searchController.isActive) {
  384. text = _noFilesSearchTitle;
  385. } else {
  386. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  387. }
  388. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  389. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  390. }
  391. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  392. {
  393. NSString *text;
  394. if (self.searchController.isActive) {
  395. text = _noFilesSearchDescription;
  396. } else {
  397. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  398. }
  399. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  400. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  401. paragraph.alignment = NSTextAlignmentCenter;
  402. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  403. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  404. }
  405. #pragma --------------------------------------------------------------------------------------------
  406. #pragma mark ===== Text Field =====
  407. #pragma --------------------------------------------------------------------------------------------
  408. - (void)minCharTextFieldDidChange:(UITextField *)sender
  409. {
  410. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  411. if (alertController)
  412. {
  413. UITextField *fileName = alertController.textFields.firstObject;
  414. UIAlertAction *okAction = alertController.actions.lastObject;
  415. okAction.enabled = fileName.text.length > 0;
  416. }
  417. }
  418. - (void)textFieldDidBeginEditing:(UITextField *)textField
  419. {
  420. [CCUtility selectFileNameFrom:textField];
  421. }
  422. #pragma --------------------------------------------------------------------------------------------
  423. #pragma mark ===== Graphic Window =====
  424. #pragma --------------------------------------------------------------------------------------------
  425. - (void)createRefreshControl
  426. {
  427. refreshControl = [NCMainRefreshControl new];
  428. self.tableView.refreshControl = refreshControl;
  429. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText;
  430. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand;
  431. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  432. }
  433. - (void)deleteRefreshControl
  434. {
  435. [refreshControl endRefreshing];
  436. for (UIView *subview in [_tableView subviews]) {
  437. if (subview == refreshControl)
  438. [subview removeFromSuperview];
  439. }
  440. if (@available(iOS 10, *)) {
  441. self.tableView.refreshControl = nil;
  442. }
  443. refreshControl = nil;
  444. }
  445. - (void)refreshControlTarget
  446. {
  447. [self readFolder:_serverUrl];
  448. // Actuate `Peek` feedback (weak boom)
  449. AudioServicesPlaySystemSound(1519);
  450. }
  451. - (void)setTitle
  452. {
  453. if (_isSelectedMode) {
  454. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  455. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  456. self.navigationItem.titleView = nil;
  457. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  458. } else {
  459. // we are in home : LOGO BRAND
  460. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  461. self.navigationItem.title = nil;
  462. UIImage *image = [self getImageLogoHome];
  463. _imageTitleHome = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)]; // IMAGE = 120 x 60
  464. _imageTitleHome.contentMode = UIViewContentModeScaleAspectFill;
  465. _imageTitleHome.translatesAutoresizingMaskIntoConstraints = NO;
  466. _imageTitleHome.image = image;
  467. // backbutton
  468. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:nil action:nil];
  469. [_imageTitleHome setUserInteractionEnabled:YES];
  470. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  471. [singleTap setNumberOfTapsRequired:1];
  472. [_imageTitleHome addGestureRecognizer:singleTap];
  473. self.navigationItem.titleView = _imageTitleHome;
  474. } else {
  475. self.navigationItem.title = _titleMain;
  476. self.navigationItem.titleView = nil;
  477. }
  478. }
  479. }
  480. - (UIImage *)getImageLogoHome
  481. {
  482. UIImage *image = [UIImage imageNamed:@"themingLogo"];
  483. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  484. if ([NCBrandOptions sharedInstance].use_themingColor && [capabilities.themingColorText isEqualToString:@"#000000"] && [UIImage imageNamed:@"themingLogoBlack"]) {
  485. image = [UIImage imageNamed:@"themingLogoBlack"];
  486. }
  487. if ([NCBrandOptions sharedInstance].use_themingLogo) {
  488. image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@-themingLogo.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl]]];
  489. if (image == nil) image = [UIImage imageNamed:@"themingLogo"];
  490. }
  491. if ([appDelegate.reachability isReachable] == NO) {
  492. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"nonetwork"] width:50 height:50 color:NCBrandColor.sharedInstance.icon];
  493. } else {
  494. return image;
  495. }
  496. }
  497. - (void)setUINavigationBarDefault
  498. {
  499. UIBarButtonItem *buttonMore, *buttonNotification;
  500. // =
  501. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  502. buttonMore.enabled = true;
  503. // <
  504. self.navigationController.navigationBar.hidden = NO;
  505. // Notification
  506. if ([appDelegate.listOfNotifications count] > 0) {
  507. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  508. buttonNotification.tintColor = NCBrandColor.sharedInstance.brandText;
  509. buttonNotification.enabled = true;
  510. }
  511. if (buttonNotification)
  512. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  513. else
  514. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  515. self.navigationItem.leftBarButtonItem = nil;
  516. }
  517. - (void)setUINavigationBarSelected
  518. {
  519. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  520. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  521. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  522. self.navigationItem.leftBarButtonItem = leftButton;
  523. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  524. }
  525. - (void)cancelSelect
  526. {
  527. [self tableViewSelect:NO];
  528. [appDelegate.reSelectMenu close];
  529. }
  530. - (void)closeAllMenu
  531. {
  532. // close Menu
  533. [appDelegate.reSelectMenu close];
  534. [appDelegate.reMainMenu close];
  535. // Close Menu Logo
  536. [CCMenuAccount dismissMenu];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ===== Document Picker =====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  542. {
  543. NSLog(@"[LOG] Cancelled");
  544. }
  545. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  546. {
  547. NSLog(@"[LOG] Cancelled");
  548. }
  549. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  550. {
  551. documentPicker.delegate = self;
  552. [self presentViewController:documentPicker animated:YES completion:nil];
  553. }
  554. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  555. {
  556. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  557. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  558. __block NSError *error;
  559. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  560. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  561. NSString *fileName = [[NCUtility sharedInstance] createFileName:[url lastPathComponent] serverUrl:serverUrl account:appDelegate.activeAccount];
  562. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  563. NSData *data = [NSData dataWithContentsOfURL:newURL];
  564. if (data && error == nil) {
  565. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  566. tableMetadata *metadataForUpload = [tableMetadata new];
  567. metadataForUpload.account = appDelegate.activeAccount;
  568. metadataForUpload.date = [NSDate new];
  569. metadataForUpload.ocId = ocId;
  570. metadataForUpload.fileName = fileName;
  571. metadataForUpload.fileNameView = fileName;
  572. metadataForUpload.serverUrl = serverUrl;
  573. metadataForUpload.session = k_upload_session;
  574. metadataForUpload.sessionSelector = selectorUploadFile;
  575. metadataForUpload.size = data.length;
  576. metadataForUpload.status = k_metadataStatusWaitUpload;
  577. // Check il file already exists
  578. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileName]];
  579. if (metadata) {
  580. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  581. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  582. // NO OVERWITE
  583. }];
  584. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  585. // Remove record metadata
  586. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  587. // Add Medtadata for upload
  588. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  589. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  590. [appDelegate startLoadAutoDownloadUpload];
  591. }];
  592. [alertController addAction:cancelAction];
  593. [alertController addAction:overwriteAction];
  594. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  595. alertWindow.rootViewController = [[UIViewController alloc]init];
  596. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  597. [alertWindow makeKeyAndVisible];
  598. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  599. } else {
  600. // Add Medtadata for upload
  601. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  602. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  603. [appDelegate startLoadAutoDownloadUpload];
  604. }
  605. } else {
  606. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  607. }
  608. } else {
  609. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  610. }
  611. }];
  612. }
  613. }
  614. - (void)openImportDocumentPicker
  615. {
  616. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  617. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  618. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  619. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  620. documentProviderMenu.delegate = self;
  621. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  622. }
  623. #pragma --------------------------------------------------------------------------------------------
  624. #pragma mark ===== Assets Picker =====
  625. #pragma --------------------------------------------------------------------------------------------
  626. -(void)dismissFormUploadAssets
  627. {
  628. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  629. }
  630. - (void)openAssetsPickerController
  631. {
  632. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100];
  633. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nonnull assets) {
  634. if (assets.count > 0) {
  635. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  636. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  637. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets cryptated:NO session:k_upload_session delegate:self];
  638. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  639. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  640. [self presentViewController:navigationController animated:YES completion:nil];
  641. });
  642. }
  643. }];
  644. }
  645. #pragma --------------------------------------------------------------------------------------------
  646. #pragma mark ===== Save selected File =====
  647. #pragma --------------------------------------------------------------------------------------------
  648. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  649. {
  650. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  651. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  652. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  653. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  654. if (image)
  655. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  656. else
  657. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  658. }
  659. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  660. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  661. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  662. } else {
  663. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  664. }
  665. }
  666. if (status != PHAuthorizationStatusAuthorized) {
  667. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  668. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  669. [alertController addAction:okAction];
  670. [self presentViewController:alertController animated:YES completion:nil];
  671. }
  672. }
  673. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  674. {
  675. if (error)
  676. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  677. else
  678. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  679. }
  680. - (void)saveSelectedFiles
  681. {
  682. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  683. return;
  684. NSLog(@"[LOG] Start download selected files ...");
  685. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  686. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  687. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  688. for (tableMetadata *metadata in metadatas) {
  689. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  690. metadata.session = k_download_session;
  691. metadata.sessionError = @"";
  692. metadata.sessionSelector = selectorSave;
  693. metadata.status = k_metadataStatusWaitDownload;
  694. // Add Metadata for Download
  695. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  696. [appDelegate startLoadAutoDownloadUpload];
  697. }
  698. }
  699. [_hud hideHud];
  700. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  701. });
  702. [self tableViewSelect:NO];
  703. }
  704. #pragma --------------------------------------------------------------------------------------------
  705. #pragma mark ==== View Notification ====
  706. #pragma --------------------------------------------------------------------------------------------
  707. - (void)viewNotification
  708. {
  709. if ([appDelegate.listOfNotifications count] > 0) {
  710. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  711. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  712. [self presentViewController:notificationVC animated:YES completion:nil];
  713. }
  714. }
  715. #pragma mark -
  716. #pragma --------------------------------------------------------------------------------------------
  717. #pragma mark ===== Peek & Pop =====
  718. #pragma --------------------------------------------------------------------------------------------
  719. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  720. {
  721. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  722. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  723. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  724. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  725. if (cell) {
  726. previewingContext.sourceRect = cell.frame;
  727. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  728. viewController.metadata = metadata;
  729. viewController.imageFile = cell.file.image;
  730. viewController.showOpenIn = true;
  731. viewController.showShare = true;
  732. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  733. viewController.showOpenInternalViewer = true;
  734. }
  735. return viewController;
  736. }
  737. return nil;
  738. }
  739. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  740. {
  741. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  742. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  743. }
  744. #pragma --------------------------------------------------------------------------------------------
  745. #pragma mark ==== Download ====
  746. #pragma --------------------------------------------------------------------------------------------
  747. - (void)downloadSelectedFilesFolders
  748. {
  749. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  750. return;
  751. NSLog(@"[LOG] Start download selected ...");
  752. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  753. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  754. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  755. for (tableMetadata *metadata in selectedMetadatas) {
  756. if (metadata.directory) {
  757. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  758. } else {
  759. [[CCSynchronize sharedSynchronize] readFile:metadata.ocId fileName:metadata.fileName serverUrl:metadata.serverUrl selector:selectorReadFileWithDownload account:appDelegate.activeAccount];
  760. }
  761. }
  762. [_hud hideHud];
  763. });
  764. [self tableViewSelect:NO];
  765. }
  766. #pragma --------------------------------------------------------------------------------------------
  767. #pragma mark ===== Upload new Photos/Videos =====
  768. #pragma --------------------------------------------------------------------------------------------
  769. //
  770. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  771. //
  772. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  773. {
  774. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  775. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  776. // if request create the folder for Auto Upload & the subfolders
  777. if ([autoUploadPath isEqualToString:serverUrl])
  778. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  779. return;
  780. dispatch_async(dispatch_get_main_queue(), ^{
  781. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  782. });
  783. });
  784. }
  785. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  786. {
  787. for (PHAsset *asset in assets) {
  788. tableMetadata *metadata;
  789. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  790. NSDate *assetDate = asset.creationDate;
  791. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  792. // Create serverUrl if use sub folder
  793. if (useSubFolder) {
  794. [formatter setDateFormat:@"yyyy"];
  795. NSString *yearString = [formatter stringFromDate:assetDate];
  796. [formatter setDateFormat:@"MM"];
  797. NSString *monthString = [formatter stringFromDate:assetDate];
  798. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  799. }
  800. // Check if is in upload
  801. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] sorted:nil ascending:NO];
  802. if ([isRecordInSessions count] > 0)
  803. continue;
  804. // Prepare record metadata
  805. tableMetadata *metadataForUpload = [tableMetadata new];
  806. metadataForUpload.account = appDelegate.activeAccount;
  807. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  808. metadataForUpload.date = [NSDate new];
  809. metadataForUpload.ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  810. metadataForUpload.fileName = fileName;
  811. metadataForUpload.fileNameView = fileName;
  812. metadataForUpload.serverUrl = serverUrl;
  813. metadataForUpload.session = session;
  814. metadataForUpload.sessionSelector = selectorUploadFile;
  815. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  816. metadataForUpload.status = k_metadataStatusWaitUpload;
  817. NSString *fileNameExtension = [fileName pathExtension];
  818. NSString *fileNameWithoutExtension = [fileName stringByDeletingPathExtension];
  819. if ([[fileNameExtension lowercaseString] isEqualToString:@"heic"] && [CCUtility getFormatCompatibility]) {
  820. NSString *fileNameCompatibility = [fileNameWithoutExtension stringByAppendingString:@".jpg"];
  821. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileNameCompatibility]];
  822. } else {
  823. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileName]];
  824. }
  825. // Check il file already exists
  826. if (metadata) {
  827. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileNameWithoutExtension message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  828. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }];
  829. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  830. // Remove record metadata
  831. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  832. // Add Medtadata for upload
  833. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  834. [appDelegate startLoadAutoDownloadUpload];
  835. }];
  836. [alertController addAction:cancelAction];
  837. [alertController addAction:overwriteAction];
  838. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  839. alertWindow.rootViewController = [[UIViewController alloc]init];
  840. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  841. [alertWindow makeKeyAndVisible];
  842. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  843. } else {
  844. // Add Medtadata for upload
  845. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  846. [appDelegate startLoadAutoDownloadUpload];
  847. }
  848. }
  849. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  850. }
  851. #pragma --------------------------------------------------------------------------------------------
  852. #pragma mark ==== Read File ====
  853. #pragma --------------------------------------------------------------------------------------------
  854. - (void)readFileReloadFolder
  855. {
  856. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  857. return;
  858. // RichWorkspace
  859. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  860. self.richWorkspaceText = directory.richWorkspace;
  861. [self setTableViewHeader];
  862. // Load Datasource
  863. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  864. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  865. });
  866. [[NCCommunication sharedInstance] readFileOrFolderWithServerUrlFileName:self.serverUrl depth:@"0" account:appDelegate.activeAccount completionHandler:^(NSString *account, NSArray*files, NSInteger errorCode, NSString *errorMessage) {
  867. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  868. tableMetadata *metadataFolder = [tableMetadata new];
  869. (void)[[NCNetworking sharedInstance] convertFiles:files urlString:appDelegate.activeUrl serverUrl:self.serverUrl user:appDelegate.activeUser metadataFolder:&metadataFolder];
  870. // Rich Workspace
  871. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadataFolder.ocId serverUrl:self.serverUrl richWorkspace:metadataFolder.richWorkspace account:account];
  872. self.richWorkspaceText = metadataFolder.richWorkspace;
  873. [self setTableViewHeader];
  874. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadataFolder.serverUrl]];
  875. // Read folder: No record, Change etag or BLINK
  876. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadataFolder.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  877. [self readFolder:self.serverUrl];
  878. }
  879. } else if (errorCode != 0) {
  880. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorMessage delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  881. } else {
  882. NSLog(@"[LOG] It has been changed user during networking process, error.");
  883. }
  884. }];
  885. }
  886. #pragma --------------------------------------------------------------------------------------------
  887. #pragma mark ==== Read Folder ====
  888. #pragma --------------------------------------------------------------------------------------------
  889. - (void)insertMetadatasWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  890. {
  891. // stoprefresh
  892. [refreshControl endRefreshing];
  893. // save metadataFolder
  894. _metadataFolder = metadataFolder;
  895. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  896. if (tableAccount == nil) {
  897. return;
  898. }
  899. if (self.searchController.isActive == NO) {
  900. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:nil etag:metadataFolder.etag ocId:metadataFolder.ocId encrypted:metadataFolder.e2eEncrypted richWorkspace:nil account:account];
  901. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND (status == %d OR status == %d)", account, serverUrl, k_metadataStatusNormal, k_metadataStatusHide]];
  902. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithServerUrl:serverUrl account:account];
  903. }
  904. NSArray *metadatasInDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", account, serverUrl, k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusDownloadError] sorted:nil ascending:NO];
  905. // insert in Database
  906. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  907. // insert in Database the /
  908. if (metadataFolder != nil) {
  909. _metadataFolder = [[NCManageDatabase sharedInstance] addMetadata:metadataFolder];
  910. }
  911. // reinsert metadatas in Download
  912. if (metadatasInDownload) {
  913. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload];
  914. }
  915. // File is changed ??
  916. if (!self.searchController.isActive && metadatasToInsertInDB) {
  917. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  918. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:serverUrl account:account withDownload:NO];
  919. });
  920. }
  921. // Search Mode
  922. if (self.searchController.isActive) {
  923. // Fix managed -> Unmanaged _searchResultMetadatas
  924. if (metadatasToInsertInDB)
  925. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  926. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  927. }
  928. // this is the same directory
  929. if ([serverUrl isEqualToString:_serverUrl] && !self.searchController.isActive) {
  930. // reload
  931. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  932. [self tableViewReloadData];
  933. }
  934. // E2EE Is encrypted folder get metadata
  935. if (_metadataFolder.e2eEncrypted) {
  936. NSString *metadataFolderocId = metadataFolder.ocId;
  937. // Read Metadata
  938. if ([CCUtility isEndToEndEnabled:account]) {
  939. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  940. NSString *metadata;
  941. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata ocId:metadataFolderocId user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  942. dispatch_async(dispatch_get_main_queue(), ^{
  943. if (error) {
  944. if (error.code != kOCErrorServerPathNotFound)
  945. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  946. } else {
  947. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:tableAccount.url] == false)
  948. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  949. else
  950. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  951. }
  952. });
  953. });
  954. } else {
  955. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  956. }
  957. }
  958. // rewrite title
  959. [self setTitle];
  960. }
  961. - (void)readFolder:(NSString *)serverUrl
  962. {
  963. // init control
  964. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  965. [refreshControl endRefreshing];
  966. return;
  967. }
  968. // Search Mode
  969. if (self.searchController.isActive) {
  970. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  971. _searchFileName = @""; // forced reload searchg
  972. [self updateSearchResultsForSearchController:self.searchController];
  973. return;
  974. }
  975. _loadingFolder = YES;
  976. [self tableViewReloadData];
  977. [[OCNetworking sharedManager] readFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl depth:@"1" completion:^(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode) {
  978. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  979. [self insertMetadatasWithAccount:account serverUrl:serverUrl metadataFolder:metadataFolder metadatas:metadatas];
  980. } else if (errorCode != 0) {
  981. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  982. } else {
  983. NSLog(@"[LOG] It has been changed user during networking process, error.");
  984. }
  985. _loadingFolder = NO;
  986. }];
  987. }
  988. #pragma mark -
  989. #pragma --------------------------------------------------------------------------------------------
  990. #pragma mark ===== Search =====
  991. #pragma --------------------------------------------------------------------------------------------
  992. - (void)searchStartTimer
  993. {
  994. if (self.searchController.isActive == false) {
  995. return;
  996. }
  997. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  998. [[OCNetworking sharedManager] searchWithAccount:appDelegate.activeAccount fileName:_searchFileName serverUrl:startDirectory contentType:nil lteDateLastModified:nil gteDateLastModified:nil depth:@"infinity" completion:^(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode) {
  999. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1000. #if TARGET_OS_SIMULATOR
  1001. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  1002. if (capabilities.isFulltextsearchEnabled) {
  1003. [[OCNetworking sharedManager] fullTextSearchWithAccount:appDelegate.activeAccount text:_searchFileName page:1 completion:^(NSString *account, NSArray *items, NSString *message, NSInteger errorCode) {
  1004. NSLog(@"x");
  1005. }];
  1006. }
  1007. #endif
  1008. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1009. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  1010. } else {
  1011. if (errorCode != 0) {
  1012. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1013. } else {
  1014. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1015. }
  1016. _searchFileName = @"";
  1017. }
  1018. }];
  1019. _noFilesSearchTitle = @"";
  1020. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1021. [self.tableView reloadEmptyDataSet];
  1022. }
  1023. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1024. {
  1025. // Color text "Cancel"
  1026. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandText];
  1027. if (searchController.isActive) {
  1028. [self deleteRefreshControl];
  1029. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1030. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1031. _searchFileName = fileName;
  1032. // First : filter
  1033. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1034. [_searchResultMetadatas removeAllObjects];
  1035. for (tableMetadata *record in records)
  1036. [_searchResultMetadatas addObject:record];
  1037. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  1038. // Version >= 12
  1039. if ([[NCManageDatabase sharedInstance] getServerVersionWithAccount:appDelegate.activeAccount] >= 12) {
  1040. [_timerWaitInput invalidate];
  1041. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1042. }
  1043. }
  1044. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1045. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1046. }
  1047. } else {
  1048. [self createRefreshControl];
  1049. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1050. }
  1051. }
  1052. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1053. {
  1054. [self cancelSearchBar];
  1055. }
  1056. - (void)cancelSearchBar
  1057. {
  1058. if (self.searchController.active) {
  1059. [self.searchController setActive:NO];
  1060. _searchFileName = @"";
  1061. _dateReadDataSource = nil;
  1062. _searchResultMetadatas = [NSMutableArray new];
  1063. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1064. }
  1065. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1066. [self setTableViewHeader];
  1067. });
  1068. }
  1069. #pragma mark -
  1070. #pragma --------------------------------------------------------------------------------------------
  1071. #pragma mark ===== Delete File or Folder =====
  1072. #pragma --------------------------------------------------------------------------------------------
  1073. - (void)deleteFile
  1074. {
  1075. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1076. return;
  1077. NSArray *metadatas;
  1078. if ([_selectedocIdsMetadatas count] > 0) {
  1079. metadatas = [_selectedocIdsMetadatas allValues];
  1080. } else {
  1081. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1082. }
  1083. // remove optimization
  1084. _dateReadDataSource = nil;
  1085. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderocId:_metadataFolder.ocId completion:^(NSInteger errorCode, NSString *message) {
  1086. // Reload
  1087. if (self.searchController.isActive)
  1088. [self readFolder:self.serverUrl];
  1089. else
  1090. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1091. }];
  1092. // End Select Table View
  1093. [self tableViewSelect:NO];
  1094. }
  1095. #pragma --------------------------------------------------------------------------------------------
  1096. #pragma mark ===== Rename =====
  1097. #pragma --------------------------------------------------------------------------------------------
  1098. - (void)renameFile:(NSArray *)arguments
  1099. {
  1100. tableMetadata *metadata = [arguments objectAtIndex:0];
  1101. NSString *fileName = [arguments objectAtIndex:1];
  1102. // E2EE
  1103. if (_metadataFolder.e2eEncrypted) {
  1104. // verify if exists the new fileName
  1105. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1106. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1107. return;
  1108. }
  1109. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1110. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:self.serverUrl fileNameRename:metadata.fileName fileNameNewRename:fileName account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1111. if (error) {
  1112. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1113. } else {
  1114. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithServerUrl:metadata.serverUrl fileName:metadata.fileName newFileNameView:fileName account:appDelegate.activeAccount];
  1115. // Move file system
  1116. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], metadata.fileNameView];
  1117. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], fileName];
  1118. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1119. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:fileName] error:nil];
  1120. }
  1121. // Unlock
  1122. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1123. if (tableLock != nil) {
  1124. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:self.serverUrl ocId:_metadataFolder.ocId token:tableLock.token user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1125. if (error) {
  1126. [[NCContentPresenter shared] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1127. }
  1128. }
  1129. dispatch_async(dispatch_get_main_queue(), ^{
  1130. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1131. });
  1132. });
  1133. } else {
  1134. // verify permission
  1135. BOOL permission = [[NCUtility sharedInstance] permissionsContainsString:metadata.permissions permissions:k_permission_can_rename];
  1136. if (![metadata.permissions isEqualToString:@""] && permission == false) {
  1137. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_no_permission_modify_file_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1138. return;
  1139. }
  1140. // Plain
  1141. NSString *fileNameNew = [CCUtility removeForbiddenCharactersServer:fileName];
  1142. if ([fileName length] == 0 || [fileName isEqualToString:metadata.fileNameView]) {
  1143. return;
  1144. }
  1145. // Verify if exists the fileName TO
  1146. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:metadata.serverUrl fileName:fileNameNew completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1147. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1148. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1149. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }];
  1150. [alert addAction:ok];
  1151. [self presentViewController:alert animated:YES completion:nil];
  1152. } else if (errorCode != 0) {
  1153. if (errorCode == kOCErrorServerPathNotFound) {
  1154. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1155. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, fileNameNew];
  1156. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1157. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1158. // Rename metadata
  1159. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:fileNameNew ocId:metadata.ocId];
  1160. if (metadata.directory) {
  1161. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  1162. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:fileNameNew];
  1163. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadata.serverUrl]];
  1164. if (directoryTable == nil) {
  1165. [[NCContentPresenter shared] messageNotification:@"_rename_" description:@"Internal error, ServerUrl not found" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1166. return;
  1167. }
  1168. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:@"" ocId:nil encrypted:directoryTable.e2eEncrypted richWorkspace:nil account:appDelegate.activeAccount];
  1169. } else {
  1170. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:metadata.ocId date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:fileNameNew etag:nil];
  1171. // Move file system
  1172. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], metadata.fileName];
  1173. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], fileNameNew];
  1174. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1175. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileName];
  1176. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:fileNameNew];
  1177. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1178. }
  1179. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1180. } else if (errorCode != 0) {
  1181. [[NCContentPresenter shared] messageNotification:@"_rename_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1182. } else {
  1183. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1184. }
  1185. }];
  1186. } else {
  1187. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1188. }
  1189. } else {
  1190. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1191. }
  1192. }];
  1193. }
  1194. }
  1195. #pragma --------------------------------------------------------------------------------------------
  1196. #pragma mark ===== Move =====
  1197. #pragma --------------------------------------------------------------------------------------------
  1198. - (void)moveFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1199. {
  1200. // verify permission
  1201. BOOL permission = [[NCUtility sharedInstance] permissionsContainsString:metadata.permissions permissions:k_permission_can_move];
  1202. if (![metadata.permissions isEqualToString:@""] && permission == false) {
  1203. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_no_permission_modify_file_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1204. return;
  1205. }
  1206. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:serverUrlTo fileName:metadata.fileName completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1207. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1208. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1209. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1210. }];
  1211. [alert addAction:ok];
  1212. [self presentViewController:alert animated:YES completion:nil];
  1213. // End Select Table View
  1214. [self tableViewSelect:NO];
  1215. // reload Datasource
  1216. [self readFileReloadFolder];
  1217. } else if (errorCode != 0) {
  1218. if (errorCode == kOCErrorServerPathNotFound) {
  1219. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1220. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName];
  1221. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1222. [_hud hideHud];
  1223. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1224. if (metadata.directory) {
  1225. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] account:account];
  1226. }
  1227. [[NCManageDatabase sharedInstance] moveMetadataWithOcId:metadata.ocId serverUrlTo:serverUrlTo];
  1228. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:metadata.serverUrl account:account];
  1229. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrlTo account:account];
  1230. // next
  1231. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  1232. if ([_selectedocIdsMetadatas count] > 0) {
  1233. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1234. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrlTo numFile:[_selectedocIdsMetadatas count] ofFile:_numSelectedocIdsMetadatas];
  1235. } else {
  1236. // End Select Table View
  1237. [self tableViewSelect:NO];
  1238. // reload Datasource
  1239. if (self.searchController.isActive)
  1240. [self readFolder:metadata.serverUrl];
  1241. else
  1242. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1243. }
  1244. } else if (errorCode != 0) {
  1245. [[NCContentPresenter shared] messageNotification:@"_move_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1246. // End Select Table View
  1247. [self tableViewSelect:NO];
  1248. // reload Datasource
  1249. if (self.searchController.isActive)
  1250. [self readFolder:metadata.serverUrl];
  1251. else
  1252. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl ocId:nil action:k_action_NULL];
  1253. } else {
  1254. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1255. }
  1256. }];
  1257. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1258. } else {
  1259. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1260. }
  1261. } else {
  1262. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1263. }
  1264. }];
  1265. }
  1266. // DELEGATE : Select
  1267. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1268. {
  1269. if (serverUrl == nil) {
  1270. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1271. } else {
  1272. // E2EE DENIED
  1273. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1274. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1275. return;
  1276. }
  1277. if ([_selectedocIdsMetadatas count] > 0) {
  1278. _numSelectedocIdsMetadatas = [_selectedocIdsMetadatas count];
  1279. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1280. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl numFile:[_selectedocIdsMetadatas count] ofFile:_numSelectedocIdsMetadatas];
  1281. } else {
  1282. _numSelectedocIdsMetadatas = 1;
  1283. [self moveFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl numFile:1 ofFile:_numSelectedocIdsMetadatas];
  1284. }
  1285. }
  1286. }
  1287. - (void)moveOpenWindow:(NSArray *)indexPaths
  1288. {
  1289. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1290. return;
  1291. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1292. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1293. viewController.delegate = self;
  1294. viewController.hideButtonCreateFolder = false;
  1295. viewController.selectFile = false;
  1296. viewController.includeDirectoryE2EEncryption = false;
  1297. viewController.includeImages = false;
  1298. viewController.type = @"";
  1299. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1300. viewController.layoutViewSelect = k_layout_view_move;
  1301. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1302. [self presentViewController:navigationController animated:YES completion:nil];
  1303. }
  1304. #pragma --------------------------------------------------------------------------------------------
  1305. #pragma mark ===== Create folder =====
  1306. #pragma --------------------------------------------------------------------------------------------
  1307. - (void)createFolder
  1308. {
  1309. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1310. NSString *message;
  1311. UIAlertController *alertController;
  1312. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1313. message = @"/";
  1314. } else {
  1315. message = [serverUrl lastPathComponent];
  1316. }
  1317. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1318. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1319. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1320. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1321. }];
  1322. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1323. NSLog(@"[LOG] Cancel action");
  1324. }];
  1325. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1326. UITextField *fileName = alertController.textFields.firstObject;
  1327. [self createFolder:fileName.text serverUrl:serverUrl];
  1328. }];
  1329. okAction.enabled = NO;
  1330. [alertController addAction:cancelAction];
  1331. [alertController addAction:okAction];
  1332. [self presentViewController:alertController animated:YES completion:nil];
  1333. }
  1334. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1335. {
  1336. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1337. fileNameFolder = [[NCUtility sharedInstance] createFileName:fileNameFolder serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1338. if (![fileNameFolder length]) return;
  1339. NSString *ocIdTemp = [[NSUUID UUID] UUIDString];
  1340. // Create Directory (temp) on metadata
  1341. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES ocId:ocIdTemp serverUrl:serverUrl fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal url:@"" contentType:@""];
  1342. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1343. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  1344. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1345. // Creeate folder Networking
  1346. [[OCNetworking sharedManager] createFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileNameFolder completion:^(NSString *account, NSString *ocId, NSDate *date, NSString *message, NSInteger errorCode) {
  1347. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1348. // Delete Temp Dir
  1349. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocIdTemp]];
  1350. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1351. if (_metadataFolder.e2eEncrypted) {
  1352. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1353. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory ocId:ocId user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1354. dispatch_async(dispatch_get_main_queue(), ^{
  1355. if (error) {
  1356. [[NCContentPresenter shared] messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1357. }
  1358. [self readFolder:self.serverUrl];
  1359. });
  1360. });
  1361. } else {
  1362. [self readFolder:self.serverUrl];
  1363. }
  1364. } else {
  1365. // Delete Temp Dir
  1366. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocIdTemp]];
  1367. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1368. if (errorCode != 0) {
  1369. [[NCContentPresenter shared] messageNotification:@"_create_folder_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1370. } else {
  1371. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1372. }
  1373. }
  1374. }];
  1375. }
  1376. #pragma --------------------------------------------------------------------------------------------
  1377. #pragma mark ===== Progress & Task Button =====
  1378. #pragma --------------------------------------------------------------------------------------------
  1379. - (void)triggerProgressTask:(NSNotification *)notification
  1380. {
  1381. if (sectionDataSource.ocIdIndexPath != nil) {
  1382. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1383. }
  1384. }
  1385. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1386. {
  1387. UITouch *touch = [[event allTouches] anyObject];
  1388. CGPoint location = [touch locationInView:self.tableView];
  1389. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1390. if ([self indexPathIsValid:indexPath]) {
  1391. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1392. if (metadataSection) {
  1393. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1394. if (metadata)
  1395. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1396. }
  1397. }
  1398. }
  1399. - (void)cancelAllTask:(id)sender
  1400. {
  1401. CGPoint location = [sender locationInView:self.tableView];
  1402. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1403. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1404. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1405. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1406. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1407. [NCUtility.sharedInstance stopActivityIndicator];
  1408. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1409. }]];
  1410. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1411. alertController.popoverPresentationController.sourceView = self.tableView;
  1412. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1413. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1414. [alertController.view layoutIfNeeded];
  1415. [self presentViewController:alertController animated:YES completion:nil];
  1416. }
  1417. #pragma --------------------------------------------------------------------------------------------
  1418. #pragma mark ===== Tap =====
  1419. #pragma --------------------------------------------------------------------------------------------
  1420. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1421. {
  1422. CGPoint location = [tapGesture locationInView:self.tableView];
  1423. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1424. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1425. if (metadata) {
  1426. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1427. }
  1428. }
  1429. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1430. {
  1431. CGPoint location = [tapGesture locationInView:self.tableView];
  1432. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1433. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1434. if (metadata) {
  1435. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1436. }
  1437. }
  1438. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1439. {
  1440. CGPoint location = [tapGesture locationInView:self.tableView];
  1441. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1442. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1443. if (metadata) {
  1444. }
  1445. }
  1446. #pragma --------------------------------------------------------------------------------------------
  1447. #pragma mark ===== Rich Workspace =====
  1448. #pragma --------------------------------------------------------------------------------------------
  1449. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1450. {
  1451. [UIView animateWithDuration:0.5 animations:^{
  1452. [self.tableView setContentOffset:CGPointMake(0, heightSearchBar)];
  1453. } completion:^(BOOL finished) {
  1454. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1455. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1456. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1457. viewerRichWorkspace.serverUrl = self.serverUrl;
  1458. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1459. [self presentViewController:navigationController animated:NO completion:NULL];
  1460. }];
  1461. }
  1462. - (void)createRichWorkspace
  1463. {
  1464. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1465. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1466. if (metadata) {
  1467. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1468. } else {
  1469. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1470. }
  1471. }
  1472. #pragma --------------------------------------------------------------------------------------------
  1473. #pragma mark ===== Favorite =====
  1474. #pragma --------------------------------------------------------------------------------------------
  1475. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1476. {
  1477. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1478. [[NCCommunication sharedInstance] setFavoriteWithUrlString:appDelegate.activeUrl fileName:fileNameServerUrl favorite:favorite account:appDelegate.activeAccount completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDecription) {
  1479. if (errorCode == 0 && [appDelegate.activeAccount isEqualToString:account]) {
  1480. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithOcId:metadata.ocId favorite:favorite];
  1481. _dateReadDataSource = nil;
  1482. if (self.searchController.isActive)
  1483. [self readFolder:self.serverUrl];
  1484. else
  1485. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1486. if (metadata.directory && favorite) {
  1487. NSString *selector;
  1488. if ([CCUtility getFavoriteOffline])
  1489. selector = selectorReadFolderWithDownload;
  1490. else
  1491. selector = selectorReadFolder;
  1492. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector account:appDelegate.activeAccount];
  1493. }
  1494. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1495. metadata.favorite = favorite;
  1496. metadata.session = k_download_session;
  1497. metadata.sessionError = @"";
  1498. metadata.sessionSelector = selectorDownloadSynchronize;
  1499. metadata.status = k_metadataStatusWaitDownload;
  1500. // Add Metadata for Download
  1501. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1502. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1503. [appDelegate startLoadAutoDownloadUpload];
  1504. }
  1505. } else if (errorCode != 0) {
  1506. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDecription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1507. } else {
  1508. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1509. }
  1510. }];
  1511. }
  1512. #pragma --------------------------------------------------------------------------------------------
  1513. #pragma mark ==== Menu LOGO ====
  1514. #pragma --------------------------------------------------------------------------------------------
  1515. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1516. {
  1517. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1518. return;
  1519. // Brand
  1520. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1521. return;
  1522. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1523. NSMutableArray *menuArray = [NSMutableArray new];
  1524. for (NSString *account in listAccount) {
  1525. CCMenuItem *item = [[CCMenuItem alloc] init];
  1526. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1527. item.argument = account;
  1528. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1529. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1530. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1531. if (avatar) {
  1532. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1533. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1534. CGSize imageSize = avatarImageView.bounds.size;
  1535. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1536. CGContextRef context = UIGraphicsGetCurrentContext();
  1537. [avatarImageView.layer renderInContext:context];
  1538. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1539. UIGraphicsEndImageContext();
  1540. } else {
  1541. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1542. }
  1543. item.image = avatar;
  1544. item.target = self;
  1545. if ([account isEqualToString:appDelegate.activeAccount]) {
  1546. item.action = nil;
  1547. [menuArray insertObject:item atIndex:0];
  1548. } else {
  1549. item.action = @selector(changeDefaultAccount:);
  1550. [menuArray addObject:item];
  1551. }
  1552. }
  1553. // Add + new account
  1554. CCMenuItem *item = [[CCMenuItem alloc] init];
  1555. item.title = NSLocalizedString(@"_add_account_", nil);
  1556. item.argument = @"";
  1557. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1558. item.target = self;
  1559. item.action = @selector(addNewAccount:);
  1560. [menuArray addObject:item];
  1561. OptionalConfiguration options;
  1562. Color backgroundColor;
  1563. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1564. backgroundColor.R = componentsBackgroundColor[0];
  1565. backgroundColor.G = componentsBackgroundColor[1];
  1566. backgroundColor.B = componentsBackgroundColor[2];
  1567. options.arrowSize = 9;
  1568. options.marginXSpacing = 7;
  1569. options.marginYSpacing = 10;
  1570. options.intervalSpacing = 20;
  1571. options.menuCornerRadius = 6.5;
  1572. options.maskToBackground = NO;
  1573. options.shadowOfMenu = YES;
  1574. options.hasSeperatorLine = YES;
  1575. options.seperatorLineHasInsets = YES;
  1576. options.textColor = NCBrandColor.sharedInstance.textView;
  1577. options.menuBackgroundColor = backgroundColor;
  1578. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1579. CGRect rect = self.view.frame;
  1580. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1581. CGFloat safeAreaTop = 0;
  1582. CGFloat offsetY = 35;
  1583. if (@available(iOS 11, *)) {
  1584. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1585. }
  1586. rect.origin.y = locationY + safeAreaTop + offsetY;
  1587. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1588. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1589. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1590. }
  1591. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1592. {
  1593. // LOGOUT
  1594. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1595. if (tableAccount) {
  1596. // LOGIN
  1597. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1598. // go to home sweet home
  1599. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1600. }
  1601. }
  1602. - (void)addNewAccount:(CCMenuItem *)sender
  1603. {
  1604. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1605. }
  1606. #pragma --------------------------------------------------------------------------------------------
  1607. #pragma mark ==== ReMenu ====
  1608. #pragma --------------------------------------------------------------------------------------------
  1609. - (void)createReMenuBackgroundView:(REMenu *)menu
  1610. {
  1611. CGFloat safeAreaBottom = 0;
  1612. CGFloat safeAreaTop = 0;
  1613. CGFloat statusBar = 0;
  1614. if (@available(iOS 11, *)) {
  1615. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1616. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1617. }
  1618. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1619. statusBar = 13;
  1620. }
  1621. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1622. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1623. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1624. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1625. [UIView animateWithDuration:0.2 animations:^{
  1626. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1627. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1628. if (y>minimum) {
  1629. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1630. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1631. }
  1632. }];
  1633. }
  1634. - (void)createReMainMenu
  1635. {
  1636. NSString *title;
  1637. //NSString *groupBy = [CCUtility getGroupBySettings];
  1638. NSString *sorted = [CCUtility getOrderSettings];
  1639. BOOL ascending = [CCUtility getAscendingSettings];
  1640. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  1641. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1642. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"selectLight"] width:50 height:50 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1643. if ([sectionDataSource.allRecordsDataSource count] > 0) [self tableViewSelect:YES];
  1644. }];
  1645. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1646. if ([sorted isEqualToString:@"fileName"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_a_z_", nil)]; }
  1647. else title = NSLocalizedString(@"_order_by_name_a_z_", nil);
  1648. appDelegate.sortFileNameAZItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameAZ"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1649. [CCUtility setOrderSettings:@"fileName"];
  1650. [CCUtility setAscendingSettings:true];
  1651. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1652. }];
  1653. if ([sorted isEqualToString:@"fileName"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_z_a_", nil)]; }
  1654. else title = NSLocalizedString(@"_order_by_name_z_a_", nil);
  1655. appDelegate.sortFileNameZAItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameZA"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1656. [CCUtility setOrderSettings:@"fileName"];
  1657. [CCUtility setAscendingSettings:false];
  1658. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1659. }];
  1660. if ([sorted isEqualToString:@"date"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_more_recent_", nil)]; }
  1661. else title = NSLocalizedString(@"_order_by_date_more_recent_", nil);
  1662. appDelegate.sortDateMoreRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateMoreRecent"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1663. [CCUtility setOrderSettings:@"date"];
  1664. [CCUtility setAscendingSettings:false];
  1665. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1666. }];
  1667. if ([sorted isEqualToString:@"date"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_less_recent_", nil)]; }
  1668. else title = NSLocalizedString(@"_order_by_date_less_recent_", nil);
  1669. appDelegate.sortDateLessRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateLessRecent"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1670. [CCUtility setOrderSettings:@"date"];
  1671. [CCUtility setAscendingSettings:true];
  1672. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1673. }];
  1674. if ([sorted isEqualToString:@"size"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_smallest_", nil)]; }
  1675. else title = NSLocalizedString(@"_order_by_size_smallest_", nil);
  1676. appDelegate.sortSmallestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortSmallest"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1677. [CCUtility setOrderSettings:@"size"];
  1678. [CCUtility setAscendingSettings:true];
  1679. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1680. }];
  1681. if ([sorted isEqualToString:@"size"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_largest_", nil)]; }
  1682. else title = NSLocalizedString(@"_order_by_size_largest_", nil);
  1683. appDelegate.sortLargestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortLargest"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1684. [CCUtility setOrderSettings:@"size"];
  1685. [CCUtility setAscendingSettings:false];
  1686. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1687. }];
  1688. /*
  1689. // ITEM GROUP ALPHABETIC -----------------------------------------------------------------------------------------------------
  1690. if ([groupBy isEqualToString:@"alphabetic"]) { title = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1691. else { title = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1692. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1693. if ([groupBy isEqualToString:@"alphabetic"]) [CCUtility setGroupBySettings:@"none"];
  1694. else [CCUtility setGroupBySettings:@"alphabetic"];
  1695. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1696. }];
  1697. // ITEM GROUP TYPEFILE -------------------------------------------------------------------------------------------------------
  1698. if ([groupBy isEqualToString:@"typefile"]) { title = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1699. else { title = NSLocalizedString(@"_group_typefile_no_", nil); }
  1700. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByFile"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1701. if ([groupBy isEqualToString:@"typefile"]) [CCUtility setGroupBySettings:@"none"];
  1702. else [CCUtility setGroupBySettings:@"typefile"];
  1703. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1704. }];
  1705. // ITEM GROUP DATE -------------------------------------------------------------------------------------------------------
  1706. if ([groupBy isEqualToString:@"date"]) { title = NSLocalizedString(@"_group_date_yes_", nil); }
  1707. else { title = NSLocalizedString(@"_group_date_no_", nil); }
  1708. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1709. if ([groupBy isEqualToString:@"date"]) [CCUtility setGroupBySettings:@"none"];
  1710. else [CCUtility setGroupBySettings:@"date"];
  1711. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1712. }];
  1713. */
  1714. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1715. if ([CCUtility getDirectoryOnTop]) { title = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1716. else { title = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1717. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"foldersOnTop"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1718. if ([CCUtility getDirectoryOnTop]) [CCUtility setDirectoryOnTop:NO];
  1719. else [CCUtility setDirectoryOnTop:YES];
  1720. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1721. }];
  1722. // ITEM ADD FOLDER INFO -----------------------------------------------------------------------------------------------
  1723. appDelegate.addFolderInfo = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_add_folder_info_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"addFolderInfo"] width:50 height:50 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1724. [self createRichWorkspace];
  1725. }];
  1726. // REMENU --------------------------------------------------------------------------------------------------------------
  1727. if (capabilities.versionMajor >= k_nextcloud_version_18_0 && self.richWorkspaceText.length == 0) {
  1728. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.sortFileNameAZItem, appDelegate.sortFileNameZAItem, appDelegate.sortDateMoreRecentItem, appDelegate.sortDateLessRecentItem, appDelegate.sortSmallestItem, appDelegate.sortLargestItem, appDelegate.directoryOnTopItem, appDelegate.addFolderInfo]];
  1729. } else {
  1730. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.sortFileNameAZItem, appDelegate.sortFileNameZAItem, appDelegate.sortDateMoreRecentItem, appDelegate.sortDateLessRecentItem, appDelegate.sortSmallestItem, appDelegate.sortLargestItem, appDelegate.directoryOnTopItem]];
  1731. }
  1732. appDelegate.reMainMenu.itemHeight = 40;
  1733. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1734. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1735. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1736. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1737. appDelegate.reMainMenu.separatorHeight = 0.5;
  1738. appDelegate.reMainMenu.separatorColor = NCBrandColor.sharedInstance.separator;
  1739. appDelegate.reMainMenu.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  1740. appDelegate.reMainMenu.textColor = NCBrandColor.sharedInstance.textView;
  1741. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  1742. appDelegate.reMainMenu.textShadowColor = nil;
  1743. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  1744. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  1745. appDelegate.reMainMenu.highlightedBackgroundColor = NCBrandColor.sharedInstance.select;
  1746. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  1747. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  1748. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  1749. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1750. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  1751. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1752. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  1753. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1754. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1755. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1756. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1757. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  1758. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1759. appDelegate.reMainMenu.borderWidth = 0;
  1760. appDelegate.reMainMenu.borderColor = NCBrandColor.sharedInstance.backgroundForm;
  1761. appDelegate.reMainMenu.animationDuration = 0.2;
  1762. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  1763. appDelegate.reMainMenu.bounce = NO;
  1764. __weak typeof(self) weakSelf = self;
  1765. [appDelegate.reMainMenu setClosePreparationBlock:^{
  1766. // Backgroun reMenu (Gesture)
  1767. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1768. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1769. }];
  1770. }
  1771. - (void)toggleReMainMenu
  1772. {
  1773. if (appDelegate.reMainMenu.isOpen) {
  1774. [appDelegate.reMainMenu close];
  1775. } else {
  1776. [self createReMainMenu];
  1777. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  1778. // Backgroun reMenu & (Gesture)
  1779. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  1780. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  1781. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1782. }
  1783. }
  1784. - (void)createReSelectMenu
  1785. {
  1786. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  1787. appDelegate.selectAllItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_all_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"selectFull"] width:50 height:50 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1788. [self didSelectAll];
  1789. }];
  1790. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  1791. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1792. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  1793. }];
  1794. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  1795. appDelegate.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1796. [self downloadSelectedFilesFolders];
  1797. }];
  1798. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  1799. appDelegate.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] multiplier:2 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1800. [self saveSelectedFiles];
  1801. }];
  1802. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  1803. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:NCBrandColor.sharedInstance.icon] highlightedImage:nil action:^(REMenuItem *item) {
  1804. [self deleteFile];
  1805. }];
  1806. // E2EE
  1807. if (_metadataFolder.e2eEncrypted) {
  1808. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1809. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1810. } else {
  1811. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1812. }
  1813. } else {
  1814. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1815. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1816. } else {
  1817. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1818. }
  1819. }
  1820. appDelegate.reSelectMenu.itemHeight = 50;
  1821. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  1822. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1823. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  1824. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  1825. appDelegate.reSelectMenu.separatorHeight = 0.5;
  1826. appDelegate.reSelectMenu.separatorColor = NCBrandColor.sharedInstance.separator;
  1827. appDelegate.reSelectMenu.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  1828. appDelegate.reSelectMenu.textColor = NCBrandColor.sharedInstance.textView;
  1829. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  1830. appDelegate.reSelectMenu.textShadowColor = nil;
  1831. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  1832. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  1833. appDelegate.reSelectMenu.highlightedBackgroundColor = NCBrandColor.sharedInstance.select;
  1834. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  1835. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  1836. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  1837. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1838. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  1839. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1840. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  1841. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1842. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1843. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1844. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1845. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  1846. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1847. appDelegate.reMainMenu.borderWidth = 0;
  1848. appDelegate.reMainMenu.borderColor = NCBrandColor.sharedInstance.backgroundForm;
  1849. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  1850. appDelegate.reSelectMenu.animationDuration = 0.2;
  1851. appDelegate.reSelectMenu.bounce = NO;
  1852. __weak typeof(self) weakSelf = self;
  1853. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  1854. // Backgroun reMenu (Gesture)
  1855. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1856. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1857. }];
  1858. }
  1859. - (void)toggleReSelectMenu
  1860. {
  1861. if (appDelegate.reSelectMenu.isOpen) {
  1862. [appDelegate.reSelectMenu close];
  1863. } else {
  1864. [self createReSelectMenu];
  1865. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  1866. // Backgroun reMenu & (Gesture)
  1867. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  1868. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  1869. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1870. }
  1871. }
  1872. #pragma --------------------------------------------------------------------------------------------
  1873. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1874. #pragma --------------------------------------------------------------------------------------------
  1875. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1876. {
  1877. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1878. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1879. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1880. NSMutableArray *items = [NSMutableArray new];
  1881. if ([self indexPathIsValid:indexPath])
  1882. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1883. else
  1884. self.metadata = nil;
  1885. [self becomeFirstResponder];
  1886. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1887. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)]];
  1888. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)]];
  1889. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1890. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)]];
  1891. }
  1892. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  1893. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_internal_view_", nil) action:@selector(openInternalViewer:)]];
  1894. }
  1895. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)]];
  1896. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)]];
  1897. [menuController setMenuItems:items];
  1898. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1899. [menuController setMenuVisible:YES animated:YES];
  1900. }
  1901. }
  1902. - (BOOL)canBecomeFirstResponder
  1903. {
  1904. return YES;
  1905. }
  1906. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1907. {
  1908. // For copy file, copy files, Open in ... :
  1909. //
  1910. // NO Directory
  1911. // NO Error Passcode
  1912. // NO In Session mode (download/upload)
  1913. // NO Template
  1914. if (@selector(copyFile:) == action || @selector(openinFile:) == action || @selector(openInternalViewer:) == action) {
  1915. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1916. else return NO;
  1917. }
  1918. if (@selector(copyFiles:) == action) {
  1919. if (_isSelectedMode) {
  1920. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1921. for (tableMetadata *metadata in selectedMetadatas) {
  1922. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1923. return YES;
  1924. }
  1925. }
  1926. return NO;
  1927. }
  1928. if (@selector(pasteFile:) == action) {
  1929. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1930. NSArray *items = [pasteboard items];
  1931. if ([items count] == 1) {
  1932. // Value : (NSData) ocId
  1933. NSDictionary *dic = [items objectAtIndex:0];
  1934. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1935. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1936. if (ocId) {
  1937. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1938. if (metadata) {
  1939. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1940. } else {
  1941. return NO;
  1942. }
  1943. }
  1944. }
  1945. return NO;
  1946. }
  1947. if (@selector(pasteFiles:) == action) {
  1948. BOOL isValid = NO;
  1949. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1950. NSArray *items = [pasteboard items];
  1951. if ([items count] <= 1) return NO;
  1952. for (NSDictionary *dic in items) {
  1953. // Value : (NSData) ocId
  1954. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1955. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1956. if (ocId) {
  1957. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1958. if (metadata) {
  1959. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1960. isValid = YES;
  1961. } else {
  1962. isValid = NO;
  1963. break;
  1964. }
  1965. } else {
  1966. isValid = NO;
  1967. break;
  1968. }
  1969. } else {
  1970. isValid = NO;
  1971. break;
  1972. }
  1973. }
  1974. return isValid;
  1975. }
  1976. return NO;
  1977. }
  1978. /************************************ COPY ************************************/
  1979. - (void)copyFile:(id)sender
  1980. {
  1981. // Remove all item
  1982. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1983. pasteboard.items = [[NSArray alloc] init];
  1984. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1985. [self copyFileToPasteboard:self.metadata];
  1986. } else {
  1987. self.metadata.session = k_download_session;
  1988. self.metadata.sessionError = @"";
  1989. self.metadata.sessionSelector = selectorLoadCopy;
  1990. self.metadata.status = k_metadataStatusWaitDownload;
  1991. // Add Metadata for Download
  1992. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1993. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  1994. [appDelegate startLoadAutoDownloadUpload];
  1995. }
  1996. }
  1997. - (void)copyFiles:(id)sender
  1998. {
  1999. // Remove all item
  2000. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2001. pasteboard.items = [[NSArray alloc] init];
  2002. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2003. for (tableMetadata *metadata in selectedMetadatas) {
  2004. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  2005. [self copyFileToPasteboard:metadata];
  2006. } else {
  2007. metadata.session = k_download_session;
  2008. metadata.sessionError = @"";
  2009. metadata.sessionSelector = selectorLoadCopy;
  2010. metadata.status = k_metadataStatusWaitDownload;
  2011. // Add Metadata for Download
  2012. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2013. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  2014. [appDelegate startLoadAutoDownloadUpload];
  2015. }
  2016. }
  2017. [self tableViewSelect:NO];
  2018. }
  2019. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2020. {
  2021. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2022. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2023. // Value : (NSData) ocId
  2024. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  2025. [items addObject:item];
  2026. [pasteboard setItems:items];
  2027. }
  2028. /************************************ OPEN IN ... ******************************/
  2029. - (void)openinFile:(id)sender
  2030. {
  2031. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  2032. }
  2033. /************************************ OPEN INTERNAL VIEWER ... ******************************/
  2034. - (void)openInternalViewer:(id)sender
  2035. {
  2036. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileInternalView];
  2037. }
  2038. /************************************ PASTE ************************************/
  2039. - (void)pasteFile:(id)sender
  2040. {
  2041. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2042. [self uploadFilePasteArray:[pasteboard items]];
  2043. }
  2044. - (void)pasteFiles:(id)sender
  2045. {
  2046. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2047. [self uploadFilePasteArray:[pasteboard items]];
  2048. }
  2049. - (void)uploadFilePasteArray:(NSArray *)items
  2050. {
  2051. for (NSDictionary *dic in items) {
  2052. // Value : (NSData) ocId
  2053. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  2054. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  2055. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  2056. if (metadata) {
  2057. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  2058. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  2059. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  2060. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  2061. tableMetadata *metadataForUpload = [tableMetadata new];
  2062. metadataForUpload.account = appDelegate.activeAccount;
  2063. metadataForUpload.date = [NSDate new];
  2064. metadataForUpload.ocId = ocId;
  2065. metadataForUpload.fileName = fileName;
  2066. metadataForUpload.fileNameView = fileName;
  2067. metadataForUpload.serverUrl = self.serverUrl;
  2068. metadataForUpload.session = k_upload_session;
  2069. metadataForUpload.sessionSelector = selectorUploadFile;
  2070. metadataForUpload.size = metadata.size;
  2071. metadataForUpload.status = k_metadataStatusWaitUpload;
  2072. // Add Medtadata for upload
  2073. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2074. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2075. }
  2076. }
  2077. }
  2078. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2079. [appDelegate startLoadAutoDownloadUpload];
  2080. }
  2081. #pragma --------------------------------------------------------------------------------------------
  2082. #pragma mark ===== Lock Passcode =====
  2083. #pragma --------------------------------------------------------------------------------------------
  2084. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2085. {
  2086. return _failedAttempts;
  2087. }
  2088. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2089. {
  2090. return _lockUntilDate;
  2091. }
  2092. - (void)passcodeViewCloseButtonPressed:(id)sender
  2093. {
  2094. [self dismissViewControllerAnimated:YES completion:nil];
  2095. }
  2096. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2097. {
  2098. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2099. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2100. _lockUntilDate = nil;
  2101. _failedAttempts = 0;
  2102. aResultHandler(YES);
  2103. } else aResultHandler(NO);
  2104. } else aResultHandler(YES);
  2105. }
  2106. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2107. {
  2108. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2109. switch (aViewController.type) {
  2110. case BKPasscodeViewControllerCheckPasscodeType: {
  2111. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2112. // possiamo procedere alla prossima directory
  2113. [self performSegueDirectoryWithControlPasscode:false metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2114. // avviamo la sessione Passcode Lock con now
  2115. appDelegate.sessionePasscodeLock = [NSDate date];
  2116. }
  2117. // disattivazione lock cartella
  2118. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2119. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2120. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  2121. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  2122. }
  2123. [self tableViewReloadData];
  2124. }
  2125. }
  2126. break;
  2127. default:
  2128. break;
  2129. }
  2130. }
  2131. - (void)comandoLockPassword
  2132. {
  2133. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2134. // se non è abilitato il Lock Passcode esci
  2135. if ([[CCUtility getBlockCode] length] == 0) {
  2136. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2137. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2138. [alertController addAction:okAction];
  2139. [self presentViewController:alertController animated:YES completion:nil];
  2140. return;
  2141. }
  2142. // se è richiesta la disattivazione si chiede la password
  2143. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2144. if (directory.lock) {
  2145. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2146. viewController.delegate = self;
  2147. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2148. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2149. viewController.inputViewTitlePassword = YES;
  2150. if ([CCUtility getSimplyBlockCode]) {
  2151. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2152. viewController.passcodeInputView.maximumLength = 6;
  2153. } else {
  2154. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2155. viewController.passcodeInputView.maximumLength = 64;
  2156. }
  2157. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2158. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2159. viewController.touchIDManager = touchIDManager;
  2160. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2161. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2162. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2163. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2164. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  2165. [self presentViewController:navigationController animated:YES completion:nil];
  2166. return;
  2167. }
  2168. // ---------------- ACTIVATE PASSWORD
  2169. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  2170. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:self.metadata.ocId];
  2171. if ([self indexPathIsValid:indexPath])
  2172. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2173. } else {
  2174. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  2175. }
  2176. }
  2177. #pragma mark -
  2178. #pragma --------------------------------------------------------------------------------------------
  2179. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2180. #pragma --------------------------------------------------------------------------------------------
  2181. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2182. {
  2183. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  2184. return NO;
  2185. // E2EE
  2186. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2187. return NO;
  2188. return YES;
  2189. }
  2190. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2191. {
  2192. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2193. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2194. return [self canOpenMenuAction:metadata];
  2195. }
  2196. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2197. {
  2198. }
  2199. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2200. {
  2201. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2202. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2203. if (direction == MGSwipeDirectionRightToLeft) {
  2204. [self actionDelete:indexPath];
  2205. }
  2206. if (direction == MGSwipeDirectionLeftToRight) {
  2207. if (self.metadata.favorite)
  2208. [self settingFavorite:self.metadata favorite:NO];
  2209. else
  2210. [self settingFavorite:self.metadata favorite:YES];
  2211. }
  2212. return YES;
  2213. }
  2214. - (void)actionDelete:(NSIndexPath *)indexPath
  2215. {
  2216. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2217. // Directory locked ?
  2218. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  2219. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2220. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  2221. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2222. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_folder_blocked_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  2223. return;
  2224. }
  2225. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2226. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2227. [self performSelector:@selector(deleteFile) withObject:nil];
  2228. }]];
  2229. if (localFile) {
  2230. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2231. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  2232. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  2233. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2234. }]];
  2235. }
  2236. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2237. }]];
  2238. alertController.popoverPresentationController.sourceView = self.tableView;
  2239. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2240. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2241. [alertController.view layoutIfNeeded];
  2242. [self presentViewController:alertController animated:YES completion:nil];
  2243. }
  2244. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2245. {
  2246. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2247. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2248. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2249. NSString *titoloLock, *titleFavorite;
  2250. if (self.metadata.favorite) {
  2251. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2252. } else {
  2253. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2254. }
  2255. if (self.metadata.directory) {
  2256. // calcolo lockServerUrl
  2257. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2258. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2259. if (directory.lock)
  2260. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2261. else
  2262. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2263. }
  2264. // ******************************************* AHKActionSheet *******************************************
  2265. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2266. actionSheet.animationDuration = 0.2;
  2267. actionSheet.buttonHeight = 50.0;
  2268. actionSheet.cancelButtonHeight = 50.0f;
  2269. actionSheet.separatorHeight = 5.0f;
  2270. actionSheet.automaticallyTintButtonImages = @(NO);
  2271. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.encrypted };
  2272. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.textView };
  2273. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.textView };
  2274. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:NCBrandColor.sharedInstance.textView };
  2275. actionSheet.separatorColor = NCBrandColor.sharedInstance.separator;
  2276. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2277. actionSheet.cancelButtonBackgroudColor = NCBrandColor.sharedInstance.backgroundForm;
  2278. // ******************************************* DIRECTORY *******************************************
  2279. if (self.metadata.directory) {
  2280. BOOL lockDirectory = NO;
  2281. BOOL isOffline = NO;
  2282. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2283. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2284. // Directory bloccata ?
  2285. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2286. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2287. if (directory.offline) isOffline = YES;
  2288. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2289. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:NCBrandColor.sharedInstance.brandElement]
  2290. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2291. height:50.0
  2292. type:AHKActionSheetButtonTypeDisabled
  2293. handler:nil
  2294. ];
  2295. [actionSheet addButtonWithTitle: titleFavorite
  2296. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:NCBrandColor.sharedInstance.yellowFavorite]
  2297. backgroundColor: NCBrandColor.sharedInstance.backgroundForm
  2298. height: 50.0
  2299. type: AHKActionSheetButtonTypeDefault
  2300. handler: ^(AHKActionSheet *as) {
  2301. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2302. else [self settingFavorite:self.metadata favorite:YES];
  2303. }];
  2304. if (!lockDirectory && !isFolderEncrypted) {
  2305. [actionSheet addButtonWithTitle:NSLocalizedString(@"_details_", nil)
  2306. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"details"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2307. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2308. height:50.0
  2309. type:AHKActionSheetButtonTypeDefault
  2310. handler:^(AHKActionSheet *as) {
  2311. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:self.metadata indexPage:0];
  2312. }];
  2313. }
  2314. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2315. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2316. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2317. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2318. height:50.0
  2319. type:AHKActionSheetButtonTypeDefault
  2320. handler:^(AHKActionSheet *as) {
  2321. __weak __typeof(UIAlertController) *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2322. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2323. textField.text = self.metadata.fileNameView;
  2324. textField.delegate = self;
  2325. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2326. }];
  2327. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2328. NSLog(@"[LOG] Cancel action");
  2329. }];
  2330. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2331. UITextField *fileName = alertController.textFields.firstObject;
  2332. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2333. }];
  2334. okAction.enabled = NO;
  2335. [alertController addAction:cancelAction];
  2336. [alertController addAction:okAction];
  2337. [self presentViewController:alertController animated:YES completion:nil];
  2338. }];
  2339. }
  2340. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2341. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2342. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2343. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2344. height:50.0
  2345. type:AHKActionSheetButtonTypeDefault
  2346. handler:^(AHKActionSheet *as) {
  2347. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2348. }];
  2349. }
  2350. if (!isFolderEncrypted) {
  2351. NSString *title;
  2352. if (isOffline) {
  2353. title = NSLocalizedString(@"_remove_available_offline_", nil);
  2354. } else {
  2355. title = NSLocalizedString(@"_set_available_offline_", nil);
  2356. }
  2357. [actionSheet addButtonWithTitle:title
  2358. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2359. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2360. height:50.0
  2361. type:AHKActionSheetButtonTypeDefault
  2362. handler:^(AHKActionSheet *as) {
  2363. if (isOffline) {
  2364. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:false account:appDelegate.activeAccount];
  2365. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2366. } else {
  2367. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true account:appDelegate.activeAccount];
  2368. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  2369. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2370. }
  2371. }];
  2372. }
  2373. [actionSheet addButtonWithTitle:titoloLock
  2374. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2375. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2376. height:50.0
  2377. type:AHKActionSheetButtonTypeDefault
  2378. handler:^(AHKActionSheet *as) {
  2379. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2380. }];
  2381. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2382. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2383. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2384. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2385. height:50.0
  2386. type:AHKActionSheetButtonTypeDefault
  2387. handler:^(AHKActionSheet *as) {
  2388. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2389. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] ocId:self.metadata.ocId user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2390. dispatch_async(dispatch_get_main_queue(), ^{
  2391. if (error) {
  2392. [[NCContentPresenter shared] messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  2393. } else {
  2394. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2395. [self readFolder:self.serverUrl];
  2396. }
  2397. });
  2398. });
  2399. }];
  2400. }
  2401. if (self.metadata.e2eEncrypted && !_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2402. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2403. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2404. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2405. height:50.0
  2406. type:AHKActionSheetButtonTypeDefault
  2407. handler:^(AHKActionSheet *as) {
  2408. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2409. NSError *error = [[NCNetworkingEndToEnd sharedManager] deletemarkEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] ocId:self.metadata.ocId user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2410. dispatch_async(dispatch_get_main_queue(), ^{
  2411. if (error) {
  2412. [[NCContentPresenter shared] messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  2413. } else {
  2414. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2415. [self readFolder:self.serverUrl];
  2416. }
  2417. });
  2418. });
  2419. }];
  2420. }
  2421. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2422. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor redColor]]
  2423. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2424. height:50.0
  2425. type:AHKActionSheetButtonTypeDestructive
  2426. handler:^(AHKActionSheet *as) {
  2427. [self actionDelete:indexPath];
  2428. }];
  2429. [actionSheet show];
  2430. }
  2431. // ******************************************* FILE *******************************************
  2432. if (!self.metadata.directory) {
  2433. UIImage *iconHeader;
  2434. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2435. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:self.metadata.ocId fileNameView:self.metadata.fileNameView]])
  2436. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconOcId:self.metadata.ocId fileNameView:self.metadata.fileNameView]];
  2437. else
  2438. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2439. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2440. image: iconHeader
  2441. backgroundColor: NCBrandColor.sharedInstance.backgroundForm
  2442. height: 50.0
  2443. type: AHKActionSheetButtonTypeDisabled
  2444. handler: nil
  2445. ];
  2446. [actionSheet addButtonWithTitle: titleFavorite
  2447. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:NCBrandColor.sharedInstance.yellowFavorite]
  2448. backgroundColor: NCBrandColor.sharedInstance.backgroundForm
  2449. height: 50.0
  2450. type: AHKActionSheetButtonTypeDefault
  2451. handler: ^(AHKActionSheet *as) {
  2452. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2453. else [self settingFavorite:self.metadata favorite:YES];
  2454. }];
  2455. if (!_metadataFolder.e2eEncrypted) {
  2456. [actionSheet addButtonWithTitle:NSLocalizedString(@"_details_", nil)
  2457. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"details"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2458. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2459. height: 50.0
  2460. type:AHKActionSheetButtonTypeDefault
  2461. handler:^(AHKActionSheet *as) {
  2462. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:self.metadata indexPage:0];
  2463. }];
  2464. }
  2465. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  2466. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2467. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2468. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2469. height: 50.0
  2470. type:AHKActionSheetButtonTypeDefault
  2471. handler:^(AHKActionSheet *as) {
  2472. [self performSelector:@selector(openinFile:) withObject:nil];
  2473. }];
  2474. }
  2475. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2476. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2477. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2478. height: 50.0
  2479. type:AHKActionSheetButtonTypeDefault
  2480. handler:^(AHKActionSheet *as) {
  2481. __weak __typeof(UIAlertController) *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2482. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2483. textField.text = self.metadata.fileNameView;
  2484. textField.delegate = self;
  2485. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2486. }];
  2487. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2488. NSLog(@"[LOG] Cancel action");
  2489. }];
  2490. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2491. UITextField *fileName = alertController.textFields.firstObject;
  2492. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2493. }];
  2494. okAction.enabled = NO;
  2495. [alertController addAction:cancelAction];
  2496. [alertController addAction:okAction];
  2497. [self presentViewController:alertController animated:YES completion:nil];
  2498. }];
  2499. if (!_metadataFolder.e2eEncrypted) {
  2500. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2501. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2502. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2503. height:50.0
  2504. type:AHKActionSheetButtonTypeDefault
  2505. handler:^(AHKActionSheet *as) {
  2506. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2507. }];
  2508. }
  2509. if ([NCUtility.sharedInstance isEditImage:self.metadata.fileNameView] != nil && !_metadataFolder.e2eEncrypted && self.metadata.status == k_metadataStatusNormal) {
  2510. [actionSheet addButtonWithTitle:NSLocalizedString(@"_modify_photo_", nil)
  2511. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"modifyPhoto"] width:50 height:50 color:NCBrandColor.sharedInstance.icon]
  2512. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2513. height:50.0
  2514. type:AHKActionSheetButtonTypeDefault
  2515. handler:^(AHKActionSheet *as) {
  2516. self.metadata.session = k_download_session;
  2517. self.metadata.sessionError = @"";
  2518. self.metadata.sessionSelector = selectorDownloadEditPhoto;
  2519. self.metadata.status = k_metadataStatusWaitDownload;
  2520. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2521. [appDelegate startLoadAutoDownloadUpload];
  2522. }];
  2523. }
  2524. if (!_metadataFolder.e2eEncrypted) {
  2525. NSString *title;
  2526. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", self.metadata.ocId]];
  2527. if (localFile == nil || localFile.offline == false) { title = NSLocalizedString(@"_set_available_offline_", nil); }
  2528. else { title = NSLocalizedString(@"_remove_available_offline_", nil); }
  2529. [actionSheet addButtonWithTitle:title
  2530. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:NCBrandColor.sharedInstance.icon]
  2531. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2532. height:50.0
  2533. type:AHKActionSheetButtonTypeDefault
  2534. handler:^(AHKActionSheet *as) {
  2535. if (localFile == nil || ![CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2536. self.metadata.session = k_download_session;
  2537. self.metadata.sessionError = @"";
  2538. self.metadata.sessionSelector = selectorLoadOffline;
  2539. self.metadata.status = k_metadataStatusWaitDownload;
  2540. // Add Metadata for Download
  2541. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2542. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2543. [appDelegate startLoadAutoDownloadUpload];
  2544. } else if (localFile.offline == false) {
  2545. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:self.metadata.ocId offline:true];
  2546. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2547. } else {
  2548. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:self.metadata.ocId offline:false];
  2549. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2550. }
  2551. }];
  2552. }
  2553. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2554. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor redColor]]
  2555. backgroundColor:NCBrandColor.sharedInstance.backgroundForm
  2556. height:50.0
  2557. type:AHKActionSheetButtonTypeDestructive
  2558. handler:^(AHKActionSheet *as) {
  2559. [self actionDelete:indexPath];
  2560. }];
  2561. [actionSheet show];
  2562. }
  2563. }
  2564. #pragma --------------------------------------------------------------------------------------------
  2565. #pragma mark - ==== Datasource ====
  2566. #pragma --------------------------------------------------------------------------------------------
  2567. - (void)clearDateReadDataSource:(NSNotification *)notification
  2568. {
  2569. _dateReadDataSource = Nil;
  2570. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  2571. }
  2572. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  2573. {
  2574. // test
  2575. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2576. return;
  2577. // Search Mode
  2578. if (self.searchController.isActive) {
  2579. // Create metadatas
  2580. NSMutableArray *metadatas = [NSMutableArray new];
  2581. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2582. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  2583. if (metadata) {
  2584. [metadatas addObject:metadata];
  2585. }
  2586. }
  2587. // [CCUtility getGroupBySettings]
  2588. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterocId:appDelegate.filterocId filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  2589. [self tableViewReloadData];
  2590. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2591. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2592. _noFilesSearchDescription = @"";
  2593. }
  2594. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2595. _noFilesSearchTitle = @"";
  2596. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2597. }
  2598. [self.tableView reloadEmptyDataSet];
  2599. return;
  2600. }
  2601. // Se non siamo nella dir appropriata esci
  2602. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2603. return;
  2604. }
  2605. // Controllo data lettura Data Source
  2606. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2607. if (tableDirectory == nil) {
  2608. return;
  2609. }
  2610. // Get MetadataFolder
  2611. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2612. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  2613. else
  2614. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  2615. // Remove optimization for encrypted directory
  2616. if (_metadataFolder.e2eEncrypted)
  2617. _dateReadDataSource = nil;
  2618. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2619. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2620. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2621. _dateReadDataSource = [NSDate date];
  2622. // Data Source
  2623. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2624. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2625. dispatch_async(dispatch_get_main_queue(), ^{
  2626. sectionDataSource = sectionDataSourceTemp;
  2627. [self tableViewReloadData];
  2628. });
  2629. });
  2630. } else {
  2631. [self tableViewReloadData];
  2632. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2633. }
  2634. // BLINK
  2635. if (self.blinkFileNamePath != nil) {
  2636. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2637. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  2638. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  2639. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  2640. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  2641. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  2642. if ([key isEqualToString:metadata.ocId]) {
  2643. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  2644. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  2645. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2646. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  2647. if (cell) {
  2648. self.blinkFileNamePath = nil;
  2649. [[NCUtility sharedInstance] blinkWithCell:cell];
  2650. }
  2651. });
  2652. }
  2653. }
  2654. }
  2655. }
  2656. });
  2657. }
  2658. }
  2659. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2660. {
  2661. // test
  2662. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2663. return nil;
  2664. }
  2665. // get auto upload folder
  2666. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2667. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2668. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2669. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND status != %i", appDelegate.activeAccount, serverUrl, k_metadataStatusHide] sorted:nil ascending:NO];
  2670. // [CCUtility getGroupBySettings]
  2671. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterocId:appDelegate.filterocId filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  2672. if (withReloadData) {
  2673. sectionDataSource = sectionDataSourceTemp;
  2674. [self tableViewReloadData];
  2675. }
  2676. return sectionDataSourceTemp;
  2677. }
  2678. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2679. {
  2680. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2681. if (selectedRows.count > 0) {
  2682. for (NSIndexPath *selectionIndex in selectedRows) {
  2683. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2684. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2685. [metadatas addObject:metadata];
  2686. }
  2687. }
  2688. return metadatas;
  2689. }
  2690. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2691. {
  2692. NSInteger totSections =[sectionDataSource.sections count] ;
  2693. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2694. return nil;
  2695. }
  2696. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2697. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2698. }
  2699. #pragma --------------------------------------------------------------------------------------------
  2700. #pragma mark - ==== Table ====
  2701. #pragma --------------------------------------------------------------------------------------------
  2702. - (void)tableViewSelect:(BOOL)edit
  2703. {
  2704. // chiudiamo eventuali swipe aperti
  2705. if (edit)
  2706. [self.tableView setEditing:NO animated:NO];
  2707. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2708. [self.tableView setEditing:edit animated:YES];
  2709. _isSelectedMode = edit;
  2710. if (edit)
  2711. [self setUINavigationBarSelected];
  2712. else
  2713. [self setUINavigationBarDefault];
  2714. [_selectedocIdsMetadatas removeAllObjects];
  2715. [self setTitle];
  2716. }
  2717. - (void)tableViewReloadData
  2718. {
  2719. // store selected cells before relod
  2720. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2721. // reload table view
  2722. [self.tableView reloadData];
  2723. // selected cells stored
  2724. for (NSIndexPath *path in indexPaths)
  2725. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2726. [self setTableViewHeader];
  2727. [self setTableViewFooter];
  2728. if (self.tableView.editing)
  2729. [self setTitle];
  2730. [self.tableView reloadEmptyDataSet];
  2731. }
  2732. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2733. {
  2734. if (tableView.editing == 1) {
  2735. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2736. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2737. return NO;
  2738. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2739. return NO;
  2740. else
  2741. return YES;
  2742. } else {
  2743. [_selectedocIdsMetadatas removeAllObjects];
  2744. }
  2745. return YES;
  2746. }
  2747. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2748. {
  2749. return 60;
  2750. }
  2751. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2752. {
  2753. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2754. }
  2755. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2756. {
  2757. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2758. }
  2759. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2760. {
  2761. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2762. NSString *sectionTitle = [sections objectAtIndex:section];
  2763. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2764. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2765. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2766. return 20.f;
  2767. }
  2768. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2769. {
  2770. float shift;
  2771. UIVisualEffectView *visualEffectView;
  2772. NSString *titleSection;
  2773. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2774. return nil;
  2775. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2776. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2777. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2778. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2779. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2780. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2781. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2782. else titleSection = NSLocalizedString(titleSection,nil);
  2783. // Format title
  2784. UIVisualEffect *blurEffect;
  2785. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2786. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2787. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  2788. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2789. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2790. shift = - 35;
  2791. else
  2792. shift = - 20;
  2793. } else shift = - 10;
  2794. // Title
  2795. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2796. titleLabel.backgroundColor = [UIColor clearColor];
  2797. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  2798. titleLabel.font = [UIFont systemFontOfSize:12];
  2799. titleLabel.textAlignment = NSTextAlignmentLeft;
  2800. titleLabel.text = titleSection;
  2801. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2802. [visualEffectView.contentView addSubview:titleLabel];
  2803. // Elements
  2804. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2805. elementLabel.backgroundColor = [UIColor clearColor];
  2806. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  2807. elementLabel.font = [UIFont systemFontOfSize:12];
  2808. elementLabel.textAlignment = NSTextAlignmentRight;
  2809. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2810. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2811. NSUInteger rowsCount = [metadatas count];
  2812. if (rowsCount == 0) return nil;
  2813. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2814. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2815. [visualEffectView.contentView addSubview:elementLabel];
  2816. return visualEffectView;
  2817. }
  2818. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2819. {
  2820. return [sectionDataSource.sections indexOfObject:title];
  2821. }
  2822. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2823. {
  2824. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2825. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2826. else
  2827. return nil;
  2828. }
  2829. /*
  2830. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2831. {
  2832. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2833. }
  2834. }
  2835. */
  2836. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2837. {
  2838. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2839. tableShare *shareCell;
  2840. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  2841. return [CCCellMain new];
  2842. }
  2843. for (tableShare *share in appDelegate.shares) {
  2844. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  2845. shareCell = share;
  2846. break;
  2847. }
  2848. }
  2849. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  2850. // NORMAL - > MAIN
  2851. if ([cell isKindOfClass:[CCCellMain class]]) {
  2852. // Comment tap
  2853. if (metadata.commentsUnread) {
  2854. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  2855. [tapComment setNumberOfTapsRequired:1];
  2856. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  2857. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  2858. }
  2859. // Share add Tap
  2860. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2861. [tapShare setNumberOfTapsRequired:1];
  2862. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  2863. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  2864. // More
  2865. if ([self canOpenMenuAction:metadata]) {
  2866. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2867. [tapMore setNumberOfTapsRequired:1];
  2868. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2869. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2870. }
  2871. // MGSwipeButton
  2872. ((CCCellMain *)cell).delegate = self;
  2873. // LEFT
  2874. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  2875. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2876. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2877. //centerIconOverText
  2878. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2879. [favoriteButton centerIconOverText];
  2880. // RIGHT
  2881. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  2882. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2883. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2884. //centerIconOverText
  2885. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2886. [deleteButton centerIconOverText];
  2887. }
  2888. // TRANSFER
  2889. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2890. // gesture Transfer
  2891. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  2892. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  2893. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  2894. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  2895. }
  2896. return cell;
  2897. }
  2898. - (void)setTableViewHeader
  2899. {
  2900. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  2901. if (capabilities.versionMajor < k_nextcloud_version_18_0 || self.richWorkspaceText.length == 0 || self.searchController.isActive) {
  2902. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  2903. } else {
  2904. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  2905. }
  2906. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  2907. self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.tableView.frame.size.width, heightSearchBar);
  2908. [self.tableView reloadData];
  2909. }
  2910. - (void)setTableViewFooter
  2911. {
  2912. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2913. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2914. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2915. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2916. UIFont *appFont = [UIFont systemFontOfSize:12];
  2917. footerLabel.font = appFont;
  2918. footerLabel.textColor = [UIColor grayColor];
  2919. footerLabel.backgroundColor = [UIColor clearColor];
  2920. footerLabel.textAlignment = NSTextAlignmentCenter;
  2921. NSString *folders;
  2922. NSString *files;
  2923. NSString *footerText;
  2924. if (sectionDataSource.directories > 1) {
  2925. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2926. } else if (sectionDataSource.directories == 1){
  2927. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2928. } else {
  2929. folders = @"";
  2930. }
  2931. if (sectionDataSource.files > 1) {
  2932. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2933. } else if (sectionDataSource.files == 1){
  2934. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2935. } else {
  2936. files = @"";
  2937. }
  2938. if ([folders isEqualToString:@""]) {
  2939. footerText = files;
  2940. } else if ([files isEqualToString:@""]) {
  2941. footerText = folders;
  2942. } else {
  2943. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2944. }
  2945. footerLabel.text = footerText;
  2946. [footerView addSubview:footerLabel];
  2947. [self.tableView setTableFooterView:footerView];
  2948. }
  2949. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2950. {
  2951. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2952. // settiamo il record file.
  2953. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2954. if (!self.metadata)
  2955. return;
  2956. // se non può essere selezionata deseleziona
  2957. if ([cell isEditing] == NO)
  2958. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2959. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2960. if (self.tableView.editing) {
  2961. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2962. [self setTitle];
  2963. return;
  2964. }
  2965. // se è in corso una sessione
  2966. if (self.metadata.status != k_metadataStatusNormal)
  2967. return;
  2968. // file
  2969. if (self.metadata.directory == NO) {
  2970. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2971. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2972. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName ocId:self.metadata.ocId serverUrl:self.metadata.serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  2973. } else {
  2974. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2975. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2976. } else {
  2977. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) && _metadataFolder.e2eEncrypted == NO) {
  2978. [self shouldPerformSegue:self.metadata selector:@""];
  2979. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2980. if (appDelegate.reachability.isReachable) {
  2981. [self shouldPerformSegue:self.metadata selector:@""];
  2982. } else {
  2983. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2984. }
  2985. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2986. if (appDelegate.reachability.isReachable) {
  2987. [self shouldPerformSegue:self.metadata selector:@""];
  2988. } else {
  2989. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2990. }
  2991. } else {
  2992. self.metadata.session = k_download_session;
  2993. self.metadata.sessionError = @"";
  2994. self.metadata.sessionSelector = selectorLoadFileView;
  2995. self.metadata.status = k_metadataStatusWaitDownload;
  2996. // Add Metadata for Download
  2997. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2998. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2999. [appDelegate startLoadAutoDownloadUpload];
  3000. }
  3001. }
  3002. }
  3003. }
  3004. if (self.metadata.directory) {
  3005. [self performSegueDirectoryWithControlPasscode:true metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  3006. }
  3007. }
  3008. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3009. {
  3010. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3011. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  3012. [self setTitle];
  3013. }
  3014. - (void)didSelectAll
  3015. {
  3016. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3017. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3018. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3019. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3020. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  3021. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3022. }
  3023. }
  3024. [self setTitle];
  3025. }
  3026. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3027. {
  3028. if (!indexPath)
  3029. return NO;
  3030. NSInteger section = indexPath.section;
  3031. NSInteger row = indexPath.row;
  3032. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3033. if (section > lastSectionIndex || lastSectionIndex < 0)
  3034. return NO;
  3035. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3036. if (rowCount < 0)
  3037. return NO;
  3038. return row <= rowCount;
  3039. }
  3040. #pragma --------------------------------------------------------------------------------------------
  3041. #pragma mark ===== Navigation ====
  3042. #pragma --------------------------------------------------------------------------------------------
  3043. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  3044. {
  3045. // if background return
  3046. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3047. if (self.view.window == NO)
  3048. return;
  3049. // Collapsed ma siamo già in detail esci
  3050. if (self.splitViewController.isCollapsed)
  3051. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3052. // Metadata for push detail
  3053. self.metadataForPushDetail = metadata;
  3054. self.selectorForPushDetail = selector;
  3055. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3056. }
  3057. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3058. {
  3059. id viewController = segue.destinationViewController;
  3060. tableMetadata *metadata;
  3061. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3062. UINavigationController *nav = viewController;
  3063. _detailViewController = (CCDetail *)nav.topViewController;
  3064. } else {
  3065. _detailViewController = segue.destinationViewController;
  3066. }
  3067. NSMutableArray *photoDataSource = [NSMutableArray new];
  3068. if ([sender isKindOfClass:[tableMetadata class]]) {
  3069. metadata = sender;
  3070. [photoDataSource addObject:sender];
  3071. } else {
  3072. metadata = self.metadataForPushDetail;
  3073. for (NSString *ocId in sectionDataSource.allOcId) {
  3074. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  3075. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3076. [photoDataSource addObject:metadata];
  3077. }
  3078. }
  3079. _detailViewController.metadataDetail = metadata;
  3080. _detailViewController.selectorDetail = self.selectorForPushDetail;
  3081. _detailViewController.photoDataSource = photoDataSource;
  3082. _detailViewController.dateFilterQuery = nil;
  3083. [_detailViewController setTitle:metadata.fileNameView];
  3084. }
  3085. // can i go to next viewcontroller
  3086. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode metadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  3087. {
  3088. NSString *nomeDir;
  3089. if (self.tableView.editing == NO) {
  3090. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  3091. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadata.account, lockServerUrl]];
  3092. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3093. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3094. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3095. viewController.delegate = self;
  3096. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3097. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3098. viewController.inputViewTitlePassword = YES;
  3099. if ([CCUtility getSimplyBlockCode]) {
  3100. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3101. viewController.passcodeInputView.maximumLength = 6;
  3102. } else {
  3103. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3104. viewController.passcodeInputView.maximumLength = 64;
  3105. }
  3106. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3107. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3108. viewController.touchIDManager = touchIDManager;
  3109. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3110. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3111. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3112. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3113. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  3114. [self presentViewController:navigationController animated:YES completion:nil];
  3115. return;
  3116. }
  3117. // E2EE Check enable
  3118. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3119. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  3120. return;
  3121. }
  3122. nomeDir = metadata.fileName;
  3123. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  3124. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3125. if (!viewController) {
  3126. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3127. viewController.serverUrl = serverUrlPush;
  3128. viewController.titleMain = metadata.fileName;
  3129. viewController.blinkFileNamePath = blinkFileNamePath;
  3130. // save self
  3131. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3132. [self.navigationController pushViewController:viewController animated:YES];
  3133. } else {
  3134. if (viewController.isViewLoaded) {
  3135. viewController.titleMain = metadata.fileName;
  3136. viewController.blinkFileNamePath = blinkFileNamePath;
  3137. // Fix : Application tried to present modally an active controller
  3138. if ([self.navigationController isBeingPresented]) {
  3139. // being presented
  3140. } else if ([self.navigationController isMovingToParentViewController]) {
  3141. // being pushed
  3142. } else {
  3143. [self.navigationController pushViewController:viewController animated:YES];
  3144. }
  3145. }
  3146. }
  3147. }
  3148. }
  3149. @end