CCMain.m 254 KB

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