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