CCMain.m 211 KB

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