CCMain.m 210 KB

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