CCMain.m 227 KB

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