CCMain.m 206 KB

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