CCMain.m 252 KB

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