CCMain.m 255 KB

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