CCMain.m 205 KB

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