CCMain.m 252 KB

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