CCMain.m 232 KB

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