CCMain.m 209 KB

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