CCMain.m 222 KB

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