CCMain.m 227 KB

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