CCMain.m 213 KB

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