CCMain.m 207 KB

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