CCMain.m 231 KB

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