CCMain.m 211 KB

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