CCMain.m 205 KB

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