CCMain.m 235 KB

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