CCMain.m 230 KB

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