CCMain.m 207 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379
  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 moveFileOrFolder:fileNamePath fileNameTo:fileNameToPath account:appDelegate.activeAccount success:^(NSString *account) {
  1150. // Rename metadata
  1151. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:fileNameNew fileID:metadata.fileID];
  1152. if (metadata.directory) {
  1153. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  1154. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:fileNameNew];
  1155. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadata.serverUrl]];
  1156. if (directoryTable == nil) {
  1157. [appDelegate messageNotification:@"_rename_" description:@"Internal error, ServerUrl not found" visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1158. return;
  1159. }
  1160. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:nil fileID:nil encrypted:directoryTable.e2eEncrypted account:appDelegate.activeAccount];
  1161. } else {
  1162. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:fileNameNew etag:nil];
  1163. // Move file system
  1164. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileName];
  1165. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileNameNew];
  1166. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1167. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileName];
  1168. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileNameNew];
  1169. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1170. }
  1171. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1172. } failure:^(NSString *account, NSString *message, NSInteger errorCode) {
  1173. [appDelegate messageNotification:@"_rename_" description:message visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1174. }];
  1175. }
  1176. }];
  1177. }
  1178. }
  1179. #pragma --------------------------------------------------------------------------------------------
  1180. #pragma mark ===== Move =====
  1181. #pragma --------------------------------------------------------------------------------------------
  1182. - (void)moveFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1183. {
  1184. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:nil withUserID:nil withPassword:nil withUrl:nil];
  1185. [ocNetworking readFileWithAccount:appDelegate.activeAccount serverUrl:serverUrlTo fileName:metadata.fileName completion:^(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode) {
  1186. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1187. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1188. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1189. }];
  1190. [alert addAction:ok];
  1191. [self presentViewController:alert animated:YES completion:nil];
  1192. // End Select Table View
  1193. [self tableViewSelect:NO];
  1194. // reload Datasource
  1195. [self readFileReloadFolder];
  1196. } else if (errorCode != 0) {
  1197. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1198. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName];
  1199. [ocNetworking moveFileOrFolder:fileNamePath fileNameTo:fileNameToPath account:appDelegate.activeAccount success:^(NSString *account) {
  1200. [_hud hideHud];
  1201. if (metadata.directory) {
  1202. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] account:account];
  1203. }
  1204. [[NCManageDatabase sharedInstance] moveMetadataWithFileID:metadata.fileID serverUrlTo:serverUrlTo];
  1205. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:metadata.serverUrl account:account];
  1206. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrlTo account:account];
  1207. // next
  1208. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  1209. if ([_selectedFileIDsMetadatas count] > 0) {
  1210. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1211. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrlTo numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1212. } else {
  1213. // End Select Table View
  1214. [self tableViewSelect:NO];
  1215. // reload Datasource
  1216. if (_isSearchMode)
  1217. [self readFolder:metadata.serverUrl];
  1218. else
  1219. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1220. }
  1221. } failure:^(NSString *account, NSString *message, NSInteger errorCode) {
  1222. [_hud hideHud];
  1223. if (message && errorCode != kOCErrorServerUnauthorized)
  1224. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1225. // End Select Table View
  1226. [self tableViewSelect:NO];
  1227. // reload Datasource
  1228. if (_isSearchMode)
  1229. [self readFolder:metadata.serverUrl];
  1230. else
  1231. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl fileID:nil action:k_action_NULL];
  1232. }];
  1233. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1234. }
  1235. }];
  1236. }
  1237. // DELEGATE : Select
  1238. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1239. {
  1240. if (serverUrl == nil) {
  1241. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1242. } else {
  1243. // E2EE DENIED
  1244. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1245. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1246. return;
  1247. }
  1248. if ([_selectedFileIDsMetadatas count] > 0) {
  1249. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1250. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1251. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1252. } else {
  1253. _numSelectedFileIDsMetadatas = 1;
  1254. [self moveFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1255. }
  1256. }
  1257. }
  1258. - (void)moveOpenWindow:(NSArray *)indexPaths
  1259. {
  1260. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1261. return;
  1262. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1263. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1264. viewController.delegate = self;
  1265. viewController.hideButtonCreateFolder = false;
  1266. viewController.selectFile = false;
  1267. viewController.includeDirectoryE2EEncryption = false;
  1268. viewController.includeImages = false;
  1269. viewController.type = @"";
  1270. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1271. viewController.layoutViewSelect = k_layout_view_move;
  1272. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1273. [self presentViewController:navigationController animated:YES completion:nil];
  1274. }
  1275. #pragma --------------------------------------------------------------------------------------------
  1276. #pragma mark ===== Create folder =====
  1277. #pragma --------------------------------------------------------------------------------------------
  1278. - (void)createFolder
  1279. {
  1280. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1281. NSString *message;
  1282. UIAlertController *alertController;
  1283. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1284. message = @"/";
  1285. } else {
  1286. message = [serverUrl lastPathComponent];
  1287. }
  1288. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1289. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1290. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1291. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  1292. }];
  1293. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1294. NSLog(@"[LOG] Cancel action");
  1295. }];
  1296. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1297. UITextField *fileName = alertController.textFields.firstObject;
  1298. [self createFolder:fileName.text serverUrl:serverUrl];
  1299. }];
  1300. okAction.enabled = NO;
  1301. [alertController addAction:cancelAction];
  1302. [alertController addAction:okAction];
  1303. [self presentViewController:alertController animated:YES completion:nil];
  1304. }
  1305. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1306. {
  1307. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1308. if (![fileNameFolder length]) return;
  1309. NSString *fileIDTemp = [[NSUUID UUID] UUIDString];
  1310. // Create Directory (temp) on metadata
  1311. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:fileIDTemp serverUrl:serverUrl fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal url:@""];
  1312. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1313. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  1314. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1315. // Creeate folder Networking
  1316. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:nil withUserID:nil withPassword:nil withUrl:nil];
  1317. [ocNetworking createFolder:fileNameFolder serverUrl:serverUrl account:appDelegate.activeAccount success:^(NSString *account, NSString *fileID, NSDate *date) {
  1318. if ([account isEqualToString:appDelegate.activeAccount]) {
  1319. // Delete Temp Dir
  1320. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp]];
  1321. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1322. if (_metadataFolder.e2eEncrypted) {
  1323. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1324. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory fileID:fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1325. dispatch_async(dispatch_get_main_queue(), ^{
  1326. if (error) {
  1327. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1328. }
  1329. [self readFolder:self.serverUrl];
  1330. });
  1331. });
  1332. } else {
  1333. [self readFolder:self.serverUrl];
  1334. }
  1335. }
  1336. } failure:^(NSString *account, NSString *message, NSInteger errorCode) {
  1337. // Unauthorized
  1338. if (errorCode == kOCErrorServerUnauthorized)
  1339. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1340. else
  1341. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1342. // Delete Temp Dir
  1343. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp]];
  1344. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1345. // We are in directory fail ?
  1346. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:fileNameFolder]];
  1347. if (vc)
  1348. [vc.navigationController popViewControllerAnimated:YES];
  1349. }];
  1350. }
  1351. #pragma --------------------------------------------------------------------------------------------
  1352. #pragma mark ===== Progress & Task Button =====
  1353. #pragma --------------------------------------------------------------------------------------------
  1354. - (void)triggerProgressTask:(NSNotification *)notification
  1355. {
  1356. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceFileIDIndexPath:sectionDataSource.fileIDIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1357. }
  1358. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1359. {
  1360. UITouch *touch = [[event allTouches] anyObject];
  1361. CGPoint location = [touch locationInView:self.tableView];
  1362. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1363. if ([self indexPathIsValid:indexPath]) {
  1364. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1365. if (metadataSection) {
  1366. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1367. if (metadata)
  1368. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true];
  1369. }
  1370. }
  1371. }
  1372. - (void)cancelAllTask:(id)sender
  1373. {
  1374. CGPoint location = [sender locationInView:self.tableView];
  1375. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1376. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1377. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1378. [[NCMainCommon sharedInstance] cancelAllTransferWithView:self.view];
  1379. }]];
  1380. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1381. alertController.popoverPresentationController.sourceView = self.tableView;
  1382. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1383. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1384. [alertController.view layoutIfNeeded];
  1385. [self presentViewController:alertController animated:YES completion:nil];
  1386. }
  1387. #pragma --------------------------------------------------------------------------------------------
  1388. #pragma mark ===== Shared =====
  1389. #pragma --------------------------------------------------------------------------------------------
  1390. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1391. {
  1392. [_hud hideHud];
  1393. // Check Active Account
  1394. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1395. return;
  1396. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl account:metadataNet.account];
  1397. if (result) {
  1398. appDelegate.sharesLink = result[0];
  1399. appDelegate.sharesUserAndGroup = result[1];
  1400. }
  1401. // Notify Shares View
  1402. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1403. if (openWindow) {
  1404. if (_shareOC) {
  1405. [_shareOC reloadData];
  1406. } else {
  1407. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1408. // Apriamo la view
  1409. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1410. _shareOC.delegate = self;
  1411. _shareOC.metadata = metadata;
  1412. _shareOC.serverUrl = metadataNet.serverUrl;
  1413. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1414. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1415. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1416. [self presentViewController:_shareOC animated:YES completion:nil];
  1417. }
  1418. }
  1419. [self tableViewReloadData];
  1420. }
  1421. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1422. {
  1423. [_hud hideHud];
  1424. // Check Active Account
  1425. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1426. return;
  1427. // Unauthorized
  1428. if (errorCode == kOCErrorServerUnauthorized)
  1429. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1430. else
  1431. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1432. if (_shareOC)
  1433. [_shareOC reloadData];
  1434. [self tableViewReloadData];
  1435. }
  1436. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload
  1437. {
  1438. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1439. metadataNet.action = actionShare;
  1440. metadataNet.fileID = metadata.fileID;
  1441. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1442. metadataNet.fileNameView = metadata.fileNameView;
  1443. metadataNet.hideDownload = hideDownload;
  1444. metadataNet.sharePermission = permission;
  1445. metadataNet.password = password;
  1446. metadataNet.selector = selectorShare;
  1447. metadataNet.serverUrl = serverUrl;
  1448. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1449. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1450. }
  1451. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1452. {
  1453. [_hud hideHud];
  1454. // Check Active Account
  1455. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1456. return;
  1457. // rimuoviamo la condivisione da db
  1458. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup account:metadataNet.account];
  1459. if (result) {
  1460. appDelegate.sharesLink = result[0];
  1461. appDelegate.sharesUserAndGroup = result[1];
  1462. }
  1463. if (_shareOC)
  1464. [_shareOC reloadData];
  1465. [self tableViewReloadData];
  1466. }
  1467. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1468. {
  1469. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1470. metadataNet.action = actionUnShare;
  1471. metadataNet.fileID = metadata.fileID;
  1472. metadataNet.fileName = metadata.fileName;
  1473. metadataNet.fileNameView = metadata.fileNameView;
  1474. metadataNet.selector = selectorUnshare;
  1475. metadataNet.serverUrl = serverUrl;
  1476. metadataNet.share = share;
  1477. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1478. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1479. }
  1480. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission hideDownload:(BOOL)hideDownload
  1481. {
  1482. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1483. metadataNet.action = actionUpdateShare;
  1484. metadataNet.fileID = metadata.fileID;
  1485. metadataNet.expirationTime = expirationTime;
  1486. metadataNet.hideDownload = hideDownload;
  1487. metadataNet.password = password;
  1488. metadataNet.selector = selectorUpdateShare;
  1489. metadataNet.serverUrl = serverUrl;
  1490. metadataNet.share = share;
  1491. metadataNet.sharePermission = permission;
  1492. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1493. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1494. }
  1495. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1496. {
  1497. [_hud hideHud];
  1498. // Check Active Account
  1499. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1500. return;
  1501. if (_shareOC)
  1502. [_shareOC reloadUserAndGroup:items];
  1503. }
  1504. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1505. {
  1506. [_hud hideHud];
  1507. // Check Active Account
  1508. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1509. return;
  1510. // Unauthorized
  1511. if (errorCode == kOCErrorServerUnauthorized)
  1512. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1513. else
  1514. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1515. }
  1516. - (void)getUserAndGroup:(NSString *)find
  1517. {
  1518. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1519. metadataNet.action = actionGetUserAndGroup;
  1520. metadataNet.optionAny = find;
  1521. metadataNet.selector = selectorGetUserAndGroup;
  1522. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1523. [_hud visibleIndeterminateHud];
  1524. }
  1525. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1526. {
  1527. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1528. metadataNet.action = actionShareWith;
  1529. metadataNet.fileID = metadata.fileID;
  1530. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1531. metadataNet.fileNameView = metadata.fileNameView;
  1532. metadataNet.serverUrl = serverUrl;
  1533. metadataNet.selector = selectorShare;
  1534. metadataNet.share = user;
  1535. metadataNet.shareeType = shareeType;
  1536. metadataNet.sharePermission = permission;
  1537. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1538. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1539. }
  1540. - (void)openWindowShare:(tableMetadata *)metadata
  1541. {
  1542. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:nil withUserID:nil withPassword:nil withUrl:nil];
  1543. [ocNetworking readShareServer:appDelegate.activeAccount completion:^(NSString *account, NSArray *items, NSString *message, NSInteger errorCode) {
  1544. [_hud hideHud];
  1545. if ([account isEqualToString:appDelegate.activeAccount]) {
  1546. for (OCSharedDto *item in items)
  1547. [appDelegate.sharesID setObject:item forKey:[@(item.idRemoteShared) stringValue]];
  1548. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:appDelegate.sharesID activeUrl:appDelegate.activeUrl account:account];
  1549. if (result) {
  1550. appDelegate.sharesLink = result[0];
  1551. appDelegate.sharesUserAndGroup = result[1];
  1552. }
  1553. // Notify Shares View
  1554. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1555. if (_shareOC) {
  1556. [_shareOC reloadData];
  1557. } else {
  1558. // Apriamo la view
  1559. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1560. _shareOC.delegate = self;
  1561. _shareOC.metadata = metadata;
  1562. _shareOC.serverUrl = metadata.serverUrl;
  1563. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1564. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1565. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1566. [self presentViewController:_shareOC animated:YES completion:nil];
  1567. }
  1568. [self tableViewReloadData];
  1569. }
  1570. }];
  1571. [_hud visibleIndeterminateHud];
  1572. }
  1573. - (void)tapActionShared:(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. [self openWindowShare:metadata];
  1580. }
  1581. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1582. {
  1583. CGPoint location = [tapGesture locationInView:self.tableView];
  1584. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1585. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1586. if (metadata) {
  1587. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1588. vc.metadata = metadata;
  1589. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1590. [self presentViewController:vc animated:YES completion:nil];
  1591. }
  1592. }
  1593. #pragma --------------------------------------------------------------------------------------------
  1594. #pragma mark ===== Favorite =====
  1595. #pragma --------------------------------------------------------------------------------------------
  1596. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1597. {
  1598. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1599. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:nil withUserID:nil withPassword:nil withUrl:nil];
  1600. [ocNetworking settingFavoriteWithAccount:appDelegate.activeAccount fileName:fileNameServerUrl favorite:favorite completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1601. if (errorCode == 0 && [appDelegate.activeAccount isEqualToString:account]) {
  1602. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  1603. _dateReadDataSource = nil;
  1604. if (_isSearchMode)
  1605. [self readFolder:self.serverUrl];
  1606. else
  1607. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1608. if (metadata.directory && favorite) {
  1609. NSString *selector;
  1610. if ([CCUtility getFavoriteOffline])
  1611. selector = selectorReadFolderWithDownload;
  1612. else
  1613. selector = selectorReadFolder;
  1614. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector];
  1615. }
  1616. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1617. metadata.favorite = favorite;
  1618. metadata.session = k_download_session;
  1619. metadata.sessionError = @"";
  1620. metadata.sessionSelector = selectorDownloadSynchronize;
  1621. metadata.status = k_metadataStatusWaitDownload;
  1622. // Add Metadata for Download
  1623. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1624. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1625. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1626. }
  1627. } else if (errorCode == kOCErrorServerUnauthorized) {
  1628. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1629. }
  1630. }];
  1631. }
  1632. #pragma --------------------------------------------------------------------------------------------
  1633. #pragma mark ===== Open in... =====
  1634. #pragma --------------------------------------------------------------------------------------------
  1635. - (void)DownloadOpenIn:(tableMetadata *)metadata
  1636. {
  1637. metadata.session = k_download_session;
  1638. metadata.sessionError = @"";
  1639. metadata.sessionSelector = selectorOpenIn;
  1640. metadata.status = k_metadataStatusWaitDownload;
  1641. // Add Metadata for Download
  1642. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1643. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1644. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1645. }
  1646. - (void)openIn:(tableMetadata *)metadata
  1647. {
  1648. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  1649. docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1650. docController.delegate = self;
  1651. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1652. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1653. if (cell) {
  1654. [docController presentOptionsMenuFromRect:cell.frame inView:self.tableView animated:YES];
  1655. } else {
  1656. [docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1657. }
  1658. }
  1659. #pragma --------------------------------------------------------------------------------------------
  1660. #pragma mark ==== Menu LOGO ====
  1661. #pragma --------------------------------------------------------------------------------------------
  1662. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1663. {
  1664. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1665. return;
  1666. // Brand
  1667. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1668. return;
  1669. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1670. NSMutableArray *menuArray = [NSMutableArray new];
  1671. for (NSString *account in listAccount) {
  1672. CCMenuItem *item = [[CCMenuItem alloc] init];
  1673. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1674. item.argument = account;
  1675. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1676. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-avatar.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url]];
  1677. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1678. if (avatar) {
  1679. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1680. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1681. CGSize imageSize = avatarImageView.bounds.size;
  1682. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1683. CGContextRef context = UIGraphicsGetCurrentContext();
  1684. [avatarImageView.layer renderInContext:context];
  1685. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1686. UIGraphicsEndImageContext();
  1687. } else {
  1688. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1689. }
  1690. item.image = avatar;
  1691. item.target = self;
  1692. if ([account isEqualToString:appDelegate.activeAccount]) {
  1693. item.action = nil;
  1694. [menuArray insertObject:item atIndex:0];
  1695. } else {
  1696. item.action = @selector(changeDefaultAccount:);
  1697. [menuArray addObject:item];
  1698. }
  1699. }
  1700. // Add + new account
  1701. CCMenuItem *item = [[CCMenuItem alloc] init];
  1702. item.title = NSLocalizedString(@"_add_account_", nil);
  1703. item.argument = @"";
  1704. item.image = [UIImage imageNamed:@"add"];
  1705. item.target = self;
  1706. item.action = @selector(addNewAccount:);
  1707. [menuArray addObject:item];
  1708. OptionalConfiguration options;
  1709. Color textColor, backgroundColor;
  1710. textColor.R = 0;
  1711. textColor.G = 0;
  1712. textColor.B = 0;
  1713. backgroundColor.R = 1;
  1714. backgroundColor.G = 1;
  1715. backgroundColor.B = 1;
  1716. options.arrowSize = 9;
  1717. options.marginXSpacing = 7;
  1718. options.marginYSpacing = 10;
  1719. options.intervalSpacing = 20;
  1720. options.menuCornerRadius = 6.5;
  1721. options.maskToBackground = NO;
  1722. options.shadowOfMenu = YES;
  1723. options.hasSeperatorLine = YES;
  1724. options.seperatorLineHasInsets = YES;
  1725. options.textColor = textColor;
  1726. options.menuBackgroundColor = backgroundColor;
  1727. CGRect rect = self.view.frame;
  1728. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1729. CGFloat safeAreaTop = 0;
  1730. CGFloat offsetY = 35;
  1731. if (@available(iOS 11, *)) {
  1732. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1733. }
  1734. rect.origin.y = locationY + safeAreaTop + offsetY;
  1735. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1736. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1737. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1738. }
  1739. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1740. {
  1741. [appDelegate.netQueue cancelAllOperations];
  1742. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1743. // LOGOUT
  1744. [appDelegate unsubscribingNextcloudServerPushNotification];
  1745. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1746. if (tableAccount) {
  1747. // LOGIN
  1748. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  1749. // go to home sweet home
  1750. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1751. [appDelegate subscribingNextcloudServerPushNotification];
  1752. }
  1753. });
  1754. }
  1755. - (void)addNewAccount:(CCMenuItem *)sender
  1756. {
  1757. [appDelegate.netQueue cancelAllOperations];
  1758. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1759. [appDelegate openLoginView:self loginType:k_login_Add selector:k_intro_login];
  1760. });
  1761. }
  1762. #pragma --------------------------------------------------------------------------------------------
  1763. #pragma mark ==== ReMenu ====
  1764. #pragma --------------------------------------------------------------------------------------------
  1765. - (void)createReMenuBackgroundView:(REMenu *)menu
  1766. {
  1767. CGFloat safeAreaBottom = 0;
  1768. CGFloat safeAreaTop = 0;
  1769. CGFloat statusBar = 0;
  1770. if (@available(iOS 11, *)) {
  1771. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1772. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1773. }
  1774. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1775. statusBar = 13;
  1776. }
  1777. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1778. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1779. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1780. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1781. [UIView animateWithDuration:0.2 animations:^{
  1782. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1783. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1784. if (y>minimum) {
  1785. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1786. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1787. }
  1788. }];
  1789. }
  1790. - (void)createReMainMenu
  1791. {
  1792. NSString *title;
  1793. NSString *groupBy = [CCUtility getGroupBySettings];
  1794. NSString *sorted = [CCUtility getOrderSettings];
  1795. BOOL ascending = [CCUtility getAscendingSettings];
  1796. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1797. 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) {
  1798. if ([sectionDataSource.allRecordsDataSource count] > 0) [self tableViewSelect:YES];
  1799. }];
  1800. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1801. if ([sorted isEqualToString:@"fileName"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_a_z_", nil)]; }
  1802. else title = NSLocalizedString(@"_order_by_name_a_z_", nil);
  1803. appDelegate.sortFileNameAZItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameAZ"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1804. [CCUtility setOrderSettings:@"fileName"];
  1805. [CCUtility setAscendingSettings:true];
  1806. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1807. }];
  1808. if ([sorted isEqualToString:@"fileName"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_z_a_", nil)]; }
  1809. else title = NSLocalizedString(@"_order_by_name_z_a_", nil);
  1810. appDelegate.sortFileNameZAItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameZA"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1811. [CCUtility setOrderSettings:@"fileName"];
  1812. [CCUtility setAscendingSettings:false];
  1813. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1814. }];
  1815. if ([sorted isEqualToString:@"date"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_more_recent_", nil)]; }
  1816. else title = NSLocalizedString(@"_order_by_date_more_recent_", nil);
  1817. appDelegate.sortDateMoreRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateMoreRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1818. [CCUtility setOrderSettings:@"date"];
  1819. [CCUtility setAscendingSettings:false];
  1820. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1821. }];
  1822. if ([sorted isEqualToString:@"date"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_less_recent_", nil)]; }
  1823. else title = NSLocalizedString(@"_order_by_date_less_recent_", nil);
  1824. appDelegate.sortDateLessRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateLessRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1825. [CCUtility setOrderSettings:@"date"];
  1826. [CCUtility setAscendingSettings:true];
  1827. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1828. }];
  1829. if ([sorted isEqualToString:@"size"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_smallest_", nil)]; }
  1830. else title = NSLocalizedString(@"_order_by_size_smallest_", nil);
  1831. appDelegate.sortSmallestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortSmallest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1832. [CCUtility setOrderSettings:@"size"];
  1833. [CCUtility setAscendingSettings:true];
  1834. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1835. }];
  1836. if ([sorted isEqualToString:@"size"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_largest_", nil)]; }
  1837. else title = NSLocalizedString(@"_order_by_size_largest_", nil);
  1838. appDelegate.sortLargestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortLargest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1839. [CCUtility setOrderSettings:@"size"];
  1840. [CCUtility setAscendingSettings:false];
  1841. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1842. }];
  1843. // ITEM GROUP ALPHABETIC -----------------------------------------------------------------------------------------------------
  1844. if ([groupBy isEqualToString:@"alphabetic"]) { title = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1845. else { title = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1846. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1847. if ([groupBy isEqualToString:@"alphabetic"]) [CCUtility setGroupBySettings:@"none"];
  1848. else [CCUtility setGroupBySettings:@"alphabetic"];
  1849. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1850. }];
  1851. // ITEM GROUP TYPEFILE -------------------------------------------------------------------------------------------------------
  1852. if ([groupBy isEqualToString:@"typefile"]) { title = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1853. else { title = NSLocalizedString(@"_group_typefile_no_", nil); }
  1854. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1855. if ([groupBy isEqualToString:@"typefile"]) [CCUtility setGroupBySettings:@"none"];
  1856. else [CCUtility setGroupBySettings:@"typefile"];
  1857. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1858. }];
  1859. // ITEM GROUP DATE -------------------------------------------------------------------------------------------------------
  1860. if ([groupBy isEqualToString:@"date"]) { title = NSLocalizedString(@"_group_date_yes_", nil); }
  1861. else { title = NSLocalizedString(@"_group_date_no_", nil); }
  1862. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1863. if ([groupBy isEqualToString:@"date"]) [CCUtility setGroupBySettings:@"none"];
  1864. else [CCUtility setGroupBySettings:@"date"];
  1865. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1866. }];
  1867. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1868. if ([CCUtility getDirectoryOnTop]) { title = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1869. else { title = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1870. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"foldersOnTop"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1871. if ([CCUtility getDirectoryOnTop]) [CCUtility setDirectoryOnTop:NO];
  1872. else [CCUtility setDirectoryOnTop:YES];
  1873. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1874. }];
  1875. // REMENU --------------------------------------------------------------------------------------------------------------
  1876. 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]];
  1877. appDelegate.reMainMenu.itemHeight = 40;
  1878. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1879. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1880. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1881. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1882. appDelegate.reMainMenu.separatorHeight = 0.5;
  1883. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1884. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1885. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  1886. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  1887. appDelegate.reMainMenu.textShadowColor = nil;
  1888. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  1889. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  1890. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  1891. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  1892. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  1893. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  1894. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1895. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  1896. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1897. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  1898. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1899. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1900. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1901. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1902. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  1903. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1904. appDelegate.reMainMenu.borderWidth = 0.3;
  1905. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  1906. appDelegate.reMainMenu.animationDuration = 0.2;
  1907. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  1908. appDelegate.reMainMenu.bounce = NO;
  1909. __weak typeof(self) weakSelf = self;
  1910. [appDelegate.reMainMenu setClosePreparationBlock:^{
  1911. // Backgroun reMenu (Gesture)
  1912. [weakSelf.reMenuBackgroundView removeFromSuperview];
  1913. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  1914. }];
  1915. }
  1916. - (void)toggleReMainMenu
  1917. {
  1918. if (appDelegate.reMainMenu.isOpen) {
  1919. [appDelegate.reMainMenu close];
  1920. } else {
  1921. [self createReMainMenu];
  1922. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  1923. // Backgroun reMenu & (Gesture)
  1924. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  1925. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  1926. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  1927. }
  1928. }
  1929. - (void)createReSelectMenu
  1930. {
  1931. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  1932. 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) {
  1933. [self didSelectAll];
  1934. }];
  1935. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  1936. 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) {
  1937. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  1938. }];
  1939. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  1940. 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) {
  1941. [self downloadSelectedFilesFolders];
  1942. }];
  1943. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  1944. 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) {
  1945. [self saveSelectedFiles];
  1946. }];
  1947. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  1948. 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) {
  1949. [self deleteFile];
  1950. }];
  1951. // E2EE
  1952. if (_metadataFolder.e2eEncrypted) {
  1953. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1954. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1955. } else {
  1956. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1957. }
  1958. } else {
  1959. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  1960. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  1961. } else {
  1962. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  1963. }
  1964. }
  1965. appDelegate.reSelectMenu.itemHeight = 50;
  1966. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  1967. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1968. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  1969. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  1970. appDelegate.reSelectMenu.separatorHeight = 0.5;
  1971. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1972. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1973. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  1974. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  1975. appDelegate.reSelectMenu.textShadowColor = nil;
  1976. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  1977. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  1978. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  1979. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  1980. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  1981. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  1982. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  1983. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  1984. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  1985. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  1986. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  1987. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  1988. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  1989. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  1990. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  1991. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  1992. appDelegate.reSelectMenu.borderWidth = 0.3;
  1993. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  1994. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  1995. appDelegate.reSelectMenu.animationDuration = 0.2;
  1996. appDelegate.reSelectMenu.bounce = NO;
  1997. __weak typeof(self) weakSelf = self;
  1998. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  1999. // Backgroun reMenu (Gesture)
  2000. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2001. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2002. }];
  2003. }
  2004. - (void)toggleReSelectMenu
  2005. {
  2006. if (appDelegate.reSelectMenu.isOpen) {
  2007. [appDelegate.reSelectMenu close];
  2008. } else {
  2009. [self createReSelectMenu];
  2010. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2011. // Backgroun reMenu & (Gesture)
  2012. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2013. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2014. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2015. }
  2016. }
  2017. #pragma --------------------------------------------------------------------------------------------
  2018. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2019. #pragma --------------------------------------------------------------------------------------------
  2020. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2021. {
  2022. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2023. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2024. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2025. if ([self indexPathIsValid:indexPath])
  2026. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2027. else
  2028. self.metadata = nil;
  2029. [self becomeFirstResponder];
  2030. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2031. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2032. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2033. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2034. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2035. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2036. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2037. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, pasteFileItem, pasteFilesItem, nil]];
  2038. } else {
  2039. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2040. }
  2041. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2042. [menuController setMenuVisible:YES animated:YES];
  2043. }
  2044. }
  2045. - (BOOL)canBecomeFirstResponder
  2046. {
  2047. return YES;
  2048. }
  2049. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2050. {
  2051. // For copy file, copy files, Open in ... :
  2052. //
  2053. // NO Directory
  2054. // NO Error Passcode
  2055. // NO In Session mode (download/upload)
  2056. // NO Template
  2057. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2058. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  2059. else return NO;
  2060. }
  2061. if (@selector(copyFiles:) == action) {
  2062. if (_isSelectedMode) {
  2063. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2064. for (tableMetadata *metadata in selectedMetadatas) {
  2065. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2066. return YES;
  2067. }
  2068. }
  2069. return NO;
  2070. }
  2071. if (@selector(pasteFile:) == action) {
  2072. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2073. NSArray *items = [pasteboard items];
  2074. if ([items count] == 1) {
  2075. // Value : (NSData) fileID
  2076. NSDictionary *dic = [items objectAtIndex:0];
  2077. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2078. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2079. if (fileID) {
  2080. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2081. if (metadata) {
  2082. return [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView];
  2083. } else {
  2084. return NO;
  2085. }
  2086. }
  2087. }
  2088. return NO;
  2089. }
  2090. if (@selector(pasteFiles:) == action) {
  2091. BOOL isValid = NO;
  2092. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2093. NSArray *items = [pasteboard items];
  2094. if ([items count] <= 1) return NO;
  2095. for (NSDictionary *dic in items) {
  2096. // Value : (NSData) fileID
  2097. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2098. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2099. if (fileID) {
  2100. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2101. if (metadata) {
  2102. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2103. isValid = YES;
  2104. } else {
  2105. isValid = NO;
  2106. break;
  2107. }
  2108. } else {
  2109. isValid = NO;
  2110. break;
  2111. }
  2112. } else {
  2113. isValid = NO;
  2114. break;
  2115. }
  2116. }
  2117. return isValid;
  2118. }
  2119. return NO;
  2120. }
  2121. /************************************ COPY ************************************/
  2122. - (void)copyFile:(id)sender
  2123. {
  2124. // Remove all item
  2125. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2126. pasteboard.items = [[NSArray alloc] init];
  2127. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2128. [self copyFileToPasteboard:self.metadata];
  2129. } else {
  2130. self.metadata.session = k_download_session;
  2131. self.metadata.sessionError = @"";
  2132. self.metadata.sessionSelector = selectorLoadCopy;
  2133. self.metadata.status = k_metadataStatusWaitDownload;
  2134. // Add Metadata for Download
  2135. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2136. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2137. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2138. }
  2139. }
  2140. - (void)copyFiles:(id)sender
  2141. {
  2142. // Remove all item
  2143. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2144. pasteboard.items = [[NSArray alloc] init];
  2145. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2146. for (tableMetadata *metadata in selectedMetadatas) {
  2147. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2148. [self copyFileToPasteboard:metadata];
  2149. } else {
  2150. metadata.session = k_download_session;
  2151. metadata.sessionError = @"";
  2152. metadata.sessionSelector = selectorLoadCopy;
  2153. metadata.status = k_metadataStatusWaitDownload;
  2154. // Add Metadata for Download
  2155. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2156. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2157. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  2158. }
  2159. }
  2160. [self tableViewSelect:NO];
  2161. }
  2162. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2163. {
  2164. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2165. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2166. // Value : (NSData) fileID
  2167. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2168. [items addObject:item];
  2169. [pasteboard setItems:items];
  2170. }
  2171. /************************************ OPEN IN ... ******************************/
  2172. - (void)openinFile:(id)sender
  2173. {
  2174. [self DownloadOpenIn:self.metadata];
  2175. }
  2176. /************************************ PASTE ************************************/
  2177. - (void)pasteFile:(id)sender
  2178. {
  2179. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2180. [self uploadFilePasteArray:[pasteboard items]];
  2181. }
  2182. - (void)pasteFiles:(id)sender
  2183. {
  2184. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2185. [self uploadFilePasteArray:[pasteboard items]];
  2186. }
  2187. - (void)uploadFilePasteArray:(NSArray *)items
  2188. {
  2189. for (NSDictionary *dic in items) {
  2190. // Value : (NSData) fileID
  2191. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2192. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2193. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2194. if (metadata) {
  2195. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2196. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  2197. NSString *fileID = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  2198. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName]];
  2199. tableMetadata *metadataForUpload = [tableMetadata new];
  2200. metadataForUpload.account = appDelegate.activeAccount;
  2201. metadataForUpload.date = [NSDate new];
  2202. metadataForUpload.fileID = fileID;
  2203. metadataForUpload.fileName = fileName;
  2204. metadataForUpload.fileNameView = fileName;
  2205. metadataForUpload.serverUrl = self.serverUrl;
  2206. metadataForUpload.session = k_upload_session;
  2207. metadataForUpload.sessionSelector = selectorUploadFile;
  2208. metadataForUpload.size = metadata.size;
  2209. metadataForUpload.status = k_metadataStatusWaitUpload;
  2210. // Add Medtadata for upload
  2211. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2212. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2213. }
  2214. }
  2215. }
  2216. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2217. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2218. }
  2219. #pragma --------------------------------------------------------------------------------------------
  2220. #pragma mark ===== Lock Passcode =====
  2221. #pragma --------------------------------------------------------------------------------------------
  2222. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2223. {
  2224. return _failedAttempts;
  2225. }
  2226. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2227. {
  2228. return _lockUntilDate;
  2229. }
  2230. - (void)passcodeViewCloseButtonPressed:(id)sender
  2231. {
  2232. [self dismissViewControllerAnimated:YES completion:nil];
  2233. }
  2234. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2235. {
  2236. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2237. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2238. _lockUntilDate = nil;
  2239. _failedAttempts = 0;
  2240. aResultHandler(YES);
  2241. } else aResultHandler(NO);
  2242. } else aResultHandler(YES);
  2243. }
  2244. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2245. {
  2246. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2247. switch (aViewController.type) {
  2248. case BKPasscodeViewControllerCheckPasscodeType: {
  2249. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2250. // possiamo procedere alla prossima directory
  2251. [self performSegueDirectoryWithControlPasscode:false];
  2252. // avviamo la sessione Passcode Lock con now
  2253. appDelegate.sessionePasscodeLock = [NSDate date];
  2254. }
  2255. // disattivazione lock cartella
  2256. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2257. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2258. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  2259. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2260. }
  2261. [self tableViewReloadData];
  2262. }
  2263. }
  2264. break;
  2265. default:
  2266. break;
  2267. }
  2268. }
  2269. - (void)comandoLockPassword
  2270. {
  2271. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2272. // se non è abilitato il Lock Passcode esci
  2273. if ([[CCUtility getBlockCode] length] == 0) {
  2274. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2275. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2276. [alertController addAction:okAction];
  2277. [self presentViewController:alertController animated:YES completion:nil];
  2278. return;
  2279. }
  2280. // se è richiesta la disattivazione si chiede la password
  2281. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2282. if (directory.lock) {
  2283. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2284. viewController.delegate = self;
  2285. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2286. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2287. viewController.inputViewTitlePassword = YES;
  2288. if ([CCUtility getSimplyBlockCode]) {
  2289. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2290. viewController.passcodeInputView.maximumLength = 6;
  2291. } else {
  2292. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2293. viewController.passcodeInputView.maximumLength = 64;
  2294. }
  2295. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2296. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2297. viewController.touchIDManager = touchIDManager;
  2298. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2299. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2300. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2301. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2302. [self presentViewController:navigationController animated:YES completion:nil];
  2303. return;
  2304. }
  2305. // ---------------- ACTIVATE PASSWORD
  2306. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  2307. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:self.metadata.fileID];
  2308. if ([self indexPathIsValid:indexPath])
  2309. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2310. } else {
  2311. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2312. }
  2313. }
  2314. #pragma mark -
  2315. #pragma --------------------------------------------------------------------------------------------
  2316. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2317. #pragma --------------------------------------------------------------------------------------------
  2318. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2319. {
  2320. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal)
  2321. return NO;
  2322. // E2EE
  2323. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2324. return NO;
  2325. return YES;
  2326. }
  2327. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2328. {
  2329. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2330. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2331. return [self canOpenMenuAction:metadata];
  2332. }
  2333. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2334. {
  2335. }
  2336. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2337. {
  2338. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2339. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2340. if (direction == MGSwipeDirectionRightToLeft) {
  2341. [self actionDelete:indexPath];
  2342. }
  2343. if (direction == MGSwipeDirectionLeftToRight) {
  2344. if (self.metadata.favorite)
  2345. [self settingFavorite:self.metadata favorite:NO];
  2346. else
  2347. [self settingFavorite:self.metadata favorite:YES];
  2348. }
  2349. return YES;
  2350. }
  2351. - (void)actionDelete:(NSIndexPath *)indexPath
  2352. {
  2353. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2354. // Directory locked ?
  2355. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  2356. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2357. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2358. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2359. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2360. return;
  2361. }
  2362. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2363. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2364. [self performSelector:@selector(deleteFile) withObject:nil];
  2365. }]];
  2366. if (localFile) {
  2367. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2368. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2369. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  2370. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2371. }]];
  2372. }
  2373. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2374. }]];
  2375. alertController.popoverPresentationController.sourceView = self.tableView;
  2376. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2377. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2378. [alertController.view layoutIfNeeded];
  2379. [self presentViewController:alertController animated:YES completion:nil];
  2380. }
  2381. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2382. {
  2383. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2384. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2385. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2386. NSString *titoloLock, *titleFavorite;
  2387. if (self.metadata.favorite) {
  2388. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2389. } else {
  2390. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2391. }
  2392. if (self.metadata.directory) {
  2393. // calcolo lockServerUrl
  2394. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2395. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2396. if (directory.lock)
  2397. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2398. else
  2399. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2400. }
  2401. // ******************************************* AHKActionSheet *******************************************
  2402. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2403. actionSheet.animationDuration = 0.2;
  2404. actionSheet.buttonHeight = 50.0;
  2405. actionSheet.cancelButtonHeight = 50.0f;
  2406. actionSheet.separatorHeight = 5.0f;
  2407. actionSheet.automaticallyTintButtonImages = @(NO);
  2408. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2409. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2410. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2411. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2412. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2413. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2414. // ******************************************* DIRECTORY *******************************************
  2415. if (self.metadata.directory) {
  2416. BOOL lockDirectory = NO;
  2417. BOOL isOffline = NO;
  2418. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  2419. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2420. // Directory bloccata ?
  2421. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2422. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2423. if (directory.offline) isOffline = YES;
  2424. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2425. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2426. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2427. height:50.0
  2428. type:AHKActionSheetButtonTypeDisabled
  2429. handler:nil
  2430. ];
  2431. [actionSheet addButtonWithTitle: titleFavorite
  2432. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2433. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2434. height: 50.0
  2435. type: AHKActionSheetButtonTypeDefault
  2436. handler: ^(AHKActionSheet *as) {
  2437. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2438. else [self settingFavorite:self.metadata favorite:YES];
  2439. }];
  2440. if (!lockDirectory && !isFolderEncrypted) {
  2441. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2442. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2443. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2444. height:50.0
  2445. type:AHKActionSheetButtonTypeDefault
  2446. handler:^(AHKActionSheet *as) {
  2447. [self openWindowShare:self.metadata];
  2448. }];
  2449. }
  2450. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2451. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2452. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2453. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2454. height:50.0
  2455. type:AHKActionSheetButtonTypeDefault
  2456. handler:^(AHKActionSheet *as) {
  2457. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2458. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2459. textField.text = self.metadata.fileNameView;
  2460. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2461. //textField.delegate = self;
  2462. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2463. }];
  2464. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2465. NSLog(@"[LOG] Cancel action");
  2466. }];
  2467. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2468. UITextField *fileName = alertController.textFields.firstObject;
  2469. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2470. }];
  2471. okAction.enabled = NO;
  2472. [alertController addAction:cancelAction];
  2473. [alertController addAction:okAction];
  2474. [self presentViewController:alertController animated:YES completion:nil];
  2475. }];
  2476. }
  2477. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2478. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2479. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2480. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2481. height:50.0
  2482. type:AHKActionSheetButtonTypeDefault
  2483. handler:^(AHKActionSheet *as) {
  2484. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2485. }];
  2486. }
  2487. if (!isFolderEncrypted) {
  2488. NSString *title;
  2489. if (isOffline) {
  2490. title = NSLocalizedString(@"_remove_available_offline_", nil);
  2491. } else {
  2492. title = NSLocalizedString(@"_set_available_offline_", nil);
  2493. }
  2494. [actionSheet addButtonWithTitle:title
  2495. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2496. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2497. height:50.0
  2498. type:AHKActionSheetButtonTypeDefault
  2499. handler:^(AHKActionSheet *as) {
  2500. if (isOffline) {
  2501. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:false account:appDelegate.activeAccount];
  2502. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2503. } else {
  2504. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true account:appDelegate.activeAccount];
  2505. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload];
  2506. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2507. }
  2508. }];
  2509. }
  2510. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [self.metadata.serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2511. [actionSheet addButtonWithTitle:titoloLock
  2512. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2513. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2514. height:50.0
  2515. type:AHKActionSheetButtonTypeDefault
  2516. handler:^(AHKActionSheet *as) {
  2517. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2518. }];
  2519. }
  2520. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2521. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2522. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2523. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2524. height:50.0
  2525. type:AHKActionSheetButtonTypeDefault
  2526. handler:^(AHKActionSheet *as) {
  2527. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2528. 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];
  2529. dispatch_async(dispatch_get_main_queue(), ^{
  2530. if (error) {
  2531. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2532. } else {
  2533. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2534. [self readFolder:self.serverUrl];
  2535. }
  2536. });
  2537. });
  2538. }];
  2539. }
  2540. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2541. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2542. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2543. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2544. height:50.0
  2545. type:AHKActionSheetButtonTypeDefault
  2546. handler:^(AHKActionSheet *as) {
  2547. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2548. 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];
  2549. dispatch_async(dispatch_get_main_queue(), ^{
  2550. if (error) {
  2551. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2552. } else {
  2553. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2554. [self readFolder:self.serverUrl];
  2555. }
  2556. });
  2557. });
  2558. }];
  2559. }
  2560. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2561. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2562. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2563. height:50.0
  2564. type:AHKActionSheetButtonTypeDestructive
  2565. handler:^(AHKActionSheet *as) {
  2566. [self actionDelete:indexPath];
  2567. }];
  2568. [actionSheet show];
  2569. }
  2570. // ******************************************* FILE *******************************************
  2571. if (!self.metadata.directory) {
  2572. UIImage *iconHeader;
  2573. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2574. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]])
  2575. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]];
  2576. else
  2577. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2578. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2579. image: iconHeader
  2580. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2581. height: 50.0
  2582. type: AHKActionSheetButtonTypeDisabled
  2583. handler: nil
  2584. ];
  2585. [actionSheet addButtonWithTitle: titleFavorite
  2586. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2587. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2588. height: 50.0
  2589. type: AHKActionSheetButtonTypeDefault
  2590. handler: ^(AHKActionSheet *as) {
  2591. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2592. else [self settingFavorite:self.metadata favorite:YES];
  2593. }];
  2594. if (!_metadataFolder.e2eEncrypted) {
  2595. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2596. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2597. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2598. height: 50.0
  2599. type:AHKActionSheetButtonTypeDefault
  2600. handler:^(AHKActionSheet *as) {
  2601. [self openWindowShare:self.metadata];
  2602. }];
  2603. }
  2604. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  2605. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2606. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2607. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2608. height: 50.0
  2609. type:AHKActionSheetButtonTypeDefault
  2610. handler:^(AHKActionSheet *as) {
  2611. [self performSelector:@selector(DownloadOpenIn:) withObject:self.metadata];
  2612. }];
  2613. }
  2614. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2615. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2616. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2617. height: 50.0
  2618. type:AHKActionSheetButtonTypeDefault
  2619. handler:^(AHKActionSheet *as) {
  2620. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2621. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2622. textField.text = self.metadata.fileNameView;
  2623. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2624. }];
  2625. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2626. NSLog(@"[LOG] Cancel action");
  2627. }];
  2628. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2629. UITextField *fileName = alertController.textFields.firstObject;
  2630. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2631. }];
  2632. okAction.enabled = NO;
  2633. [alertController addAction:cancelAction];
  2634. [alertController addAction:okAction];
  2635. [self presentViewController:alertController animated:YES completion:nil];
  2636. }];
  2637. if (!_metadataFolder.e2eEncrypted) {
  2638. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2639. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2640. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2641. height:50.0
  2642. type:AHKActionSheetButtonTypeDefault
  2643. handler:^(AHKActionSheet *as) {
  2644. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2645. }];
  2646. }
  2647. if (!_metadataFolder.e2eEncrypted) {
  2648. NSString *title;
  2649. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadata.fileID]];
  2650. if (localFile == nil || localFile.offline == false) { title = NSLocalizedString(@"_set_available_offline_", nil); }
  2651. else { title = NSLocalizedString(@"_remove_available_offline_", nil); }
  2652. [actionSheet addButtonWithTitle:title
  2653. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2654. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2655. height:50.0
  2656. type:AHKActionSheetButtonTypeDefault
  2657. handler:^(AHKActionSheet *as) {
  2658. if (localFile == nil || ![CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2659. self.metadata.session = k_download_session;
  2660. self.metadata.sessionError = @"";
  2661. self.metadata.sessionSelector = selectorLoadOffline;
  2662. self.metadata.status = k_metadataStatusWaitDownload;
  2663. // Add Metadata for Download
  2664. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2665. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2666. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2667. } else if (localFile.offline == false) {
  2668. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:true];
  2669. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2670. } else {
  2671. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:false];
  2672. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2673. }
  2674. }];
  2675. }
  2676. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2677. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2678. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2679. height:50.0
  2680. type:AHKActionSheetButtonTypeDestructive
  2681. handler:^(AHKActionSheet *as) {
  2682. [self actionDelete:indexPath];
  2683. }];
  2684. [actionSheet show];
  2685. }
  2686. }
  2687. #pragma --------------------------------------------------------------------------------------------
  2688. #pragma mark - ==== Datasource ====
  2689. #pragma --------------------------------------------------------------------------------------------
  2690. - (void)clearDateReadDataSource:(NSNotification *)notification
  2691. {
  2692. _dateReadDataSource = Nil;
  2693. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2694. }
  2695. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID action:(NSInteger)action
  2696. {
  2697. // test
  2698. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2699. return;
  2700. // Search Mode
  2701. if (_isSearchMode) {
  2702. // Create metadatas
  2703. NSMutableArray *metadatas = [NSMutableArray new];
  2704. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2705. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", resultMetadata.fileID]];
  2706. if (metadata) {
  2707. [metadatas addObject:metadata];
  2708. }
  2709. }
  2710. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2711. [self tableViewReloadData];
  2712. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2713. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2714. _noFilesSearchDescription = @"";
  2715. }
  2716. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2717. _noFilesSearchTitle = @"";
  2718. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2719. }
  2720. [self.tableView reloadEmptyDataSet];
  2721. return;
  2722. }
  2723. // Se non siamo nella dir appropriata esci
  2724. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2725. return;
  2726. }
  2727. // Remove optimization for encrypted directory
  2728. if (_metadataFolder.e2eEncrypted)
  2729. _dateReadDataSource = nil;
  2730. // Controllo data lettura Data Source
  2731. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2732. // Get MetadataFolder
  2733. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2734. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  2735. else
  2736. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  2737. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2738. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2739. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2740. _dateReadDataSource = [NSDate date];
  2741. // Data Source
  2742. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2743. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2744. dispatch_async(dispatch_get_main_queue(), ^{
  2745. sectionDataSource = sectionDataSourceTemp;
  2746. [self tableViewReloadData];
  2747. });
  2748. });
  2749. } else {
  2750. [self tableViewReloadData];
  2751. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2752. }
  2753. }
  2754. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2755. {
  2756. // test
  2757. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2758. return nil;
  2759. }
  2760. // get auto upload folder
  2761. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2762. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2763. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2764. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND status != %i", appDelegate.activeAccount, serverUrl, k_metadataStatusHide] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  2765. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2766. if (withReloadData) {
  2767. sectionDataSource = sectionDataSourceTemp;
  2768. [self tableViewReloadData];
  2769. }
  2770. return sectionDataSourceTemp;
  2771. }
  2772. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2773. {
  2774. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2775. if (selectedRows.count > 0) {
  2776. for (NSIndexPath *selectionIndex in selectedRows) {
  2777. NSString *fileID = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2778. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  2779. [metadatas addObject:metadata];
  2780. }
  2781. }
  2782. return metadatas;
  2783. }
  2784. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2785. {
  2786. NSInteger totSections =[sectionDataSource.sections count] ;
  2787. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2788. return nil;
  2789. }
  2790. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2791. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2792. }
  2793. #pragma --------------------------------------------------------------------------------------------
  2794. #pragma mark - ==== Table ====
  2795. #pragma --------------------------------------------------------------------------------------------
  2796. - (void)tableViewSelect:(BOOL)edit
  2797. {
  2798. // chiudiamo eventuali swipe aperti
  2799. if (edit)
  2800. [self.tableView setEditing:NO animated:NO];
  2801. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2802. [self.tableView setEditing:edit animated:YES];
  2803. _isSelectedMode = edit;
  2804. if (edit)
  2805. [self setUINavigationBarSelected];
  2806. else
  2807. [self setUINavigationBarDefault];
  2808. [_selectedFileIDsMetadatas removeAllObjects];
  2809. [self setTitle];
  2810. }
  2811. - (void)tableViewReloadData
  2812. {
  2813. // store selected cells before relod
  2814. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2815. // reload table view
  2816. [self.tableView reloadData];
  2817. // selected cells stored
  2818. for (NSIndexPath *path in indexPaths)
  2819. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2820. [self setTableViewFooter];
  2821. if (self.tableView.editing)
  2822. [self setTitle];
  2823. //
  2824. [self.tableView reloadEmptyDataSet];
  2825. }
  2826. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2827. {
  2828. if (tableView.editing == 1) {
  2829. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2830. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2831. return NO;
  2832. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2833. return NO;
  2834. else
  2835. return YES;
  2836. } else {
  2837. [_selectedFileIDsMetadatas removeAllObjects];
  2838. }
  2839. return YES;
  2840. }
  2841. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2842. {
  2843. return 60;
  2844. }
  2845. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2846. {
  2847. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2848. }
  2849. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2850. {
  2851. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2852. }
  2853. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2854. {
  2855. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2856. NSString *sectionTitle = [sections objectAtIndex:section];
  2857. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2858. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2859. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2860. return 20.f;
  2861. }
  2862. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2863. {
  2864. float shift;
  2865. UIVisualEffectView *visualEffectView;
  2866. NSString *titleSection;
  2867. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2868. return nil;
  2869. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2870. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2871. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2872. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2873. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2874. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2875. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2876. else titleSection = NSLocalizedString(titleSection,nil);
  2877. // Format title
  2878. NSString *currentDevice = [CCUtility currentDevice];
  2879. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  2880. visualEffectView = [[UIVisualEffectView alloc] init];
  2881. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  2882. } else {
  2883. UIVisualEffect *blurEffect;
  2884. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2885. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2886. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  2887. }
  2888. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2889. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2890. shift = - 35;
  2891. else
  2892. shift = - 20;
  2893. } else shift = - 10;
  2894. // Title
  2895. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2896. titleLabel.backgroundColor = [UIColor clearColor];
  2897. titleLabel.textColor = [UIColor blackColor];
  2898. titleLabel.font = [UIFont systemFontOfSize:12];
  2899. titleLabel.textAlignment = NSTextAlignmentLeft;
  2900. titleLabel.text = titleSection;
  2901. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2902. [visualEffectView.contentView addSubview:titleLabel];
  2903. // Elements
  2904. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2905. elementLabel.backgroundColor = [UIColor clearColor];
  2906. elementLabel.textColor = [UIColor blackColor];;
  2907. elementLabel.font = [UIFont systemFontOfSize:12];
  2908. elementLabel.textAlignment = NSTextAlignmentRight;
  2909. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2910. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2911. NSUInteger rowsCount = [metadatas count];
  2912. if (rowsCount == 0) return nil;
  2913. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2914. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2915. [visualEffectView.contentView addSubview:elementLabel];
  2916. return visualEffectView;
  2917. }
  2918. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2919. {
  2920. return [sectionDataSource.sections indexOfObject:title];
  2921. }
  2922. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2923. {
  2924. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2925. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2926. else
  2927. return nil;
  2928. }
  2929. /*
  2930. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2931. {
  2932. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2933. }
  2934. }
  2935. */
  2936. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2937. {
  2938. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2939. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  2940. return [CCCellMain new];
  2941. }
  2942. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory];
  2943. // NORMAL - > MAIN
  2944. if ([cell isKindOfClass:[CCCellMain class]]) {
  2945. NSString *shareLink = [appDelegate.sharesLink objectForKey:[metadata.serverUrl stringByAppendingString:metadata.fileName]];
  2946. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[metadata.serverUrl stringByAppendingString:metadata.fileName]];
  2947. BOOL isShare = false;
  2948. BOOL isMounted = false;
  2949. if (_metadataFolder) {
  2950. isShare = [metadata.permissions containsString:k_permission_shared] && ![_metadataFolder.permissions containsString:k_permission_shared];
  2951. isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_metadataFolder.permissions containsString:k_permission_mounted];
  2952. }
  2953. // Share add Tap
  2954. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  2955. if (isShare || isMounted) {
  2956. // Shared with you
  2957. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  2958. [tap setNumberOfTapsRequired:1];
  2959. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  2960. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  2961. } else if (shareLink != nil || shareUserAndGroup != nil) {
  2962. // You share
  2963. if (metadata.directory) {
  2964. ((CCCellMain *)cell).shared.userInteractionEnabled = NO;
  2965. } else {
  2966. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2967. [tap setNumberOfTapsRequired:1];
  2968. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  2969. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  2970. }
  2971. }
  2972. }
  2973. // More
  2974. if ([self canOpenMenuAction:metadata]) {
  2975. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2976. [tapMore setNumberOfTapsRequired:1];
  2977. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2978. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2979. }
  2980. // MGSwipeButton
  2981. ((CCCellMain *)cell).delegate = self;
  2982. // LEFT
  2983. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:1 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  2984. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2985. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2986. //centerIconOverText
  2987. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2988. [favoriteButton centerIconOverText];
  2989. // RIGHT
  2990. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  2991. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2992. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2993. //centerIconOverText
  2994. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2995. [deleteButton centerIconOverText];
  2996. }
  2997. // TRANSFER
  2998. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2999. // gesture Transfer
  3000. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3001. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  3002. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3003. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  3004. }
  3005. return cell;
  3006. }
  3007. - (void)setTableViewFooter
  3008. {
  3009. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3010. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3011. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3012. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3013. UIFont *appFont = [UIFont systemFontOfSize:12];
  3014. footerLabel.font = appFont;
  3015. footerLabel.textColor = [UIColor grayColor];
  3016. footerLabel.backgroundColor = [UIColor clearColor];
  3017. footerLabel.textAlignment = NSTextAlignmentCenter;
  3018. NSString *folders;
  3019. NSString *files;
  3020. NSString *footerText;
  3021. if (sectionDataSource.directories > 1) {
  3022. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3023. } else if (sectionDataSource.directories == 1){
  3024. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3025. } else {
  3026. folders = @"";
  3027. }
  3028. if (sectionDataSource.files > 1) {
  3029. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3030. } else if (sectionDataSource.files == 1){
  3031. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3032. } else {
  3033. files = @"";
  3034. }
  3035. if ([folders isEqualToString:@""]) {
  3036. footerText = files;
  3037. } else if ([files isEqualToString:@""]) {
  3038. footerText = folders;
  3039. } else {
  3040. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3041. }
  3042. footerLabel.text = footerText;
  3043. [footerView addSubview:footerLabel];
  3044. [self.tableView setTableFooterView:footerView];
  3045. }
  3046. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3047. {
  3048. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3049. // settiamo il record file.
  3050. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3051. if (!self.metadata)
  3052. return;
  3053. // se non può essere selezionata deseleziona
  3054. if ([cell isEditing] == NO)
  3055. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3056. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3057. if (self.tableView.editing) {
  3058. [_selectedFileIDsMetadatas setObject:self.metadata forKey:self.metadata.fileID];
  3059. [self setTitle];
  3060. return;
  3061. }
  3062. // se è in corso una sessione
  3063. if (self.metadata.status != k_metadataStatusNormal)
  3064. return;
  3065. // file
  3066. if (self.metadata.directory == NO) {
  3067. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3068. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  3069. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName fileID:self.metadata.fileID serverUrl:self.metadata.serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3070. } else {
  3071. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3072. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3073. } else {
  3074. 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) {
  3075. [self shouldPerformSegue:self.metadata];
  3076. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCViewerRichdocument sharedInstance] isRichDocument:self.metadata]) {
  3077. [self shouldPerformSegue:self.metadata];
  3078. } else {
  3079. self.metadata.session = k_download_session;
  3080. self.metadata.sessionError = @"";
  3081. self.metadata.sessionSelector = selectorLoadFileView;
  3082. self.metadata.status = k_metadataStatusWaitDownload;
  3083. // Add Metadata for Download
  3084. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  3085. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3086. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  3087. }
  3088. }
  3089. }
  3090. }
  3091. if (self.metadata.directory) {
  3092. imageTitleSegue = cell.imageTitleSegue;
  3093. [self performSegueDirectoryWithControlPasscode:true];
  3094. }
  3095. }
  3096. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3097. {
  3098. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3099. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3100. [self setTitle];
  3101. }
  3102. - (void)didSelectAll
  3103. {
  3104. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3105. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3106. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3107. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3108. [_selectedFileIDsMetadatas setObject:metadata forKey:metadata.fileID];
  3109. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3110. }
  3111. }
  3112. [self setTitle];
  3113. }
  3114. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3115. {
  3116. if (!indexPath)
  3117. return NO;
  3118. NSInteger section = indexPath.section;
  3119. NSInteger row = indexPath.row;
  3120. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3121. if (section > lastSectionIndex || lastSectionIndex < 0)
  3122. return NO;
  3123. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3124. if (rowCount < 0)
  3125. return NO;
  3126. return row <= rowCount;
  3127. }
  3128. #pragma --------------------------------------------------------------------------------------------
  3129. #pragma mark ===== Navigation ====
  3130. #pragma --------------------------------------------------------------------------------------------
  3131. - (void)shouldPerformSegue:(tableMetadata *)metadata
  3132. {
  3133. // if background return
  3134. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3135. if (self.view.window == NO)
  3136. return;
  3137. // Collapsed ma siamo già in detail esci
  3138. if (self.splitViewController.isCollapsed)
  3139. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3140. // Metadata for push detail
  3141. self.metadataForPushDetail = metadata;
  3142. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3143. }
  3144. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3145. {
  3146. id viewController = segue.destinationViewController;
  3147. tableMetadata *metadata;
  3148. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3149. UINavigationController *nav = viewController;
  3150. _detailViewController = (CCDetail *)nav.topViewController;
  3151. } else {
  3152. _detailViewController = segue.destinationViewController;
  3153. }
  3154. NSMutableArray *photoDataSource = [NSMutableArray new];
  3155. if ([sender isKindOfClass:[tableMetadata class]]) {
  3156. metadata = sender;
  3157. [photoDataSource addObject:sender];
  3158. } else {
  3159. metadata = self.metadataForPushDetail;
  3160. for (NSString *fileID in sectionDataSource.allFileID) {
  3161. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3162. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3163. [photoDataSource addObject:metadata];
  3164. }
  3165. }
  3166. _detailViewController.metadataDetail = metadata;
  3167. _detailViewController.photoDataSource = photoDataSource;
  3168. _detailViewController.dateFilterQuery = nil;
  3169. [_detailViewController setTitle:metadata.fileNameView];
  3170. }
  3171. // can i go to next viewcontroller
  3172. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3173. {
  3174. NSString *nomeDir;
  3175. if (self.tableView.editing == NO) {
  3176. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  3177. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3178. // 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
  3179. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3180. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3181. viewController.delegate = self;
  3182. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3183. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3184. viewController.inputViewTitlePassword = YES;
  3185. if ([CCUtility getSimplyBlockCode]) {
  3186. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3187. viewController.passcodeInputView.maximumLength = 6;
  3188. } else {
  3189. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3190. viewController.passcodeInputView.maximumLength = 64;
  3191. }
  3192. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3193. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3194. viewController.touchIDManager = touchIDManager;
  3195. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3196. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3197. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3198. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3199. [self presentViewController:navController animated:YES completion:nil];
  3200. return;
  3201. }
  3202. // E2EE Check enable
  3203. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3204. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3205. return;
  3206. }
  3207. nomeDir = self.metadata.fileName;
  3208. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:nomeDir];
  3209. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3210. if (!viewController) {
  3211. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3212. viewController.serverUrl = serverUrlPush;
  3213. viewController.titleMain = self.metadata.fileName;
  3214. // save self
  3215. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3216. [self.navigationController pushViewController:viewController animated:YES];
  3217. } else {
  3218. if (viewController.isViewLoaded) {
  3219. viewController.titleMain = self.metadata.fileName;
  3220. // Fix : Application tried to present modally an active controller
  3221. if ([self.navigationController isBeingPresented]) {
  3222. // being presented
  3223. } else if ([self.navigationController isMovingToParentViewController]) {
  3224. // being pushed
  3225. } else {
  3226. [self.navigationController pushViewController:viewController animated:YES];
  3227. }
  3228. }
  3229. }
  3230. }
  3231. }
  3232. @end