CCMain.m 206 KB

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