CCMain.m 209 KB

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