CCMain.m 223 KB

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