CCMain.m 204 KB

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