CCMain.m 229 KB

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