CCMain.m 254 KB

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