CCMain.m 229 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "OCActivity.h"
  28. #import "OCNotifications.h"
  29. #import "OCNotificationsAction.h"
  30. #import "OCFrameworkConstants.h"
  31. #import "OCCapabilities.h"
  32. #import "CTAssetCheckmark.h"
  33. #import "JDStatusBarNotification.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. #import "NCNetworkingEndToEnd.h"
  37. #import "PKDownloadButton.h"
  38. @interface CCMain () <CCActionsRenameDelegate, CCActionsSearchDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. AppDelegate *appDelegate;
  41. tableMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. UIImageView *_ImageTitleHomeCryptoCloud;
  48. NSString *_directoryGroupBy;
  49. NSString *_directoryOrder;
  50. NSUInteger _failedAttempts;
  51. NSDate *_lockUntilDate;
  52. 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 reloadDatasource];
  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 ====
  797. #pragma --------------------------------------------------------------------------------------------
  798. - (void)downloadThumbnail:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl indexPath:(NSIndexPath *)indexPath
  799. {
  800. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  801. [ocNetworking downloadThumbnailWithDimOfThumbnail:@"m" fileID:metadata.fileID fileNamePath:[CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl] fileNameView:metadata.fileNameView completion:^(NSString *message, NSInteger errorCode) {
  802. if (errorCode == 0 && [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  803. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  804. }
  805. }];
  806. }
  807. #pragma --------------------------------------------------------------------------------------------
  808. #pragma mark ==== Download ====
  809. #pragma --------------------------------------------------------------------------------------------
  810. - (void)downloadStart:(NSString *)fileID account:(NSString *)account task:(NSURLSessionDownloadTask *)task serverUrl:(NSString *)serverUrl
  811. {
  812. [self reloadDatasource:serverUrl];
  813. [appDelegate updateApplicationIconBadgeNumber];
  814. }
  815. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  816. {
  817. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  818. if (metadata == nil)
  819. return;
  820. if (errorCode == 0) {
  821. // Synchronized
  822. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  823. [self reloadDatasource:serverUrl];
  824. }
  825. // open View File
  826. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  827. [self reloadDatasource:serverUrl];
  828. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  829. selector = selectorOpenIn;
  830. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  831. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  832. selector = selectorOpenIn;
  833. } else {
  834. _metadata = metadata;
  835. if ([self shouldPerformSegue])
  836. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  837. }
  838. }
  839. // Open with...
  840. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  841. [self reloadDatasource:serverUrl];
  842. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  843. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  844. _docController.delegate = self;
  845. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  846. }
  847. // Save to Photo Album
  848. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  849. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  850. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  851. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  852. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  853. if (image)
  854. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  855. else
  856. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  857. }
  858. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  859. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  860. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  861. } else {
  862. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  863. }
  864. }
  865. if (status != PHAuthorizationStatusAuthorized) {
  866. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  867. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  868. [alertController addAction:okAction];
  869. [self presentViewController:alertController animated:YES completion:nil];
  870. }
  871. [self reloadDatasource:serverUrl];
  872. }
  873. // Copy File
  874. if ([selector isEqualToString:selectorLoadCopy]) {
  875. [self reloadDatasource:serverUrl];
  876. [self copyFileToPasteboard:metadata];
  877. }
  878. //selectorLoadViewImage
  879. if ([selector isEqualToString:selectorLoadViewImage]) {
  880. // Detail
  881. if (appDelegate.activeDetail)
  882. [appDelegate.activeDetail downloadPhotoBrowserSuccessFailure:metadata selector:selector errorCode:0];
  883. // Photos
  884. if (appDelegate.activePhotos)
  885. [appDelegate.activePhotos downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selector errorMessage:errorMessage errorCode:errorCode];
  886. [self reloadDatasource:serverUrl];
  887. }
  888. // Auto Download Upload
  889. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  890. } else {
  891. // File do not exists on server, remove in local
  892. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  893. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:fileID] error:nil];
  894. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID] clearDateReadDirectoryID:nil];
  895. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  896. [[NCManageDatabase sharedInstance] deletePhotosWithFileID:fileID];
  897. [appDelegate.activePhotos.fileIDHide addObject:fileID];
  898. }
  899. if ([selector isEqualToString:selectorLoadViewImage]) {
  900. dispatch_async(dispatch_get_main_queue(), ^{
  901. // Updating Detail
  902. if (appDelegate.activeDetail)
  903. [appDelegate.activeDetail downloadPhotoBrowserSuccessFailure:metadata selector:selector errorCode:errorCode];
  904. // Updating Photos
  905. if (appDelegate.activePhotos)
  906. [appDelegate.activePhotos downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selector errorMessage:errorMessage errorCode:errorCode];
  907. });
  908. } else {
  909. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized && errorCode != k_CCErrorFileAlreadyInDownload)
  910. [appDelegate messageNotification:@"_download_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  911. }
  912. [self reloadDatasource:serverUrl];
  913. }
  914. }
  915. - (void)downloadSelectedFilesFolders
  916. {
  917. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  918. return;
  919. NSLog(@"[LOG] Start download selected ...");
  920. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  921. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  922. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  923. for (tableMetadata *metadata in selectedMetadatas) {
  924. if (metadata.directory) {
  925. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  926. if (serverUrl) {
  927. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  928. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  929. }
  930. } else {
  931. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  932. }
  933. }
  934. [_hud hideHud];
  935. });
  936. [self tableViewSelect:NO];
  937. }
  938. #pragma --------------------------------------------------------------------------------------------
  939. #pragma mark ===== Upload new Photos/Videos =====
  940. #pragma --------------------------------------------------------------------------------------------
  941. - (void)uploadStart:(NSString *)fileID account:(NSString *)account task:(NSURLSessionUploadTask *)task serverUrl:(NSString *)serverUrl
  942. {
  943. [self reloadDatasource:serverUrl];
  944. [appDelegate updateApplicationIconBadgeNumber];
  945. }
  946. - (void)uploadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID assetLocalIdentifier:(NSString *)assetLocalIdentifier serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  947. {
  948. if (errorCode == 0) {
  949. // Auto Download Upload
  950. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  951. } else {
  952. // Activity
  953. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:errorMessage type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
  954. if (errorCode != -999 && errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  955. [appDelegate messageNotification:@"_upload_file_" description:errorMessage visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  956. }
  957. [self reloadDatasource:serverUrl];
  958. }
  959. //
  960. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  961. //
  962. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  963. {
  964. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  965. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  966. // if request create the folder for Photos & the subfolders
  967. if ([autoUploadPath isEqualToString:serverUrl])
  968. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderPhotosWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  969. return;
  970. dispatch_async(dispatch_get_main_queue(), ^{
  971. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  972. });
  973. });
  974. }
  975. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  976. {
  977. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  978. if (!directoryID) return;
  979. for (PHAsset *asset in assets) {
  980. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  981. NSDate *assetDate = asset.creationDate;
  982. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  983. // Create serverUrl if use sub folder
  984. if (useSubFolder) {
  985. [formatter setDateFormat:@"yyyy"];
  986. NSString *yearString = [formatter stringFromDate:assetDate];
  987. [formatter setDateFormat:@"MM"];
  988. NSString *monthString = [formatter stringFromDate:assetDate];
  989. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  990. }
  991. // Check if is in upload
  992. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@ AND session != ''", directoryID, fileName];
  993. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  994. if ([isRecordInSessions count] > 0)
  995. continue;
  996. // Prepare record metadata
  997. tableMetadata *metadataForUpload = [tableMetadata new];
  998. metadataForUpload.account = appDelegate.activeAccount;
  999. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  1000. metadataForUpload.date = [NSDate new];
  1001. metadataForUpload.directoryID = directoryID;
  1002. metadataForUpload.fileID = [directoryID stringByAppendingString:fileName];
  1003. metadataForUpload.fileName = fileName;
  1004. metadataForUpload.fileNameView = fileName;
  1005. metadataForUpload.session = session;
  1006. metadataForUpload.sessionSelector = selectorUploadFile;
  1007. metadataForUpload.status = k_metadataStatusWaitUpload;
  1008. // Check il file already exists
  1009. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView == %@", directoryID, fileName]];
  1010. if (metadata) {
  1011. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1012. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1013. // NO OVERWITE
  1014. }];
  1015. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1016. // Remove record metadata
  1017. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  1018. // Add Medtadata for upload
  1019. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1020. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1021. }];
  1022. [alertController addAction:cancelAction];
  1023. [alertController addAction:overwriteAction];
  1024. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  1025. alertWindow.rootViewController = [[UIViewController alloc]init];
  1026. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  1027. [alertWindow makeKeyAndVisible];
  1028. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  1029. } else {
  1030. // Add Medtadata for upload
  1031. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1032. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1033. }
  1034. }
  1035. }
  1036. #pragma --------------------------------------------------------------------------------------------
  1037. #pragma mark ==== Read File ====
  1038. #pragma --------------------------------------------------------------------------------------------
  1039. - (void)readFileSuccessFailure:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata message:(NSString *)message errorCode:(NSInteger)errorCode
  1040. {
  1041. // Check Active Account
  1042. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1043. return;
  1044. if (errorCode == 0) {
  1045. // Read Folder
  1046. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1047. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadataNet.account, metadataNet.serverUrl]];
  1048. // Change etag, read folder
  1049. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1050. [self readFolder:metadataNet.serverUrl];
  1051. }
  1052. }
  1053. } else {
  1054. // Unauthorized
  1055. if (errorCode == kOCErrorServerUnauthorized)
  1056. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1057. }
  1058. }
  1059. - (void)readFileReloadFolder
  1060. {
  1061. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1062. return;
  1063. // Load Datasource
  1064. [self reloadDatasource];
  1065. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1066. metadataNet.action = actionReadFile;
  1067. metadataNet.priority = NSOperationQueuePriorityHigh;
  1068. metadataNet.selector = selectorReadFileReloadFolder;
  1069. metadataNet.serverUrl = _serverUrl;
  1070. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1071. }
  1072. #pragma --------------------------------------------------------------------------------------------
  1073. #pragma mark ==== Read Folder ====
  1074. #pragma --------------------------------------------------------------------------------------------
  1075. - (void)readFolderSuccessFailure:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1076. {
  1077. // stoprefresh
  1078. [_refreshControl endRefreshing];
  1079. // Check Active Account
  1080. if (![metadataNet.account isEqualToString:metadataNet.account])
  1081. return;
  1082. // ERROR
  1083. if (errorCode != 0) {
  1084. _loadingFolder = NO;
  1085. // Check Active Account
  1086. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1087. return;
  1088. // Unauthorized
  1089. if (errorCode == kOCErrorServerUnauthorized) {
  1090. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1091. } else {
  1092. [self tableViewReloadData];
  1093. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1094. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1095. [self reloadDatasource:metadataNet.serverUrl];
  1096. }
  1097. return;
  1098. }
  1099. // save metadataFolder
  1100. _metadataFolder = metadataFolder;
  1101. // save father e update permission
  1102. if(!_isSearchMode && metadataFolder)
  1103. _fatherPermission = metadataFolder.permissions;
  1104. if (_isSearchMode == NO) {
  1105. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1106. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND (status == %d OR status == %d)", metadataNet.directoryID, k_metadataStatusNormal, k_metadataStatusHide] clearDateReadDirectoryID:metadataNet.directoryID];
  1107. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1108. }
  1109. 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];
  1110. // insert in Database
  1111. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas serverUrl:metadataNet.serverUrl];
  1112. // reinsert metadatas in Download
  1113. if (metadatasInDownload) {
  1114. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload serverUrl:metadataNet.serverUrl];
  1115. }
  1116. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1117. // File is changed ??
  1118. if (!_isSearchMode && metadatasToInsertInDB)
  1119. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  1120. });
  1121. // Search Mode
  1122. if (_isSearchMode) {
  1123. // Fix managed -> Unmanaged _searchResultMetadatas
  1124. if (metadatasToInsertInDB)
  1125. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1126. [self reloadDatasource:metadataNet.serverUrl];
  1127. }
  1128. // this is the same directory
  1129. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1130. // reload
  1131. [self reloadDatasource:metadataNet.serverUrl];
  1132. // Enable change user
  1133. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1134. _loadingFolder = NO;
  1135. [self tableViewReloadData];
  1136. }
  1137. // E2EE Is encrypted folder get metadata
  1138. if (_metadataFolder.e2eEncrypted) {
  1139. // Read Metadata
  1140. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1141. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1142. NSString *metadata;
  1143. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileID:metadataFolder.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1144. dispatch_async(dispatch_get_main_queue(), ^{
  1145. if (error) {
  1146. if (error.code != 404)
  1147. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1148. } else {
  1149. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  1150. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1151. else
  1152. [self reloadDatasource];
  1153. }
  1154. });
  1155. });
  1156. } else {
  1157. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1158. }
  1159. }
  1160. // rewrite title
  1161. [self setTitle];
  1162. }
  1163. - (void)readFolder:(NSString *)serverUrl
  1164. {
  1165. // init control
  1166. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1167. [_refreshControl endRefreshing];
  1168. return;
  1169. }
  1170. // Search Mode
  1171. if (_isSearchMode) {
  1172. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1173. _searchFileName = @""; // forced reload searchg
  1174. [self updateSearchResultsForSearchController:self.searchController];
  1175. return;
  1176. }
  1177. _loadingFolder = YES;
  1178. [self tableViewReloadData];
  1179. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1180. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1181. metadataNet.action = actionReadFolder;
  1182. metadataNet.date = [NSDate date];
  1183. metadataNet.depth = @"1";
  1184. metadataNet.directoryID = directory.directoryID;
  1185. metadataNet.priority = NSOperationQueuePriorityHigh;
  1186. metadataNet.selector = selectorReadFolder;
  1187. metadataNet.serverUrl = serverUrl;
  1188. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1189. }
  1190. #pragma mark -
  1191. #pragma --------------------------------------------------------------------------------------------
  1192. #pragma mark ===== Search =====
  1193. #pragma --------------------------------------------------------------------------------------------
  1194. - (void)searchEnabled:(BOOL)enabled
  1195. {
  1196. if (enabled) {
  1197. if (self.tableView.tableHeaderView != nil)
  1198. return;
  1199. self.definesPresentationContext = YES;
  1200. self.searchController.searchResultsUpdater = self;
  1201. self.searchController.dimsBackgroundDuringPresentation = NO;
  1202. self.searchController.searchBar.translucent = NO;
  1203. [self.searchController.searchBar sizeToFit];
  1204. self.searchController.searchBar.delegate = self;
  1205. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1206. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1207. self.searchController.searchBar.backgroundImage = [UIImage new];
  1208. // color searchbbar button text (cancel)
  1209. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  1210. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  1211. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  1212. }
  1213. self.tableView.tableHeaderView = self.searchController.searchBar;
  1214. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1215. } else {
  1216. self.tableView.tableHeaderView = nil;
  1217. }
  1218. }
  1219. - (void)searchStartTimer
  1220. {
  1221. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1222. [[CCActions sharedInstance] search:startDirectory fileName:_searchFileName etag:@"" depth:@"infinity" date:nil contenType:nil selector:selectorSearchFiles delegate:self];
  1223. _noFilesSearchTitle = @"";
  1224. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1225. [self.tableView reloadEmptyDataSet];
  1226. }
  1227. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1228. {
  1229. // Color text "Cancel"
  1230. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1231. _isSearchMode = YES;
  1232. [self deleteRefreshControl];
  1233. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1234. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1235. _searchFileName = fileName;
  1236. // First : filter
  1237. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1238. if (!directoryID) return;
  1239. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView CONTAINS[cd] %@", directoryID, fileName];
  1240. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1241. [_searchResultMetadatas removeAllObjects];
  1242. for (tableMetadata *record in records)
  1243. [_searchResultMetadatas addObject:record];
  1244. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1245. metadataNet.account = appDelegate.activeAccount;
  1246. metadataNet.directoryID = directoryID;
  1247. metadataNet.selector = selectorSearchFiles;
  1248. metadataNet.serverUrl = _serverUrl;
  1249. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas message:nil errorCode:0];
  1250. // Version >= 12
  1251. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1252. [_timerWaitInput invalidate];
  1253. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1254. }
  1255. }
  1256. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1257. [self reloadDatasource];
  1258. }
  1259. }
  1260. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1261. {
  1262. [self cancelSearchBar];
  1263. [self readFolder:_serverUrl];
  1264. }
  1265. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1266. {
  1267. // Check Active Account
  1268. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1269. return;
  1270. if (errorCode == 0) {
  1271. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1272. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:metadatas message:nil errorCode:0];
  1273. } else {
  1274. // Unauthorized
  1275. if (errorCode == kOCErrorServerUnauthorized)
  1276. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1277. else
  1278. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1279. _searchFileName = @"";
  1280. }
  1281. }
  1282. - (void)cancelSearchBar
  1283. {
  1284. if (self.searchController.active) {
  1285. [self.searchController setActive:NO];
  1286. [self createRefreshControl];
  1287. _isSearchMode = NO;
  1288. _searchFileName = @"";
  1289. _dateReadDataSource = nil;
  1290. _searchResultMetadatas = [NSMutableArray new];
  1291. [self reloadDatasource];
  1292. }
  1293. //[self setNeedsStatusBarAppearanceUpdate];
  1294. }
  1295. #pragma mark -
  1296. #pragma --------------------------------------------------------------------------------------------
  1297. #pragma mark ===== Delete File or Folder =====
  1298. #pragma --------------------------------------------------------------------------------------------
  1299. - (void)deleteFile
  1300. {
  1301. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1302. return;
  1303. NSArray *metadatas;
  1304. if ([_selectedFileIDsMetadatas count] > 0) {
  1305. metadatas = [_selectedFileIDsMetadatas allValues];
  1306. } else {
  1307. metadatas = [[NSArray alloc] initWithObjects:_metadata, nil];
  1308. }
  1309. if (_metadataFolder.e2eEncrypted) {
  1310. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1311. NSError *error = [[NCNetworkingEndToEnd sharedManager] lockEndToEndFolderEncryptedOnServerUrl:self.serverUrl fileID:_metadataFolder.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1312. dispatch_async(dispatch_get_main_queue(), ^{
  1313. if (error == nil) {
  1314. [self deleteFile:metadatas e2ee:_metadataFolder.e2eEncrypted];
  1315. } else {
  1316. [appDelegate messageNotification:@"_delete_" description:error.localizedDescription visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1317. return;
  1318. }
  1319. });
  1320. });
  1321. } else {
  1322. [self deleteFile:metadatas e2ee:_metadataFolder.e2eEncrypted];
  1323. }
  1324. }
  1325. - (void)deleteFile:(NSArray *)metadatas e2ee:(BOOL)e2ee
  1326. {
  1327. NSInteger numDelete = metadatas.count;
  1328. __block NSInteger cont = 0;
  1329. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1330. for (tableMetadata *metadata in metadatas) {
  1331. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1332. if (!serverUrl)
  1333. continue;
  1334. [ocNetworking deleteFileOrFolder:metadata.fileName serverUrl:serverUrl completion:^(NSString *message, NSInteger errorCode) {
  1335. if (errorCode == 0 || errorCode == 404) {
  1336. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  1337. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  1338. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  1339. [[NCManageDatabase sharedInstance] deletePhotosWithFileID:metadata.fileID];
  1340. [[appDelegate activePhotos].fileIDHide addObject:metadata.fileID];
  1341. // Directory ?
  1342. if (metadata.directory) {
  1343. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName]];
  1344. }
  1345. // E2EE (if exists the record)
  1346. if (e2ee) {
  1347. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName]];
  1348. }
  1349. }
  1350. if (++cont == numDelete) {
  1351. if (e2ee) {
  1352. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1353. [[NCNetworkingEndToEnd sharedManager] rebuildAndSendEndToEndMetadataOnServerUrl:serverUrl account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1354. dispatch_async(dispatch_get_main_queue(), ^{
  1355. // ONLY for this View
  1356. // End Select Table View
  1357. [self tableViewSelect:NO];
  1358. [self reloadDatasource:serverUrl];
  1359. });
  1360. });
  1361. } else {
  1362. // ONLY for this View
  1363. // End Select Table View
  1364. [self tableViewSelect:NO];
  1365. // Reload
  1366. if (_isSearchMode)
  1367. [self readFolder:serverUrl];
  1368. else
  1369. [self reloadDatasource:serverUrl];
  1370. }
  1371. }
  1372. }];
  1373. }
  1374. }
  1375. #pragma --------------------------------------------------------------------------------------------
  1376. #pragma mark ===== Rename / Move =====
  1377. #pragma --------------------------------------------------------------------------------------------
  1378. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1379. {
  1380. [self reloadDatasource:metadataNet.serverUrl];
  1381. }
  1382. - (void)renameFile:(NSArray *)arguments
  1383. {
  1384. tableMetadata* metadata = [arguments objectAtIndex:0];
  1385. NSString *fileName = [arguments objectAtIndex:1];
  1386. // E2EE
  1387. if (_metadataFolder.e2eEncrypted) {
  1388. // verify if exists the new fileName
  1389. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1390. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1391. return;
  1392. }
  1393. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1394. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:self.serverUrl fileNameRename:metadata.fileName fileNameNewRename:fileName account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1395. if (error) {
  1396. dispatch_async(dispatch_get_main_queue(), ^{
  1397. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1398. });
  1399. } else {
  1400. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1401. // Move file system
  1402. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  1403. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileName];
  1404. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1405. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileName] error:nil];
  1406. }
  1407. // Unlock
  1408. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1409. if (tableLock != nil) {
  1410. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:self.serverUrl fileID:_metadataFolder.fileID token:tableLock.token user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1411. if (error) {
  1412. dispatch_async(dispatch_get_main_queue(), ^{
  1413. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1414. });
  1415. }
  1416. }
  1417. dispatch_async(dispatch_get_main_queue(), ^{
  1418. [self reloadDatasource];
  1419. });
  1420. });
  1421. } else {
  1422. // Plain
  1423. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1424. }
  1425. }
  1426. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1427. {
  1428. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1429. [_hud hideHud];
  1430. if (message && errorCode != kOCErrorServerUnauthorized)
  1431. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1432. // End Select Table View
  1433. [self tableViewSelect:NO];
  1434. // reload Datasource
  1435. if (_isSearchMode)
  1436. [self readFolder:metadataNet.serverUrl];
  1437. else
  1438. [self reloadDatasource];
  1439. }
  1440. }
  1441. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1442. {
  1443. [_queueSelector removeObject:metadataNet.selector];
  1444. if ([_queueSelector count] == 0) {
  1445. [_hud hideHud];
  1446. NSString *fileName = metadataNet.fileName;
  1447. NSString *directoryID = metadataNet.directoryID;
  1448. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1449. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1450. if (!serverUrlTo) return;
  1451. // FILE -> Metadata
  1452. if (metadataNet.directory == NO)
  1453. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1454. // DIRECTORY -> Directory - CCMetadata
  1455. if (metadataNet.directory == YES) {
  1456. // delete all dir / subdir
  1457. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1458. // move metadata
  1459. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1460. // Add new directory
  1461. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1462. (void) [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:false favorite:false fileID:nil permissions:nil serverUrl:newDirectory];
  1463. }
  1464. // next
  1465. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1466. if ([_selectedFileIDsMetadatas count] > 0) {
  1467. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1468. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1469. } else {
  1470. // End Select Table View
  1471. [self tableViewSelect:NO];
  1472. // reload Datasource
  1473. if (_isSearchMode)
  1474. [self readFolder:metadataNet.serverUrl];
  1475. else
  1476. [self reloadDatasource];
  1477. }
  1478. }
  1479. }
  1480. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1481. {
  1482. tableMetadata *metadata = [arguments objectAtIndex:0];
  1483. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1484. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1485. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1486. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1487. if (!serverUrl) return;
  1488. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1489. if (!directoryIDTo) return;
  1490. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1491. [ocNetworking readFile:metadata.fileName serverUrl:serverUrlTo account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1492. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1493. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1494. }];
  1495. [alert addAction:ok];
  1496. [self presentViewController:alert animated:YES completion:nil];
  1497. // End Select Table View
  1498. [self tableViewSelect:NO];
  1499. // reload Datasource
  1500. [self readFileReloadFolder];
  1501. } failure:^(NSString *message, NSInteger errorCode) {
  1502. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1503. metadataNet.action = actionMoveFileOrFolder;
  1504. metadataNet.directory = metadata.directory;
  1505. metadataNet.fileID = metadata.fileID;
  1506. metadataNet.directoryID = metadata.directoryID;
  1507. metadataNet.directoryIDTo = directoryIDTo;
  1508. metadataNet.fileName = metadata.fileName;
  1509. metadataNet.fileNameView = metadata.fileNameView;
  1510. metadataNet.fileNameTo = metadata.fileName;
  1511. metadataNet.etag = metadata.etag;
  1512. metadataNet.selector = selectorMove;
  1513. metadataNet.serverUrl = serverUrl;
  1514. metadataNet.serverUrlTo = serverUrlTo;
  1515. [_queueSelector addObject:metadataNet.selector];
  1516. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1517. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1518. }];
  1519. }
  1520. // DELEGATE : Move
  1521. - (void)dismissMove
  1522. {
  1523. [self reloadDatasource];
  1524. }
  1525. // DELEGATE : Move
  1526. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1527. {
  1528. [_queueSelector removeAllObjects];
  1529. // E2EE DENIED
  1530. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1531. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1532. return;
  1533. }
  1534. if ([_selectedFileIDsMetadatas count] > 0) {
  1535. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1536. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1537. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1538. } else {
  1539. _numSelectedFileIDsMetadatas = 1;
  1540. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1541. }
  1542. }
  1543. - (void)moveOpenWindow:(NSArray *)indexPaths
  1544. {
  1545. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1546. return;
  1547. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1548. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1549. viewController.delegate = self;
  1550. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1551. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1552. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1553. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1554. viewController.networkingOperationQueue = appDelegate.netQueue;
  1555. // E2EE
  1556. viewController.includeDirectoryE2EEncryption = NO;
  1557. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1558. [self presentViewController:navigationController animated:YES completion:nil];
  1559. }
  1560. #pragma --------------------------------------------------------------------------------------------
  1561. #pragma mark ===== Create folder =====
  1562. #pragma --------------------------------------------------------------------------------------------
  1563. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1564. {
  1565. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1566. if (![fileNameFolder length]) return;
  1567. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1568. if (!directoryID) return;
  1569. NSString *fileIDTemp = [[NSUUID UUID] UUIDString];
  1570. // Create Directory (temp) on metadata
  1571. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:fileIDTemp directoryID:directoryID fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal];
  1572. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1573. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1574. [self reloadDatasource];
  1575. // Creeate folder Networking
  1576. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1577. [ocNetworking createFolder:fileNameFolder serverUrl:serverUrl account:appDelegate.activeAccount success:^(NSString *fileID, NSDate *date) {
  1578. // Delete Temp Dir
  1579. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1580. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1581. if (_metadataFolder.e2eEncrypted) {
  1582. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1583. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory fileID:fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1584. dispatch_async(dispatch_get_main_queue(), ^{
  1585. if (error) {
  1586. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1587. }
  1588. [self readFolder:self.serverUrl];
  1589. });
  1590. });
  1591. } else {
  1592. [self readFolder:self.serverUrl];
  1593. }
  1594. } failure:^(NSString *message, NSInteger errorCode) {
  1595. // Unauthorized
  1596. if (errorCode == kOCErrorServerUnauthorized)
  1597. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1598. else
  1599. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1600. // Delete Temp Dir
  1601. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1602. [self reloadDatasource];
  1603. // We are in directory fail ?
  1604. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:fileNameFolder]];
  1605. if (vc)
  1606. [vc.navigationController popViewControllerAnimated:YES];
  1607. }];
  1608. }
  1609. #pragma --------------------------------------------------------------------------------------------
  1610. #pragma mark ===== Progress & Task Button =====
  1611. #pragma --------------------------------------------------------------------------------------------
  1612. - (void)triggerProgressTask:(NSNotification *)notification
  1613. {
  1614. NSDictionary *dict = notification.userInfo;
  1615. NSString *fileID = [dict valueForKey:@"fileID"];
  1616. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1617. long status = [[dict valueForKey:@"status"] longValue];
  1618. NSString *statusString = @"";
  1619. float progress = [[dict valueForKey:@"progress"] floatValue];
  1620. long long totalBytes = [[dict valueForKey:@"totalBytes"] longLongValue];
  1621. long long totalBytesExpected = [[dict valueForKey:@"totalBytesExpected"] longLongValue];
  1622. // Check
  1623. if (!fileID || [fileID isEqualToString: @""])
  1624. return;
  1625. [appDelegate.listProgressMetadata setObject:[NSArray arrayWithObjects:[NSNumber numberWithFloat:progress], [dict valueForKey:@"totalBytes"], [dict valueForKey:@"totalBytesExpected"], nil] forKey:fileID];
  1626. if (![serverUrl isEqualToString:_serverUrl])
  1627. return;
  1628. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1629. if ([self indexPathIsValid:indexPath]) {
  1630. CCCellMainTransfer *cell = (CCCellMainTransfer *)[self.tableView cellForRowAtIndexPath:indexPath];
  1631. if (status == k_metadataStatusInDownload) {
  1632. statusString = @"↓";
  1633. } else if (status == k_metadataStatusInUpload) {
  1634. statusString = @"↑";
  1635. }
  1636. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ - %@%@", [CCUtility transformedSize:totalBytesExpected], statusString, [CCUtility transformedSize:totalBytes]];
  1637. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1638. cell.transferButton.progress = progress;
  1639. }
  1640. }
  1641. }
  1642. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1643. {
  1644. UITouch *touch = [[event allTouches] anyObject];
  1645. CGPoint location = [touch locationInView:self.tableView];
  1646. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1647. if ([self indexPathIsValid:indexPath]) {
  1648. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1649. if (metadataSection) {
  1650. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1651. if (metadata)
  1652. [self cancelTaskButton:metadata reloadTable:YES];
  1653. }
  1654. }
  1655. }
  1656. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1657. {
  1658. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1659. __block NSURLSessionTask *findTask;
  1660. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1661. NSString *fileID = metadata.fileID;
  1662. // SESSION EXTENSION
  1663. if ([metadata.session isEqualToString:k_download_session_extension] || [metadata.session isEqualToString:k_upload_session_extension]) {
  1664. if ([metadata.session isEqualToString:k_upload_session_extension]) {
  1665. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:fileID] error:nil];
  1666. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID] clearDateReadDirectoryID:nil];
  1667. } else {
  1668. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  1669. }
  1670. [self reloadDatasource];
  1671. return;
  1672. }
  1673. // DOWNLOAD
  1674. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1675. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1676. for (NSURLSessionTask *task in downloadTasks)
  1677. if (task.taskIdentifier == sessionTaskIdentifier) {
  1678. findTask = task;
  1679. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1680. [task cancel];
  1681. }
  1682. if (!findTask) {
  1683. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1684. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1685. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1686. }
  1687. }];
  1688. }
  1689. // UPLOAD
  1690. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1691. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1692. for (NSURLSessionUploadTask *task in uploadTasks)
  1693. if (task.taskIdentifier == sessionTaskIdentifier) {
  1694. findTask = task;
  1695. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1696. [task cancel];
  1697. }
  1698. if (!findTask) {
  1699. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1700. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1701. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1702. }
  1703. }];
  1704. }
  1705. }
  1706. - (void)cancelAllTask:(id)sender
  1707. {
  1708. CGPoint location = [sender locationInView:self.tableView];
  1709. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1710. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1711. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1712. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  1713. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError] clearDateReadDirectoryID:nil];
  1714. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND status != %d AND status != %d", appDelegate.activeAccount, k_metadataStatusNormal, k_metadataStatusHide] sorted:@"fileName" ascending:true];
  1715. for (tableMetadata *metadata in metadatas) {
  1716. // Modify
  1717. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  1718. metadata.session = @"";
  1719. metadata.sessionSelector = @"";
  1720. metadata.status = k_metadataStatusNormal;
  1721. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1722. }
  1723. // Cancel Task
  1724. if (metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading) {
  1725. [self cancelTaskButton:metadata reloadTable:NO];
  1726. }
  1727. }
  1728. [self reloadDatasource];
  1729. }]];
  1730. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1731. alertController.popoverPresentationController.sourceView = self.view;
  1732. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1733. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1734. [alertController.view layoutIfNeeded];
  1735. [self presentViewController:alertController animated:YES completion:nil];
  1736. }
  1737. #pragma --------------------------------------------------------------------------------------------
  1738. #pragma mark ===== Shared =====
  1739. #pragma --------------------------------------------------------------------------------------------
  1740. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1741. {
  1742. [_hud hideHud];
  1743. // Check Active Account
  1744. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1745. return;
  1746. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1747. if (result) {
  1748. appDelegate.sharesLink = result[0];
  1749. appDelegate.sharesUserAndGroup = result[1];
  1750. }
  1751. // Notify Shares View
  1752. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1753. if (openWindow) {
  1754. if (_shareOC) {
  1755. [_shareOC reloadData];
  1756. } else {
  1757. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1758. // Apriamo la view
  1759. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1760. _shareOC.delegate = self;
  1761. _shareOC.metadata = metadata;
  1762. _shareOC.serverUrl = metadataNet.serverUrl;
  1763. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1764. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1765. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1766. [self presentViewController:_shareOC animated:YES completion:nil];
  1767. }
  1768. }
  1769. [self tableViewReloadData];
  1770. }
  1771. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1772. {
  1773. [_hud hideHud];
  1774. // Check Active Account
  1775. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1776. return;
  1777. // Unauthorized
  1778. if (errorCode == kOCErrorServerUnauthorized)
  1779. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1780. else
  1781. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1782. if (_shareOC)
  1783. [_shareOC reloadData];
  1784. [self tableViewReloadData];
  1785. }
  1786. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1787. {
  1788. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1789. metadataNet.action = actionShare;
  1790. metadataNet.fileID = metadata.fileID;
  1791. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1792. metadataNet.fileNameView = metadata.fileNameView;
  1793. metadataNet.password = password;
  1794. metadataNet.selector = selectorShare;
  1795. metadataNet.serverUrl = serverUrl;
  1796. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1797. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1798. }
  1799. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1800. {
  1801. [_hud hideHud];
  1802. // Check Active Account
  1803. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1804. return;
  1805. // rimuoviamo la condivisione da db
  1806. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1807. if (result) {
  1808. appDelegate.sharesLink = result[0];
  1809. appDelegate.sharesUserAndGroup = result[1];
  1810. }
  1811. if (_shareOC)
  1812. [_shareOC reloadData];
  1813. [self tableViewReloadData];
  1814. }
  1815. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1816. {
  1817. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1818. metadataNet.action = actionUnShare;
  1819. metadataNet.fileID = metadata.fileID;
  1820. metadataNet.fileName = metadata.fileName;
  1821. metadataNet.fileNameView = metadata.fileNameView;
  1822. metadataNet.selector = selectorUnshare;
  1823. metadataNet.serverUrl = serverUrl;
  1824. metadataNet.share = share;
  1825. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1826. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1827. }
  1828. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1829. {
  1830. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1831. metadataNet.action = actionUpdateShare;
  1832. metadataNet.fileID = metadata.fileID;
  1833. metadataNet.expirationTime = expirationTime;
  1834. metadataNet.password = password;
  1835. metadataNet.selector = selectorUpdateShare;
  1836. metadataNet.serverUrl = serverUrl;
  1837. metadataNet.share = share;
  1838. metadataNet.sharePermission = permission;
  1839. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1840. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1841. }
  1842. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1843. {
  1844. [_hud hideHud];
  1845. // Check Active Account
  1846. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1847. return;
  1848. if (_shareOC)
  1849. [_shareOC reloadUserAndGroup:items];
  1850. }
  1851. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1852. {
  1853. [_hud hideHud];
  1854. // Check Active Account
  1855. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1856. return;
  1857. // Unauthorized
  1858. if (errorCode == kOCErrorServerUnauthorized)
  1859. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1860. else
  1861. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1862. }
  1863. - (void)getUserAndGroup:(NSString *)find
  1864. {
  1865. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1866. metadataNet.action = actionGetUserAndGroup;
  1867. metadataNet.optionAny = find;
  1868. metadataNet.selector = selectorGetUserAndGroup;
  1869. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1870. [_hud visibleIndeterminateHud];
  1871. }
  1872. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1873. {
  1874. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1875. metadataNet.action = actionShareWith;
  1876. metadataNet.fileID = metadata.fileID;
  1877. metadataNet.directoryID = directoryID;
  1878. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1879. metadataNet.fileNameView = metadata.fileNameView;
  1880. metadataNet.serverUrl = serverUrl;
  1881. metadataNet.selector = selectorShare;
  1882. metadataNet.share = user;
  1883. metadataNet.shareeType = shareeType;
  1884. metadataNet.sharePermission = permission;
  1885. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1886. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1887. }
  1888. - (void)openWindowShare:(tableMetadata *)metadata
  1889. {
  1890. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1891. if (!serverUrl) return;
  1892. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1893. metadataNet.action = actionReadShareServer;
  1894. metadataNet.fileID = metadata.fileID;
  1895. metadataNet.fileName = metadata.fileName;
  1896. metadataNet.fileNameView = metadata.fileNameView;
  1897. metadataNet.selector = selectorOpenWindowShare;
  1898. metadataNet.serverUrl = serverUrl;
  1899. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1900. [_hud visibleIndeterminateHud];
  1901. }
  1902. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1903. {
  1904. CGPoint location = [tapGesture locationInView:self.tableView];
  1905. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1906. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1907. if (metadata)
  1908. [self openWindowShare:metadata];
  1909. }
  1910. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1911. {
  1912. CGPoint location = [tapGesture locationInView:self.tableView];
  1913. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1914. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1915. if (metadata) {
  1916. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1917. vc.metadata = metadata;
  1918. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1919. [self presentViewController:vc animated:YES completion:nil];
  1920. }
  1921. }
  1922. #pragma --------------------------------------------------------------------------------------------
  1923. #pragma mark ===== Favorite =====
  1924. #pragma --------------------------------------------------------------------------------------------
  1925. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1926. {
  1927. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1928. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1929. [ocNetworking settingFavorite:fileNameServerUrl favorite:favorite completion:^(NSString *message, NSInteger errorCode) {
  1930. if (errorCode == 0) {
  1931. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  1932. _dateReadDataSource = nil;
  1933. if (_isSearchMode)
  1934. [self readFolder:self.serverUrl];
  1935. else
  1936. [self reloadDatasource:self.serverUrl];
  1937. if (metadata.directory && favorite) {
  1938. NSString *dir = [CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName];
  1939. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1940. }
  1941. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1942. metadata.favorite = favorite;
  1943. metadata.session = k_download_session;
  1944. metadata.sessionError = @"";
  1945. metadata.sessionSelector = selectorDownloadSynchronize;
  1946. metadata.status = k_metadataStatusWaitDownload;
  1947. // Add Metadata for Download
  1948. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1949. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1950. }
  1951. } else {
  1952. if (errorCode == kOCErrorServerUnauthorized)
  1953. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1954. }
  1955. }];
  1956. }
  1957. #pragma --------------------------------------------------------------------------------------------
  1958. #pragma mark ===== Open in... =====
  1959. #pragma --------------------------------------------------------------------------------------------
  1960. - (void)openIn:(tableMetadata *)metadata
  1961. {
  1962. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1963. if (!serverUrl) return;
  1964. metadata.session = k_download_session;
  1965. metadata.sessionError = @"";
  1966. metadata.sessionSelector = selectorOpenIn;
  1967. metadata.status = k_metadataStatusWaitDownload;
  1968. // Add Metadata for Download
  1969. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1970. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1971. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1972. if ([self indexPathIsValid:indexPath])
  1973. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  1974. }
  1975. #pragma --------------------------------------------------------------------------------------------
  1976. #pragma mark ===== Remove Local File =====
  1977. #pragma --------------------------------------------------------------------------------------------
  1978. - (void)removeLocalFile:(tableMetadata *)metadata
  1979. {
  1980. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  1981. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  1982. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1983. if (serverUrl)
  1984. [self reloadDatasource:serverUrl];
  1985. }
  1986. #pragma --------------------------------------------------------------------------------------------
  1987. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  1988. #pragma --------------------------------------------------------------------------------------------
  1989. - (void)orderTable:(NSString *)order
  1990. {
  1991. [CCUtility setOrderSettings:order];
  1992. // Clear data-read of DataSource
  1993. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1994. }
  1995. - (void)ascendingTable:(BOOL)ascending
  1996. {
  1997. [CCUtility setAscendingSettings:ascending];
  1998. // Clear data-read of DataSource
  1999. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2000. }
  2001. - (void)directoryOnTop:(BOOL)directoryOnTop
  2002. {
  2003. [CCUtility setDirectoryOnTop:directoryOnTop];
  2004. // Clear data-read of DataSource
  2005. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2006. }
  2007. - (void)tableGroupBy:(NSString *)groupBy
  2008. {
  2009. [CCUtility setGroupBySettings:groupBy];
  2010. // Clear data-read of DataSource
  2011. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2012. }
  2013. #pragma --------------------------------------------------------------------------------------------
  2014. #pragma mark ==== Menu LOGO ====
  2015. #pragma --------------------------------------------------------------------------------------------
  2016. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2017. {
  2018. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2019. return;
  2020. // Brand
  2021. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2022. return;
  2023. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2024. NSMutableArray *menuArray = [NSMutableArray new];
  2025. for (NSString *account in listAccount) {
  2026. CCMenuItem *item = [[CCMenuItem alloc] init];
  2027. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2028. item.argument = account;
  2029. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  2030. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-avatar.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url]];
  2031. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  2032. if (avatar) {
  2033. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  2034. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  2035. CGSize imageSize = avatarImageView.bounds.size;
  2036. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  2037. CGContextRef context = UIGraphicsGetCurrentContext();
  2038. [avatarImageView.layer renderInContext:context];
  2039. avatar = UIGraphicsGetImageFromCurrentImageContext();
  2040. UIGraphicsEndImageContext();
  2041. } else {
  2042. avatar = [UIImage imageNamed:@"menuLogoUser"];
  2043. }
  2044. item.image = avatar;
  2045. item.target = self;
  2046. if ([account isEqualToString:appDelegate.activeAccount]) {
  2047. item.action = nil;
  2048. [menuArray insertObject:item atIndex:0];
  2049. } else {
  2050. item.action = @selector(changeDefaultAccount:);
  2051. [menuArray addObject:item];
  2052. }
  2053. }
  2054. // Add + new account
  2055. CCMenuItem *item = [[CCMenuItem alloc] init];
  2056. item.title = NSLocalizedString(@"_add_account_", nil);
  2057. item.argument = @"";
  2058. item.image = [UIImage imageNamed:@"add"];
  2059. item.target = self;
  2060. item.action = @selector(addNewAccount:);
  2061. [menuArray addObject:item];
  2062. OptionalConfiguration options;
  2063. Color textColor, backgroundColor;
  2064. textColor.R = 0;
  2065. textColor.G = 0;
  2066. textColor.B = 0;
  2067. backgroundColor.R = 1;
  2068. backgroundColor.G = 1;
  2069. backgroundColor.B = 1;
  2070. options.arrowSize = 9;
  2071. options.marginXSpacing = 7;
  2072. options.marginYSpacing = 10;
  2073. options.intervalSpacing = 20;
  2074. options.menuCornerRadius = 6.5;
  2075. options.maskToBackground = NO;
  2076. options.shadowOfMenu = YES;
  2077. options.hasSeperatorLine = YES;
  2078. options.seperatorLineHasInsets = YES;
  2079. options.textColor = textColor;
  2080. options.menuBackgroundColor = backgroundColor;
  2081. CGRect rect = self.view.frame;
  2082. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2083. CGFloat safeAreaTop = 0;
  2084. CGFloat offsetY = 35;
  2085. if (@available(iOS 11, *)) {
  2086. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2087. }
  2088. rect.origin.y = locationY + safeAreaTop + offsetY;
  2089. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2090. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2091. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2092. }
  2093. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2094. {
  2095. 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];
  2096. if (transferInprogress > 0) {
  2097. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2098. return;
  2099. }
  2100. [appDelegate.netQueue cancelAllOperations];
  2101. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2102. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2103. if (tableAccount) {
  2104. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2105. // go to home sweet home
  2106. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2107. }
  2108. });
  2109. }
  2110. - (void)addNewAccount:(CCMenuItem *)sender
  2111. {
  2112. 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];
  2113. if (transferInprogress > 0) {
  2114. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2115. return;
  2116. }
  2117. [appDelegate.netQueue cancelAllOperations];
  2118. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2119. [appDelegate openLoginView:self loginType:k_login_Add selector:k_intro_login];
  2120. });
  2121. }
  2122. #pragma --------------------------------------------------------------------------------------------
  2123. #pragma mark ==== ReMenu ====
  2124. #pragma --------------------------------------------------------------------------------------------
  2125. - (void)createReMenuBackgroundView:(REMenu *)menu
  2126. {
  2127. CGFloat safeAreaBottom = 0;
  2128. CGFloat safeAreaTop = 0;
  2129. CGFloat statusBar = 0;
  2130. if (@available(iOS 11, *)) {
  2131. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2132. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2133. }
  2134. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2135. statusBar = 13;
  2136. }
  2137. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2138. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2139. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2140. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2141. [UIView animateWithDuration:0.2 animations:^{
  2142. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2143. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2144. if (y>minimum) {
  2145. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2146. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2147. }
  2148. }];
  2149. }
  2150. - (void)createReMainMenu
  2151. {
  2152. NSString *ordinamento;
  2153. NSString *groupBy = _directoryGroupBy;
  2154. __block NSString *nuovoOrdinamento;
  2155. NSString *titoloNuovo, *titoloAttuale;
  2156. BOOL ascendente;
  2157. __block BOOL nuovoAscendente;
  2158. UIImage *image;
  2159. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2160. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"select"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2161. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2162. [self tableViewSelect:YES];
  2163. }
  2164. }];
  2165. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2166. ordinamento = _directoryOrder;
  2167. if ([ordinamento isEqualToString:@"fileName"]) {
  2168. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  2169. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2170. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2171. nuovoOrdinamento = @"date";
  2172. }
  2173. if ([ordinamento isEqualToString:@"date"]) {
  2174. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  2175. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2176. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2177. nuovoOrdinamento = @"fileName";
  2178. }
  2179. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2180. [self orderTable:nuovoOrdinamento];
  2181. }];
  2182. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2183. ascendente = [CCUtility getAscendingSettings];
  2184. if (ascendente) {
  2185. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  2186. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2187. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2188. nuovoAscendente = false;
  2189. }
  2190. if (!ascendente) {
  2191. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  2192. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2193. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2194. nuovoAscendente = true;
  2195. }
  2196. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2197. [self ascendingTable:nuovoAscendente];
  2198. }];
  2199. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2200. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2201. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2202. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2203. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2204. else [self tableGroupBy:@"alphabetic"];
  2205. }];
  2206. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2207. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2208. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2209. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2210. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2211. else [self tableGroupBy:@"typefile"];
  2212. }];
  2213. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2214. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2215. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2216. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2217. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2218. else [self tableGroupBy:@"date"];
  2219. }];
  2220. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2221. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2222. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2223. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2224. if ([CCUtility getDirectoryOnTop])
  2225. [self directoryOnTop:NO];
  2226. else
  2227. [self directoryOnTop:YES];
  2228. }];
  2229. // REMENU --------------------------------------------------------------------------------------------------------------
  2230. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2231. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2232. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2233. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2234. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2235. appDelegate.reMainMenu.separatorHeight = 0.5;
  2236. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2237. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2238. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2239. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2240. appDelegate.reMainMenu.textShadowColor = nil;
  2241. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2242. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2243. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2244. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2245. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2246. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2247. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2248. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2249. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2250. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2251. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2252. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2253. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2254. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2255. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2256. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2257. appDelegate.reMainMenu.borderWidth = 0.3;
  2258. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2259. appDelegate.reMainMenu.animationDuration = 0.2;
  2260. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2261. appDelegate.reMainMenu.bounce = NO;
  2262. __weak typeof(self) weakSelf = self;
  2263. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2264. // Backgroun reMenu (Gesture)
  2265. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2266. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2267. }];
  2268. }
  2269. - (void)toggleReMainMenu
  2270. {
  2271. if (appDelegate.reMainMenu.isOpen) {
  2272. [appDelegate.reMainMenu close];
  2273. } else {
  2274. [self createReMainMenu];
  2275. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2276. // Backgroun reMenu & (Gesture)
  2277. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2278. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2279. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2280. }
  2281. }
  2282. - (void)createReSelectMenu
  2283. {
  2284. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  2285. appDelegate.selectAllItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_all_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"selectAll"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2286. [self didSelectAll];
  2287. }];
  2288. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  2289. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2290. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2291. }];
  2292. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2293. appDelegate.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2294. [self downloadSelectedFilesFolders];
  2295. }];
  2296. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2297. appDelegate.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2298. [self saveSelectedFiles];
  2299. }];
  2300. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2301. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2302. [self deleteFile];
  2303. }];
  2304. // E2EE
  2305. if (_metadataFolder.e2eEncrypted) {
  2306. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2307. } else {
  2308. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2309. }
  2310. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2311. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2312. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2313. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2314. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2315. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2316. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2317. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2318. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2319. appDelegate.reSelectMenu.textShadowColor = nil;
  2320. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2321. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2322. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2323. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2324. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2325. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2326. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2327. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2328. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2329. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2330. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2331. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2332. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2333. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2334. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2335. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2336. appDelegate.reSelectMenu.borderWidth = 0.3;
  2337. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2338. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2339. appDelegate.reSelectMenu.animationDuration = 0.2;
  2340. appDelegate.reSelectMenu.bounce = NO;
  2341. __weak typeof(self) weakSelf = self;
  2342. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2343. // Backgroun reMenu (Gesture)
  2344. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2345. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2346. }];
  2347. }
  2348. - (void)toggleReSelectMenu
  2349. {
  2350. if (appDelegate.reSelectMenu.isOpen) {
  2351. [appDelegate.reSelectMenu close];
  2352. } else {
  2353. [self createReSelectMenu];
  2354. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2355. // Backgroun reMenu & (Gesture)
  2356. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2357. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2358. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2359. }
  2360. }
  2361. #pragma --------------------------------------------------------------------------------------------
  2362. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2363. #pragma --------------------------------------------------------------------------------------------
  2364. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2365. {
  2366. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2367. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2368. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2369. if ([self indexPathIsValid:indexPath])
  2370. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2371. else
  2372. _metadata = nil;
  2373. [self becomeFirstResponder];
  2374. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2375. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2376. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2377. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2378. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2379. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2380. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2381. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2382. [menuController setMenuVisible:YES animated:YES];
  2383. }
  2384. }
  2385. - (BOOL)canBecomeFirstResponder
  2386. {
  2387. return YES;
  2388. }
  2389. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2390. {
  2391. // For copy file, copy files, Open in ... :
  2392. //
  2393. // NO Directory
  2394. // NO Error Passcode
  2395. // NO In Session mode (download/upload)
  2396. // NO Template
  2397. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2398. if (_isSelectedMode == NO && _metadata && !_metadata.directory && _metadata.status == k_metadataStatusNormal) return YES;
  2399. else return NO;
  2400. }
  2401. if (@selector(copyFiles:) == action) {
  2402. if (_isSelectedMode) {
  2403. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2404. for (tableMetadata *metadata in selectedMetadatas) {
  2405. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2406. return YES;
  2407. }
  2408. }
  2409. return NO;
  2410. }
  2411. if (@selector(pasteFile:) == action) {
  2412. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2413. NSArray *items = [pasteboard items];
  2414. if ([items count] == 1) {
  2415. // Value : (NSData) fileID
  2416. NSDictionary *dic = [items objectAtIndex:0];
  2417. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2418. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2419. if (fileID) {
  2420. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2421. if (metadata) {
  2422. return [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView];
  2423. } else {
  2424. return NO;
  2425. }
  2426. }
  2427. }
  2428. return NO;
  2429. }
  2430. if (@selector(pasteFiles:) == action) {
  2431. BOOL isValid = NO;
  2432. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2433. NSArray *items = [pasteboard items];
  2434. if ([items count] <= 1) return NO;
  2435. for (NSDictionary *dic in items) {
  2436. // Value : (NSData) fileID
  2437. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2438. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2439. if (fileID) {
  2440. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2441. if (metadata) {
  2442. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  2443. isValid = YES;
  2444. } else {
  2445. isValid = NO;
  2446. break;
  2447. }
  2448. } else {
  2449. isValid = NO;
  2450. break;
  2451. }
  2452. } else {
  2453. isValid = NO;
  2454. break;
  2455. }
  2456. }
  2457. return isValid;
  2458. }
  2459. return NO;
  2460. }
  2461. /************************************ COPY ************************************/
  2462. - (void)copyFile:(id)sender
  2463. {
  2464. // Remove all item
  2465. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2466. pasteboard.items = [[NSArray alloc] init];
  2467. if ([CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  2468. [self copyFileToPasteboard:_metadata];
  2469. } else {
  2470. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2471. if (serverUrl) {
  2472. _metadata.session = k_download_session;
  2473. _metadata.sessionError = @"";
  2474. _metadata.sessionSelector = selectorLoadCopy;
  2475. _metadata.status = k_metadataStatusWaitDownload;
  2476. // Add Metadata for Download
  2477. (void)[[NCManageDatabase sharedInstance] addMetadata:_metadata];
  2478. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2479. }
  2480. }
  2481. }
  2482. - (void)copyFiles:(id)sender
  2483. {
  2484. // Remove all item
  2485. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2486. pasteboard.items = [[NSArray alloc] init];
  2487. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2488. for (tableMetadata *metadata in selectedMetadatas) {
  2489. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  2490. [self copyFileToPasteboard:metadata];
  2491. } else {
  2492. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2493. if (serverUrl) {
  2494. metadata.session = k_download_session;
  2495. metadata.sessionError = @"";
  2496. metadata.sessionSelector = selectorLoadCopy;
  2497. metadata.status = k_metadataStatusWaitDownload;
  2498. // Add Metadata for Download
  2499. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2500. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2501. }
  2502. }
  2503. }
  2504. [self tableViewSelect:NO];
  2505. }
  2506. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2507. {
  2508. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2509. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2510. // Value : (NSData) fileID
  2511. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2512. [items addObject:item];
  2513. [pasteboard setItems:items];
  2514. }
  2515. /************************************ OPEN IN ... ******************************/
  2516. - (void)openinFile:(id)sender
  2517. {
  2518. [self openIn:_metadata];
  2519. }
  2520. /************************************ PASTE ************************************/
  2521. - (void)pasteFile:(id)sender
  2522. {
  2523. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2524. [self uploadFilePasteArray:[pasteboard items]];
  2525. }
  2526. - (void)pasteFiles:(id)sender
  2527. {
  2528. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2529. [self uploadFilePasteArray:[pasteboard items]];
  2530. }
  2531. - (void)uploadFilePasteArray:(NSArray *)items
  2532. {
  2533. for (NSDictionary *dic in items) {
  2534. // Value : (NSData) fileID
  2535. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2536. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2537. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl];
  2538. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2539. if (metadata) {
  2540. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  2541. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView directoryID:directoryID];
  2542. NSString *fileID = [directoryID stringByAppendingString:fileName];
  2543. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileName:fileName]];
  2544. tableMetadata *metadataForUpload = [tableMetadata new];
  2545. metadataForUpload.account = appDelegate.activeAccount;
  2546. metadataForUpload.date = [NSDate new];
  2547. metadataForUpload.directoryID = directoryID;
  2548. metadataForUpload.fileID = fileID;
  2549. metadataForUpload.fileName = fileName;
  2550. metadataForUpload.fileNameView = fileName;
  2551. metadataForUpload.session = k_upload_session;
  2552. metadataForUpload.sessionSelector = selectorUploadFile;
  2553. metadataForUpload.status = k_metadataStatusWaitUpload;
  2554. // Add Medtadata for upload
  2555. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2556. }
  2557. }
  2558. }
  2559. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2560. [self reloadDatasource];
  2561. }
  2562. #pragma --------------------------------------------------------------------------------------------
  2563. #pragma mark ===== Lock Passcode =====
  2564. #pragma --------------------------------------------------------------------------------------------
  2565. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2566. {
  2567. return _failedAttempts;
  2568. }
  2569. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2570. {
  2571. return _lockUntilDate;
  2572. }
  2573. - (void)passcodeViewCloseButtonPressed:(id)sender
  2574. {
  2575. [self dismissViewControllerAnimated:YES completion:nil];
  2576. }
  2577. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2578. {
  2579. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2580. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2581. _lockUntilDate = nil;
  2582. _failedAttempts = 0;
  2583. aResultHandler(YES);
  2584. } else aResultHandler(NO);
  2585. } else aResultHandler(YES);
  2586. }
  2587. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2588. {
  2589. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2590. switch (aViewController.type) {
  2591. case BKPasscodeViewControllerCheckPasscodeType: {
  2592. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2593. // possiamo procedere alla prossima directory
  2594. [self performSegueDirectoryWithControlPasscode:false];
  2595. // avviamo la sessione Passcode Lock con now
  2596. appDelegate.sessionePasscodeLock = [NSDate date];
  2597. }
  2598. // disattivazione lock cartella
  2599. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2600. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2601. if (!serverUrl)
  2602. return;
  2603. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2604. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2605. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2606. }
  2607. [self tableViewReloadData];
  2608. }
  2609. }
  2610. break;
  2611. default:
  2612. break;
  2613. }
  2614. }
  2615. - (void)comandoLockPassword
  2616. {
  2617. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2618. if (!serverUrl) return;
  2619. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2620. // se non è abilitato il Lock Passcode esci
  2621. if ([[CCUtility getBlockCode] length] == 0) {
  2622. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2623. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2624. [alertController addAction:okAction];
  2625. [self presentViewController:alertController animated:YES completion:nil];
  2626. return;
  2627. }
  2628. // se è richiesta la disattivazione si chiede la password
  2629. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2630. if (directory.lock) {
  2631. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2632. viewController.delegate = self;
  2633. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2634. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2635. viewController.inputViewTitlePassword = YES;
  2636. if ([CCUtility getSimplyBlockCode]) {
  2637. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2638. viewController.passcodeInputView.maximumLength = 6;
  2639. } else {
  2640. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2641. viewController.passcodeInputView.maximumLength = 64;
  2642. }
  2643. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2644. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2645. viewController.touchIDManager = touchIDManager;
  2646. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2647. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2648. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2649. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2650. [self presentViewController:navigationController animated:YES completion:nil];
  2651. return;
  2652. }
  2653. // ---------------- ACTIVATE PASSWORD
  2654. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2655. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2656. if ([self indexPathIsValid:indexPath])
  2657. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2658. } else {
  2659. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2660. }
  2661. }
  2662. #pragma mark -
  2663. #pragma --------------------------------------------------------------------------------------------
  2664. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2665. #pragma --------------------------------------------------------------------------------------------
  2666. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2667. {
  2668. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2669. return NO;
  2670. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2671. return NO;
  2672. // E2EE
  2673. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2674. return NO;
  2675. return YES;
  2676. }
  2677. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2678. {
  2679. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2680. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2681. return [self canOpenMenuAction:metadata];
  2682. }
  2683. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2684. {
  2685. }
  2686. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2687. {
  2688. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2689. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2690. if (direction == MGSwipeDirectionRightToLeft) {
  2691. [self actionDelete:indexPath];
  2692. }
  2693. if (direction == MGSwipeDirectionLeftToRight) {
  2694. if (_metadata.favorite)
  2695. [self settingFavorite:_metadata favorite:NO];
  2696. else
  2697. [self settingFavorite:_metadata favorite:YES];
  2698. }
  2699. return YES;
  2700. }
  2701. - (void)actionDelete:(NSIndexPath *)indexPath
  2702. {
  2703. // Directory locked ?
  2704. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2705. if (!lockServerUrl) return;
  2706. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2707. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", _metadata.fileID]];
  2708. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2709. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2710. return;
  2711. }
  2712. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2713. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2714. [self performSelector:@selector(deleteFile) withObject:nil];
  2715. }]];
  2716. if (localFile || [CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  2717. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2718. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  2719. }]];
  2720. }
  2721. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2722. [alertController dismissViewControllerAnimated:YES completion:nil];
  2723. }]];
  2724. alertController.popoverPresentationController.sourceView = self.view;
  2725. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2726. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2727. [alertController.view layoutIfNeeded];
  2728. [self presentViewController:alertController animated:YES completion:nil];
  2729. }
  2730. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2731. {
  2732. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2733. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2734. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2735. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2736. if (!serverUrl) return;
  2737. NSString *titoloLock, *titleFavorite;
  2738. if (_metadata.favorite) {
  2739. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2740. } else {
  2741. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2742. }
  2743. if (_metadata.directory) {
  2744. // calcolo lockServerUrl
  2745. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2746. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2747. if (directory.lock)
  2748. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2749. else
  2750. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2751. }
  2752. // ******************************************* AHKActionSheet *******************************************
  2753. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2754. actionSheet.animationDuration = 0.2;
  2755. actionSheet.buttonHeight = 50.0;
  2756. actionSheet.cancelButtonHeight = 50.0f;
  2757. actionSheet.separatorHeight = 5.0f;
  2758. actionSheet.automaticallyTintButtonImages = @(NO);
  2759. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2760. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2761. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2762. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2763. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2764. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2765. // ******************************************* DIRECTORY *******************************************
  2766. if (_metadata.directory) {
  2767. BOOL lockDirectory = NO;
  2768. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2769. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2770. // Directory bloccata ?
  2771. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2772. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2773. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2774. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2775. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2776. height:50.0
  2777. type:AHKActionSheetButtonTypeDisabled
  2778. handler:nil
  2779. ];
  2780. [actionSheet addButtonWithTitle: titleFavorite
  2781. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2782. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2783. height: 50.0
  2784. type: AHKActionSheetButtonTypeDefault
  2785. handler: ^(AHKActionSheet *as) {
  2786. if (_metadata.favorite) [self settingFavorite:_metadata favorite:NO];
  2787. else [self settingFavorite:_metadata favorite:YES];
  2788. }];
  2789. if (!lockDirectory && !isFolderEncrypted) {
  2790. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2791. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2792. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2793. height:50.0
  2794. type:AHKActionSheetButtonTypeDefault
  2795. handler:^(AHKActionSheet *as) {
  2796. [self openWindowShare:_metadata];
  2797. }];
  2798. }
  2799. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2800. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2801. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2802. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2803. height:50.0
  2804. type:AHKActionSheetButtonTypeDefault
  2805. handler:^(AHKActionSheet *as) {
  2806. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2807. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2808. textField.text = _metadata.fileNameView;
  2809. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2810. //textField.delegate = self;
  2811. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2812. }];
  2813. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2814. NSLog(@"[LOG] Cancel action");
  2815. }];
  2816. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2817. UITextField *fileName = alertController.textFields.firstObject;
  2818. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2819. }];
  2820. okAction.enabled = NO;
  2821. [alertController addAction:cancelAction];
  2822. [alertController addAction:okAction];
  2823. [self presentViewController:alertController animated:YES completion:nil];
  2824. }];
  2825. }
  2826. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2827. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2828. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2829. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2830. height:50.0
  2831. type:AHKActionSheetButtonTypeDefault
  2832. handler:^(AHKActionSheet *as) {
  2833. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2834. }];
  2835. }
  2836. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2837. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2838. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2839. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2840. height:50.0
  2841. type:AHKActionSheetButtonTypeDefault
  2842. handler:^(AHKActionSheet *as) {
  2843. // Settings new folder Automatatic upload
  2844. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2845. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2846. // Clear data (old) Auto Upload
  2847. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2848. [self readFolder:serverUrl];
  2849. }];
  2850. }
  2851. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2852. [actionSheet addButtonWithTitle:titoloLock
  2853. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2854. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2855. height:50.0
  2856. type:AHKActionSheetButtonTypeDefault
  2857. handler:^(AHKActionSheet *as) {
  2858. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2859. }];
  2860. }
  2861. if (!_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2862. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2863. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  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_HIGH, 0), ^{
  2869. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] fileID:_metadata.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2870. dispatch_async(dispatch_get_main_queue(), ^{
  2871. if (error) {
  2872. [appDelegate messageNotification:@"_e2e_error_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. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2882. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2883. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2884. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2885. height:50.0
  2886. type:AHKActionSheetButtonTypeDefault
  2887. handler:^(AHKActionSheet *as) {
  2888. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2889. NSError *error = [[NCNetworkingEndToEnd sharedManager] deletemarkEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] fileID:_metadata.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2890. dispatch_async(dispatch_get_main_queue(), ^{
  2891. if (error) {
  2892. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2893. } else {
  2894. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  2895. [self readFolder:self.serverUrl];
  2896. }
  2897. });
  2898. });
  2899. }];
  2900. }
  2901. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2902. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2903. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2904. height:50.0
  2905. type:AHKActionSheetButtonTypeDestructive
  2906. handler:^(AHKActionSheet *as) {
  2907. [self actionDelete:indexPath];
  2908. }];
  2909. [actionSheet show];
  2910. }
  2911. // ******************************************* FILE *******************************************
  2912. if (!_metadata.directory) {
  2913. UIImage *iconHeader;
  2914. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2915. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:_metadata.fileID fileNameView:_metadata.fileNameView]])
  2916. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:_metadata.fileID fileNameView:_metadata.fileNameView]];
  2917. else
  2918. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2919. [actionSheet addButtonWithTitle: _metadata.fileNameView
  2920. image: iconHeader
  2921. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2922. height: 50.0
  2923. type: AHKActionSheetButtonTypeDisabled
  2924. handler: nil
  2925. ];
  2926. [actionSheet addButtonWithTitle: titleFavorite
  2927. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2928. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2929. height: 50.0
  2930. type: AHKActionSheetButtonTypeDefault
  2931. handler: ^(AHKActionSheet *as) {
  2932. if (_metadata.favorite) [self settingFavorite:_metadata favorite:NO];
  2933. else [self settingFavorite:_metadata favorite:YES];
  2934. }];
  2935. if (!_metadataFolder.e2eEncrypted) {
  2936. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2937. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2938. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2939. height: 50.0
  2940. type:AHKActionSheetButtonTypeDefault
  2941. handler:^(AHKActionSheet *as) {
  2942. [self openWindowShare:_metadata];
  2943. }];
  2944. }
  2945. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2946. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2947. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2948. height: 50.0
  2949. type:AHKActionSheetButtonTypeDefault
  2950. handler:^(AHKActionSheet *as) {
  2951. [self performSelector:@selector(openIn:) withObject:_metadata];
  2952. }];
  2953. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2954. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2955. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2956. height: 50.0
  2957. type:AHKActionSheetButtonTypeDefault
  2958. handler:^(AHKActionSheet *as) {
  2959. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2960. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2961. textField.text = _metadata.fileNameView;
  2962. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2963. }];
  2964. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2965. NSLog(@"[LOG] Cancel action");
  2966. }];
  2967. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2968. UITextField *fileName = alertController.textFields.firstObject;
  2969. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2970. }];
  2971. okAction.enabled = NO;
  2972. [alertController addAction:cancelAction];
  2973. [alertController addAction:okAction];
  2974. [self presentViewController:alertController animated:YES completion:nil];
  2975. }];
  2976. if (!_metadataFolder.e2eEncrypted) {
  2977. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2978. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2979. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2980. height:50.0
  2981. type:AHKActionSheetButtonTypeDefault
  2982. handler:^(AHKActionSheet *as) {
  2983. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2984. }];
  2985. }
  2986. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2987. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2988. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2989. height:50.0
  2990. type:AHKActionSheetButtonTypeDestructive
  2991. handler:^(AHKActionSheet *as) {
  2992. [self actionDelete:indexPath];
  2993. }];
  2994. [actionSheet show];
  2995. }
  2996. }
  2997. #pragma --------------------------------------------------------------------------------------------
  2998. #pragma mark - ==== Datasource ====
  2999. #pragma --------------------------------------------------------------------------------------------
  3000. - (void)clearDateReadDataSource:(NSNotification *)notification
  3001. {
  3002. _dateReadDataSource = Nil;
  3003. [self reloadDatasource];
  3004. }
  3005. - (void)reloadDatasource
  3006. {
  3007. [self reloadDatasource:_serverUrl];
  3008. }
  3009. - (void)reloadDatasource:(NSString *)serverUrl
  3010. {
  3011. // test
  3012. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3013. return;
  3014. // Search Mode
  3015. if (_isSearchMode) {
  3016. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy fileIDHide:nil activeAccount:appDelegate.activeAccount];
  3017. [self tableViewReloadData];
  3018. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3019. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3020. _noFilesSearchDescription = @"";
  3021. }
  3022. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3023. _noFilesSearchTitle = @"";
  3024. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3025. }
  3026. [self.tableView reloadEmptyDataSet];
  3027. return;
  3028. }
  3029. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3030. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3031. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3032. if (main) {
  3033. [main reloadDatasource];
  3034. } else {
  3035. [self tableViewReloadData];
  3036. [appDelegate.activeTransfers reloadDatasource];
  3037. }
  3038. return;
  3039. }
  3040. [appDelegate.activeTransfers reloadDatasource];
  3041. // Settaggio variabili per le ottimizzazioni
  3042. _directoryGroupBy = [CCUtility getGroupBySettings];
  3043. _directoryOrder = [CCUtility getOrderSettings];
  3044. // Remove optimization for encrypted directory
  3045. if (_metadataFolder.e2eEncrypted)
  3046. _dateReadDataSource = nil;
  3047. // current directoryID
  3048. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3049. // Controllo data lettura Data Source
  3050. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  3051. // Get MetadataFolder
  3052. if (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  3053. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  3054. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3055. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3056. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3057. _dateReadDataSource = [NSDate date];
  3058. // Data Source
  3059. NSString *sorted = _directoryOrder;
  3060. if ([sorted isEqualToString:@"fileName"])
  3061. sorted = @"fileName";
  3062. if (directoryID) {
  3063. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND status != %i", directoryID, k_metadataStatusHide] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3064. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3065. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy fileIDHide:nil activeAccount:appDelegate.activeAccount];
  3066. // get auto upload folder
  3067. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3068. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3069. }
  3070. } else {
  3071. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3072. }
  3073. [self tableViewReloadData];
  3074. }
  3075. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3076. {
  3077. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3078. if (selectedRows.count > 0) {
  3079. for (NSIndexPath *selectionIndex in selectedRows) {
  3080. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3081. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3082. [metadatas addObject:metadata];
  3083. }
  3084. }
  3085. return metadatas;
  3086. }
  3087. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3088. {
  3089. NSInteger section = indexPath.section + 1;
  3090. NSInteger row = indexPath.row + 1;
  3091. NSInteger totSections = [_sectionDataSource.sections count] ;
  3092. if ((totSections < section) || (section > totSections)) {
  3093. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3094. return nil;
  3095. }
  3096. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3097. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3098. if (fileIDs) {
  3099. NSInteger totRows =[fileIDs count] ;
  3100. if ((totRows < row) || (row > totRows)) {
  3101. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3102. return nil;
  3103. }
  3104. } else {
  3105. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3106. return nil;
  3107. }
  3108. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3109. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3110. return metadata;
  3111. }
  3112. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3113. {
  3114. NSInteger totSections =[_sectionDataSource.sections count] ;
  3115. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3116. return nil;
  3117. }
  3118. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3119. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3120. }
  3121. #pragma --------------------------------------------------------------------------------------------
  3122. #pragma mark - ==== Table ====
  3123. #pragma --------------------------------------------------------------------------------------------
  3124. - (void)tableViewSelect:(BOOL)edit
  3125. {
  3126. // chiudiamo eventuali swipe aperti
  3127. if (edit)
  3128. [self.tableView setEditing:NO animated:NO];
  3129. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3130. [self.tableView setEditing:edit animated:YES];
  3131. _isSelectedMode = edit;
  3132. if (edit)
  3133. [self setUINavigationBarSelected];
  3134. else
  3135. [self setUINavigationBarDefault];
  3136. [_selectedFileIDsMetadatas removeAllObjects];
  3137. [self setTitle];
  3138. }
  3139. - (void)tableViewReloadData
  3140. {
  3141. // store selected cells before relod
  3142. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3143. // reload table view
  3144. [self.tableView reloadData];
  3145. // selected cells stored
  3146. for (NSIndexPath *path in indexPaths)
  3147. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3148. [self setTableViewFooter];
  3149. if (self.tableView.editing)
  3150. [self setTitle];
  3151. }
  3152. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3153. {
  3154. if (tableView.editing == 1) {
  3155. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3156. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3157. return NO;
  3158. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  3159. return NO;
  3160. else
  3161. return YES;
  3162. } else {
  3163. [_selectedFileIDsMetadatas removeAllObjects];
  3164. }
  3165. return YES;
  3166. }
  3167. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3168. {
  3169. return 60;
  3170. }
  3171. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3172. {
  3173. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3174. }
  3175. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3176. {
  3177. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3178. }
  3179. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3180. {
  3181. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3182. NSString *sectionTitle = [sections objectAtIndex:section];
  3183. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3184. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3185. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3186. return 20.f;
  3187. }
  3188. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3189. {
  3190. float shift;
  3191. UIVisualEffectView *visualEffectView;
  3192. NSString *titleSection;
  3193. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3194. return nil;
  3195. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3196. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3197. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3198. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3199. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3200. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3201. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3202. else titleSection = NSLocalizedString(titleSection,nil);
  3203. // Format title
  3204. NSString *currentDevice = [CCUtility currentDevice];
  3205. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3206. visualEffectView = [[UIVisualEffectView alloc] init];
  3207. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3208. } else {
  3209. UIVisualEffect *blurEffect;
  3210. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3211. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3212. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3213. }
  3214. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3215. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3216. shift = - 35;
  3217. else
  3218. shift = - 20;
  3219. } else shift = - 10;
  3220. // Title
  3221. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3222. titleLabel.backgroundColor = [UIColor clearColor];
  3223. titleLabel.textColor = [UIColor blackColor];
  3224. titleLabel.font = [UIFont systemFontOfSize:12];
  3225. titleLabel.textAlignment = NSTextAlignmentLeft;
  3226. titleLabel.text = titleSection;
  3227. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3228. [visualEffectView.contentView addSubview:titleLabel];
  3229. // Elements
  3230. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3231. elementLabel.backgroundColor = [UIColor clearColor];
  3232. elementLabel.textColor = [UIColor blackColor];;
  3233. elementLabel.font = [UIFont systemFontOfSize:12];
  3234. elementLabel.textAlignment = NSTextAlignmentRight;
  3235. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3236. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3237. NSUInteger rowsCount = [metadatas count];
  3238. if (rowsCount == 0) return nil;
  3239. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3240. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3241. [visualEffectView.contentView addSubview:elementLabel];
  3242. return visualEffectView;
  3243. }
  3244. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3245. {
  3246. return [_sectionDataSource.sections indexOfObject:title];
  3247. }
  3248. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3249. {
  3250. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3251. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3252. else
  3253. return nil;
  3254. }
  3255. /*
  3256. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3257. {
  3258. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3259. }
  3260. }
  3261. */
  3262. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3263. {
  3264. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3265. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3266. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3267. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3268. if (serverUrl == nil) {
  3269. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3270. }
  3271. // Create File System
  3272. if (metadata.directory) {
  3273. [CCUtility getDirectoryProviderStorageFileID:metadata.fileID];
  3274. } else {
  3275. [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  3276. }
  3277. // CCCell
  3278. if (metadata.status == k_metadataStatusNormal) {
  3279. // NORMAL
  3280. CCCellMain *cell = (CCCellMain *)[tableView dequeueReusableCellWithIdentifier:@"CellMain" forIndexPath:indexPath];
  3281. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3282. cell.accessoryType = UITableViewCellAccessoryNone;
  3283. cell.file.image = nil;
  3284. cell.status.image = nil;
  3285. cell.favorite.image = nil;
  3286. cell.shared.image = nil;
  3287. cell.local.image = nil;
  3288. cell.imageTitleSegue = nil;
  3289. cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3290. // change color selection
  3291. UIView *selectionColor = [UIView new];
  3292. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3293. cell.selectedBackgroundView = selectionColor;
  3294. cell.tintColor = [NCBrandColor sharedInstance].brandElement;
  3295. cell.delegate = self;
  3296. cell.labelTitle.textColor = [UIColor blackColor];
  3297. cell.labelTitle.text = metadata.fileNameView;
  3298. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3299. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3300. BOOL isShare = [metadata.permissions containsString:k_permission_shared] && ![_fatherPermission containsString:k_permission_shared];
  3301. BOOL isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_fatherPermission containsString:k_permission_mounted];
  3302. if (metadata.directory) {
  3303. // lable Info
  3304. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3305. // File Image & Image Title Segue
  3306. if (metadata.e2eEncrypted) {
  3307. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3308. cell.imageTitleSegue = [UIImage imageNamed:@"lock"];
  3309. } else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory]) {
  3310. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderPhotos"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3311. cell.imageTitleSegue = [UIImage imageNamed:@"photos"];
  3312. } else if (isShare) {
  3313. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3314. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3315. } else if (isMounted) {
  3316. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3317. cell.imageTitleSegue = [UIImage imageNamed:@"shareMounted"];
  3318. } else if (shareUserAndGroup != nil) {
  3319. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3320. cell.imageTitleSegue = [UIImage imageNamed:@"share"];
  3321. } else if (shareLink != nil) {
  3322. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3323. cell.imageTitleSegue = [UIImage imageNamed:@"sharebylink"];
  3324. } else
  3325. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  3326. // Image Status Lock Passcode
  3327. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3328. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3329. if ((directory.lock && [[CCUtility getBlockCode] length])) {
  3330. cell.status.image = [UIImage imageNamed:@"passcode"];
  3331. }
  3332. } else {
  3333. BOOL iconFileExists = [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3334. // Lable Info
  3335. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", [CCUtility dateDiff:metadata.date], [CCUtility transformedSize:metadata.size]];
  3336. // File Image
  3337. if (iconFileExists) {
  3338. cell.file.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3339. } else {
  3340. if (metadata.iconName.length > 0) {
  3341. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3342. } else {
  3343. cell.file.image = [UIImage imageNamed:@"file"];
  3344. }
  3345. }
  3346. // Local Image
  3347. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  3348. if (localFile && [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  3349. cell.local.image = [UIImage imageNamed:@"local"];
  3350. } else {
  3351. cell.local.image = nil;
  3352. }
  3353. // Download thumbnail
  3354. if (metadata.thumbnailExists && !iconFileExists && !_metadataFolder.e2eEncrypted) {
  3355. [self downloadThumbnail:metadata serverUrl:serverUrl indexPath:indexPath];
  3356. }
  3357. // Status Image
  3358. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName]];
  3359. if (tableE2eEncryption && [[NCUtility sharedInstance] isEncryptedMetadata:metadata]) {
  3360. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3361. }
  3362. // Share
  3363. if (isShare) {
  3364. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  3365. } else if (isMounted) {
  3366. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  3367. } else if (shareLink != nil) {
  3368. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sharebylink"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  3369. } else if (shareUserAndGroup != nil) {
  3370. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  3371. }
  3372. }
  3373. //
  3374. // File & Directory
  3375. //
  3376. // Favorite
  3377. if (metadata.favorite) {
  3378. cell.favorite.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite];
  3379. }
  3380. // Share add Tap
  3381. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  3382. if (isShare || isMounted) { // Shared with you
  3383. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3384. [tap setNumberOfTapsRequired:1];
  3385. cell.shared.userInteractionEnabled = YES;
  3386. [cell.shared addGestureRecognizer:tap];
  3387. } else if (shareLink != nil || shareUserAndGroup != nil) { // You share
  3388. if (metadata.directory) {
  3389. cell.shared.userInteractionEnabled = NO;
  3390. } else {
  3391. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3392. [tap setNumberOfTapsRequired:1];
  3393. cell.shared.userInteractionEnabled = YES;
  3394. [cell.shared addGestureRecognizer:tap];
  3395. }
  3396. }
  3397. } else {
  3398. cell.shared.userInteractionEnabled = NO;
  3399. }
  3400. // More Image
  3401. cell.more.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"more"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  3402. if ([self canOpenMenuAction:metadata]) {
  3403. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3404. [tapMore setNumberOfTapsRequired:1];
  3405. cell.more.userInteractionEnabled = YES;
  3406. [cell.more addGestureRecognizer:tapMore];
  3407. }
  3408. // MGSwipeButton
  3409. // LEFT
  3410. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3411. cell.leftExpansion.buttonIndex = 0;
  3412. cell.leftExpansion.fillOnTrigger = NO;
  3413. //centerIconOverText
  3414. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3415. [favoriteButton centerIconOverText];
  3416. // RIGHT
  3417. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3418. cell.rightExpansion.buttonIndex = 0;
  3419. cell.rightExpansion.fillOnTrigger = NO;
  3420. //centerIconOverText
  3421. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3422. [deleteButton centerIconOverText];
  3423. return cell;
  3424. } else {
  3425. // TRASNFER
  3426. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer" forIndexPath:indexPath];
  3427. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3428. cell.accessoryType = UITableViewCellAccessoryNone;
  3429. cell.file.image = nil;
  3430. cell.status.image = nil;
  3431. cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3432. cell.labelTitle.textColor = [UIColor blackColor];
  3433. cell.labelTitle.text = metadata.fileNameView;
  3434. cell.transferButton.tintColor = [NCBrandColor sharedInstance].icon;
  3435. float progress = 0;
  3436. long long totalBytes = 0, totalBytesExpected = 0;
  3437. NSArray *progressArray = [appDelegate.listProgressMetadata objectForKey:metadata.fileID];
  3438. if (progressArray != nil && progressArray.count == 3) {
  3439. progress = [[progressArray objectAtIndex:0] floatValue];
  3440. totalBytes = [[progressArray objectAtIndex:1] longLongValue];
  3441. totalBytesExpected = [[progressArray objectAtIndex:2] longLongValue];
  3442. }
  3443. // Write status on Label Info
  3444. NSString *statusString = @"";
  3445. switch (metadata.status) {
  3446. case 2:
  3447. statusString = NSLocalizedString(@"_status_wait_download_",nil);
  3448. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", [CCUtility transformedSize:metadata.size], statusString];
  3449. break;
  3450. case 3:
  3451. statusString = NSLocalizedString(@"_status_in_download_",nil);
  3452. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", [CCUtility transformedSize:metadata.size], statusString];
  3453. break;
  3454. case 4:
  3455. if (totalBytes > 0) {
  3456. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ - %@%@", [CCUtility transformedSize:totalBytesExpected], statusString, [CCUtility transformedSize:totalBytes]];
  3457. } else {
  3458. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", [CCUtility transformedSize:metadata.size]];
  3459. }
  3460. break;
  3461. case 6:
  3462. statusString = NSLocalizedString(@"_status_wait_upload_",nil);
  3463. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", statusString];
  3464. break;
  3465. case 7:
  3466. statusString = NSLocalizedString(@"_status_in_upload_",nil);
  3467. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", statusString];
  3468. break;
  3469. case 8:
  3470. if (totalBytes > 0) {
  3471. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ - %@%@", [CCUtility transformedSize:totalBytesExpected], statusString, [CCUtility transformedSize:totalBytes]];
  3472. } else {
  3473. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", [CCUtility transformedSize:metadata.size]];
  3474. }
  3475. break;
  3476. default:
  3477. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", [CCUtility transformedSize:metadata.size]];
  3478. break;
  3479. }
  3480. BOOL iconFileExists = [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3481. if (iconFileExists) {
  3482. cell.file.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  3483. } else {
  3484. if (metadata.iconName.length > 0) {
  3485. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3486. } else {
  3487. cell.file.image = [UIImage imageNamed:@"file"];
  3488. }
  3489. }
  3490. // Session Upload Extension
  3491. if ([metadata.session isEqualToString:k_upload_session_extension] && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading)) {
  3492. cell.labelTitle.enabled = NO;
  3493. cell.labelInfoFile.enabled = NO;
  3494. } else {
  3495. cell.labelTitle.enabled = YES;
  3496. cell.labelInfoFile.enabled = YES;
  3497. }
  3498. // downloadFile
  3499. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError) {
  3500. //
  3501. }
  3502. // downloadFile Error
  3503. if (metadata.status == k_metadataStatusDownloadError) {
  3504. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3505. if ([metadata.sessionError length] == 0) {
  3506. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3507. } else {
  3508. cell.labelInfoFile.text = metadata.sessionError;
  3509. }
  3510. }
  3511. // uploadFile
  3512. if (metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError) {
  3513. if (!iconFileExists) {
  3514. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploadCloud"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  3515. }
  3516. cell.labelTitle.enabled = NO;
  3517. }
  3518. // uploadFileError
  3519. if (metadata.status == k_metadataStatusUploadError) {
  3520. cell.labelTitle.enabled = NO;
  3521. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3522. if (!iconFileExists) {
  3523. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploadCloud"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  3524. }
  3525. if ([metadata.sessionError length] == 0) {
  3526. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3527. } else {
  3528. cell.labelInfoFile.text = metadata.sessionError;
  3529. }
  3530. }
  3531. // Progress
  3532. cell.transferButton.progress = progress;
  3533. // gesture Transfer
  3534. [cell.transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3535. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  3536. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3537. [cell.transferButton.stopButton addGestureRecognizer:stopLongGesture];
  3538. return cell;
  3539. }
  3540. }
  3541. - (void)setTableViewFooter
  3542. {
  3543. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3544. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3545. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3546. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3547. UIFont *appFont = [UIFont systemFontOfSize:12];
  3548. footerLabel.font = appFont;
  3549. footerLabel.textColor = [UIColor grayColor];
  3550. footerLabel.backgroundColor = [UIColor clearColor];
  3551. footerLabel.textAlignment = NSTextAlignmentCenter;
  3552. NSString *folders;
  3553. NSString *files;
  3554. NSString *footerText;
  3555. if (_sectionDataSource.directories > 1) {
  3556. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3557. } else if (_sectionDataSource.directories == 1){
  3558. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3559. } else {
  3560. folders = @"";
  3561. }
  3562. if (_sectionDataSource.files > 1) {
  3563. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3564. } else if (_sectionDataSource.files == 1){
  3565. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3566. } else {
  3567. files = @"";
  3568. }
  3569. if ([folders isEqualToString:@""]) {
  3570. footerText = files;
  3571. } else if ([files isEqualToString:@""]) {
  3572. footerText = folders;
  3573. } else {
  3574. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3575. }
  3576. footerLabel.text = footerText;
  3577. [footerView addSubview:footerLabel];
  3578. [self.tableView setTableFooterView:footerView];
  3579. }
  3580. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3581. {
  3582. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3583. // settiamo il record file.
  3584. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3585. if (!_metadata)
  3586. return;
  3587. // se non può essere selezionata deseleziona
  3588. if ([cell isEditing] == NO)
  3589. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3590. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3591. if (self.tableView.editing) {
  3592. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3593. [self setTitle];
  3594. return;
  3595. }
  3596. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3597. if (!serverUrl) return;
  3598. // se è in corso una sessione
  3599. if (_metadata.status != k_metadataStatusNormal)
  3600. return;
  3601. // file
  3602. if (_metadata.directory == NO) {
  3603. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3604. if ([CCUtility fileProviderStorageExists:_metadata.fileID fileName:_metadata.fileNameView]) {
  3605. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3606. } else {
  3607. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3608. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3609. } else {
  3610. _metadata.session = k_download_session;
  3611. _metadata.sessionError = @"";
  3612. _metadata.sessionSelector = selectorLoadFileView;
  3613. _metadata.status = k_metadataStatusWaitDownload;
  3614. // Add Metadata for Download
  3615. (void)[[NCManageDatabase sharedInstance] addMetadata:_metadata];
  3616. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3617. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3618. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3619. }
  3620. }
  3621. }
  3622. if (_metadata.directory) {
  3623. imageTitleSegue = cell.imageTitleSegue;
  3624. [self performSegueDirectoryWithControlPasscode:true];
  3625. }
  3626. }
  3627. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3628. {
  3629. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3630. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3631. [self setTitle];
  3632. }
  3633. - (void)didSelectAll
  3634. {
  3635. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3636. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3637. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3638. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3639. [_selectedFileIDsMetadatas setObject:metadata forKey:metadata.fileID];
  3640. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3641. }
  3642. }
  3643. [self setTitle];
  3644. }
  3645. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3646. {
  3647. if (!indexPath)
  3648. return NO;
  3649. NSInteger section = indexPath.section;
  3650. NSInteger row = indexPath.row;
  3651. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3652. if (section > lastSectionIndex || lastSectionIndex < 0)
  3653. return NO;
  3654. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3655. if (rowCount < 0)
  3656. return NO;
  3657. return row <= rowCount;
  3658. }
  3659. #pragma --------------------------------------------------------------------------------------------
  3660. #pragma mark ===== Navigation ====
  3661. #pragma --------------------------------------------------------------------------------------------
  3662. - (BOOL)shouldPerformSegue
  3663. {
  3664. // if background return
  3665. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3666. if (self.view.window == NO)
  3667. return NO;
  3668. // Collapsed ma siamo già in detail esci
  3669. if (self.splitViewController.isCollapsed)
  3670. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3671. return YES;
  3672. }
  3673. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3674. {
  3675. id viewController = segue.destinationViewController;
  3676. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3677. tableMetadata *metadata;
  3678. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3679. UINavigationController *nav = viewController;
  3680. _detailViewController = (CCDetail *)nav.topViewController;
  3681. } else {
  3682. _detailViewController = segue.destinationViewController;
  3683. }
  3684. if ([sender isKindOfClass:[tableMetadata class]]) {
  3685. metadata = sender;
  3686. [allRecordsDataSourceImagesVideos addObject:sender];
  3687. } else {
  3688. metadata = _metadata;
  3689. for (NSString *fileID in _sectionDataSource.allFileID) {
  3690. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3691. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3692. [allRecordsDataSourceImagesVideos addObject:metadata];
  3693. }
  3694. }
  3695. _detailViewController.metadataDetail = metadata;
  3696. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3697. _detailViewController.dateFilterQuery = nil;
  3698. [_detailViewController setTitle:metadata.fileNameView];
  3699. }
  3700. // can i go to next viewcontroller
  3701. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3702. {
  3703. NSString *nomeDir;
  3704. if (self.tableView.editing == NO) {
  3705. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3706. if (!serverUrl) return;
  3707. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3708. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3709. // 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
  3710. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3711. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3712. viewController.delegate = self;
  3713. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3714. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3715. viewController.inputViewTitlePassword = YES;
  3716. if ([CCUtility getSimplyBlockCode]) {
  3717. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3718. viewController.passcodeInputView.maximumLength = 6;
  3719. } else {
  3720. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3721. viewController.passcodeInputView.maximumLength = 64;
  3722. }
  3723. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3724. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3725. viewController.touchIDManager = touchIDManager;
  3726. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3727. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3728. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3729. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3730. [self presentViewController:navController animated:YES completion:nil];
  3731. return;
  3732. }
  3733. // E2EE Check enable
  3734. if (_metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3735. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3736. return;
  3737. }
  3738. nomeDir = _metadata.fileName;
  3739. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3740. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3741. if (!viewController) {
  3742. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3743. viewController.serverUrl = serverUrlPush;
  3744. viewController.titleMain = _metadata.fileName;
  3745. viewController.textBackButton = _titleMain;
  3746. viewController.imageTitle = imageTitleSegue;
  3747. // save self
  3748. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3749. [self.navigationController pushViewController:viewController animated:YES];
  3750. } else {
  3751. if (viewController.isViewLoaded) {
  3752. // Icon Title
  3753. viewController.imageTitle = imageTitleSegue;
  3754. // Fix : Application tried to present modally an active controller
  3755. if ([self.navigationController isBeingPresented]) {
  3756. // being presented
  3757. } else if ([self.navigationController isMovingToParentViewController]) {
  3758. // being pushed
  3759. } else {
  3760. [self.navigationController pushViewController:viewController animated:YES];
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. @end