CCMain.m 208 KB

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