CCMain.m 232 KB

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