CCMain.m 256 KB

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