CCMain.m 209 KB

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