CCMain.m 253 KB

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