CCMain.m 225 KB

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