CCMain.m 221 KB

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