CCMain.m 213 KB

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