CCMain.m 210 KB

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