CCMain.m 208 KB

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