CCMain.m 207 KB

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