CCMain.m 208 KB

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