CCMain.m 253 KB

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