CCMain.m 206 KB

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