diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 65c5ca8..0000000 --- a/LICENSE +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/LICENÇA.txt b/LICENÇA.txt new file mode 100644 index 0000000..57efb42 --- /dev/null +++ b/LICENÇA.txt @@ -0,0 +1,80 @@ +LICENÇA CC BY 3.0 BR + +A OBRA (CONFORME DEFINIDA ABAIXO) É DISPONIBILIZADA DE ACORDO COM OS TERMOS DESTA LICENÇA PÚBLICA +CREATIVE COMMONS ("CCPL" OU "LICENÇA"). A OBRA É PROTEGIDA POR DIREITO AUTORAL E/OU OUTRAS LEIS +APLICÁVEIS. QUALQUER USO DA OBRA QUE NÃO O AUTORIZADO SOB ESTA LICENÇA OU PELA LEGISLAÇÃO AUTORAL +É PROIBIDO. + +AO EXERCER QUAISQUER DOS DIREITOS À OBRA AQUI CONCEDIDOS, VOCÊ ACEITA E CONCORDA FICAR OBRIGADO +NOS TERMOS DESTA LICENÇA. O LICENCIANTE CONCEDE A VOCÊ OS DIREITOS AQUI CONTIDOS EM CONTRAPARTIDA +A SUA ACEITAÇÃO DESTES TERMOS E CONDIÇÕES. + +1. Definições + +"Obra Derivada" significa uma Obra baseada na Obra ou na Obra e outras Obras pré-existentes, +tal qual uma tradução, adaptação, arranjo musical ou outras alterações de uma Obra literária, +artística ou científica, ou fonograma ou performance, incluindo adaptações cinematográficas ou +qualquer outra forma na qual a Obra possa ser refeita, transformada ou adaptada, abrangendo +qualquer forma reconhecível como derivada da original, com exceção da Obra que constitua uma +Obra Coletiva, a qual não será considerada uma Obra Derivada para os propósitos desta Licença. +Para evitar dúvidas, quando a Obra for uma Obra musical, performance ou fonograma, a sincronização +da Obra em relação cronometrada com uma imagem em movimento (“synching”) será considerada uma +Obra Derivada para os propósitos desta Licença. + +"Obra Coletiva" significa uma coleção de Obras literárias, artísticas ou científicas, tais quais +enciclopédias e antologias, ou performances, fonogramas ou transmissões, ou outras Obras ou +materiais não indicados na Seção 1(g) abaixo, que em razão da seleção e arranjo do seu conteúdo, +constituam criações intelectuais nas quais a Obra é incluída na sua integridade em forma +não-modificada, juntamente com uma ou mais contribuições, cada qual constituindo separada e +independentemente uma Obra em si própria, que juntas são reunidas em um todo coletivo. A Obra +que constituir uma Obra Coletiva não será considerada uma Obra Derivada (como definido acima) +para os propósitos desta Licença. + +"Distribuir" significa colocar à disposição do público o original e cópias da Obra ou Obra +Derivada, o que for apropriado, por meio de venda ou qualquer outra forma de transferência de +propriedade ou posse. + +"Licenciante" significa a pessoa física ou jurídica que oferece a Obra sob os termos desta Licença. + +"Autor Original" significa, no caso de uma Obra literária, artística ou científica, o indivíduo ou +indivíduos que criaram a Obra ou, se nenhum indivíduo puder ser identificado, a editora. + +"Titular de Direitos Conexos" significa (i) no caso de uma performance os atores, cantores, músicos, +dançarinos, e outras pessoas que atuem, cantem, recitem, declamem, participem em, interpretem ou +façam performances de Obras literárias ou artísticas ou expressões de folclore (ii) no caso de um +fonograma, o produtor, sendo este a pessoa ou entidade legal que primeiramente fixar os sons de +uma performance ou outros sons; e (iii) no caso de radiodifusão, a empresa de radiodifusão. + +"Obra" significa a Obra literária, artística e/ou científica oferecida sob os termos desta Licença, +incluindo, sem limitação, qualquer produção nos domínios literário, artístico e científico, qualquer +que seja o modo ou a forma de sua expressão, incluindo a forma digital, tal qual um livro, brochuras +e outros escritos; uma conferência, alocução, sermão e outras Obras da mesma natureza; uma +Obra dramática ou dramático-musical; uma Obra coreográfica ou pantomima; uma composição musical +com ou sem palavras; uma Obra cinematográfica e as expressas por um processo análogo ao da +cinematografia; uma Obra de desenho, pintura, arquitetura, escultura, gravura ou litografia; uma +Obra fotográfica e as Obras expressas por um processo análogo ao da fotografia; uma Obra de arte +aplicada; uma ilustração, mapa, plano, esboço ou Obra tridimensional relativa a geografia, topografia, +arquitetura ou ciência; uma performance, transmissão ou fonograma, na medida em que tais +Obras/direitos sejam reconhecidos e protegidos pela legislação aplicável; uma compilação de dados, +na extensão em que ela seja protegida como uma Obra sujeita ao regime dos direitos autorais; ou +uma Obra executada por artistas circenses ou de shows de variedade, conforme ela não for considerada +uma Obra literária, artística ou científica. + +"Você" significa a pessoa física ou jurídica exercendo direitos sob esta Licença, que não tenha +previamente violado os termos desta Licença com relação à Obra, ou que tenha recebido permissão +expressa do Licenciante para exercer direitos sob esta Licença apesar de uma violação prévia. + +"Executar Publicamente" significa fazer a utilização pública da Obra e comunicar ao público a Obra, +por qualquer meio ou processo, inclusive por meios com ou sem fio ou performances públicas digitais; +disponibilizar ao público Obras de tal forma que membros do público possam acessar essas Obras de um +local e em um local escolhido individualmente por eles; Executar a Obra para o público por qualquer +meio ou processo e comunicar ao público performances da Obra, inclusive por performance pública +digital; transmitir e retransmitir a Obra por quaisquer meios, inclusive sinais, sons ou imagens. + +"Reproduzir" significa fazer cópias da Obra por qualquer meio, inclusive, sem qualquer limitação, +por gravação sonora ou visual, e o direito de fixar e Reproduzir fixações da Obra, inclusive o +armazenamento de uma performance protegida ou fonograma, em forma digital ou qualquer outro meio +eletrônico. + +Para continuar lendo a licença +https://creativecommons.org/licenses/by/3.0/br/legalcode diff --git a/README.md b/README.md index 95afaea..3ce9ba1 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,11 @@ -Gestor v1.1 +Gestor v1.0 =========== Por BrunoMine Um gestor de servidor de minetest -### Licenças - -Software LGPL v3 - -Gestor é um software livre; você pode redistribuí-lo e/ou -modificá-lo dentro dos termos da Licença Pública Geral Menor GNU -como publicada pela Fundação do Software Livre (FSF); na versão 3 -da Licença, ou (na sua opinião) qualquer versão. -Este programa é distribuído na esperança de que possa ser útil, -mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO -a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a -Licença Pública Geral Menor GNU para maiores detalhes. -Você deve ter recebido uma cópia da Licença Pública -Geral Menor GNU junto com este programa, -se não, veja . - -Arte - -- gestor.png | por BrunoMine | CC BY v3 - -## Comandos +COMANDOS /gestor | Abre o painel do gestor administrativo @@ -35,7 +15,7 @@ Arte /deserializar | Cria uma estrutura do diretorio de estruturas (toma a posicao do jogador como a menos em x, y e z) -## Estruturas +ESTRUTURAS Para que as estruturas sejam controladas pelo gestor precisam estar serializadas na pasta 'estruturas' @@ -49,25 +29,15 @@ jamais usar sempre usar "_" (sublinhado/underline) no lugar de espaço e evitar caracteres especiais como c cidilha e outros. -## Anticrash +ANTICRASH -O sistema anticrash funciona de maneira independete -do servidor no entanto os dados que ele utiliza são +O sistema anticrash funciona de maneira indempendete +do servidor no entanto os dados que ele utiliza sao atualizados quando o servidor inicia portanto sempre abra o servidor no mundo desejado uma vez antes de iniciar o anticrash (apenas quando tiver mudado de -lugar ou renomeado um diretorio do servidor de -minetest incluindo a pasta do mundo). O anticrash deve -abrir o servidor e deve ser execute o arquivo -gestor-anticrash-minetest.sh a partir de qualquer da -pasta bin do minetest (exemplos de comandos ficam no -painel administrativo ingame). -Lembre de rodar esse anticrash em segundo plano para -poder fechar o terminal e deixar o anticrash rodando -normalmente. -AVISO. Para desligar o anticrash corretamente apenas -desligando o servidor pelo painel administrativo do -gestor. -Para o anticrash funcionar corretamente nos -diretórios é preciso que o minetest seja RUN_IN_PLACE -(roda no local) +lugar ou renomeado um diretorio onde do dervidor de +minetest incluindo passta do mundo). O anticrash deve +abrir o servidor portanto apenas execute os comandos +de ligamento do anticrash com o servidor desligado. +(comandos ficam no painel administrativo ingame) diff --git a/alerta_de_crash.lua b/alerta_de_crash.lua new file mode 100644 index 0000000..413c408 --- /dev/null +++ b/alerta_de_crash.lua @@ -0,0 +1,70 @@ +--[[ + Mod Gestor para Minetest + Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) + + Recebeste uma cópia da GNU Lesser General + Public License junto com esse software, + se não, veja em . + + Funcionalidades do alerta de crash + ]] + +gestor.alerta_de_crash = {} + +-- Lista de admins +local lista_moderadores = {} + +-- Coloca o nome de admin padrao se houver +if minetest.setting_get("name") then + lista_moderadores[minetest.setting_get("name")] = true +end + + +-- Enviar email +gestor.alerta_de_crash.enviar_email = function() + local servidor_smtp = minetest.setting_get("gestor_servidor_smtp") + local login_smtp = minetest.setting_get("gestor_login_smtp") + local senha_login_smtp = minetest.setting_get("gestor_senha_login_smtp") + local email_destinatario = minetest.setting_get("gestor_email_destinatario") + local titulo = minetest.setting_get("gestor_titulo_email") + local texto = minetest.setting_get("gestor_texto_email") + + -- Verificar tem todos os dados + if not servidor_smtp + or not login_smtp + or not senha_login_smtp + or not email_destinatario + or not titulo + or not texto + then + return false + end + + -- Enviar comando + local comando = "nohup sendemail -s \""..servidor_smtp.."\" -xu \""..login_smtp.."\" -xp \""..senha_login_smtp.."\" -f \""..login_smtp.."\" -t \""..email_destinatario.."\" -u \""..titulo.."\" -m \""..texto.."\" >> gestor_envios_de_alerta.out &" + os.execute(comando) + + return true +end + + +-- Avisar por email quando o servidor desligar inesperadamente +minetest.register_on_shutdown(function() + + if minetest.setting_getbool("gestor_alerta_de_crash") then + local inesperado = true + + -- Verifica se um admin está online (nesse caso nao precisa enviar alerta no email) + for _,player in ipairs(minetest.get_connected_players()) do + if lista_moderadores[player:get_player_name()] then + inesperado = false + break + end + end + + if inesperado then + gestor.alerta_de_crash.enviar_email() + end + end + +end) diff --git a/anticrash.lua b/anticrash.lua deleted file mode 100644 index d22bfef..0000000 --- a/anticrash.lua +++ /dev/null @@ -1,78 +0,0 @@ ---[[ - Mod Gestor para Minetest - Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) - - Recebeste uma cópia da GNU Lesser General - Public License junto com esse software, - se não, veja em . - - Funcionalidades do anticrash - ]] - -gestor.anticrash = {} - --- Caminho do mod -local modpath = minetest.get_modpath("gestor") - --- Nome do mundo -local worldname = string.split(minetest.get_worldpath(), "worlds/") -worldname = worldname[table.maxn(worldname)] - --- Validar dados ---[[ - Verificar a existencia de dados e - cria-los com valor padrão para que - estejam disponiveis - ]] -local verificar_dado = function(dado, padrao) - if gestor.bd:verif("anticrash", dado) ~= true then - gestor.bd:salvar("anticrash", dado, padrao) - end -end - --- Tabela de dados (que devem estar no banco de dados) -local dados = { - -- Dados Valor padrao - -- Sistema AntCrash - { "bin_args", "./minetest --server --worldname "..worldname}, - { "interval", "300"}, - { "quedas", "2"}, - -- Sistema de Email - { "status_email", "false"}, - { "from_email", "-"}, - { "from_login", "-"}, - { "from_smtp", "-"}, - { "from_smtp_port", "-"}, - { "from_subject", "Servidor reiniciado!"}, - { "from_text", "Texto"}, - { "from_subject_em", "ALERTA Servidor inoperante"}, - { "from_text_em", "O servidor cai muito rapidamente. Anticrash foi interrompido para evitar danos"}, - { "to_email", "-"}, - -- Sistema de Backups - { "status_backup", "false"}, - { "world_path", minetest.get_worldpath()}, -} - --- Verifica todos os dados -for _, v in ipairs(dados) do - verificar_dado(v[1], v[2]) -end - --- Salvar um valor para o antcrash -gestor.anticrash.serializar = function(dado, valor) - if not dado or not valor then return end - os.execute("echo \""..valor.."\" > "..string.gsub(modpath, " ", "\\ ").."/dados/"..dado) -end - --- Salva todos os dados para o shell -gestor.anticrash.salvar_dados = function() - for _, v in ipairs(dados) do - gestor.anticrash.serializar(v[1], gestor.bd:pegar("anticrash", v[1])) - end - if gestor.bd:verif("anticrash", "from_senha") then -- separada - gestor.anticrash.serializar("from_senha", gestor.bd:pegar("anticrash", "from_senha")) - end -end - --- Atualiza os dados salvos por garantia -gestor.anticrash.salvar_dados() diff --git a/comandos.lua b/comandos.lua index 8ef1a15..f32c297 100644 --- a/comandos.lua +++ b/comandos.lua @@ -1,13 +1,8 @@ ---[[ - Mod Gestor para Minetest - Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) - - Recebeste uma cópia da GNU Lesser General - Public License junto com esse software, - se não, veja em . - - Comandos - ]] +-- +-- Mod gestor +-- +-- Comandos +-- -- Comando para exibir tela de gerenciamento minetest.register_chatcommand("gestor", { @@ -24,7 +19,7 @@ minetest.register_chatcommand("gestor", { minetest.register_chatcommand("serializar", { privs = {server=true}, params = "[ ]", - description = "Serializa uma estrutura", + description = "Serializa uma estrutura (recomenda-se 10 blocos de profundidade do solo da vila)", func = function(name, param) local m = string.split(param, " ") local param1, param2, param3 = m[1], m[2], m[3] diff --git a/dados/interval b/dados/interval deleted file mode 100644 index 697cb3a..0000000 --- a/dados/interval +++ /dev/null @@ -1 +0,0 @@ -300 diff --git a/diretrizes.lua b/diretrizes.lua index 473157f..6e755fa 100644 --- a/diretrizes.lua +++ b/diretrizes.lua @@ -1,29 +1,24 @@ ---[[ - Mod Gestor para Minetest - Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) - - Recebeste uma cópia da GNU Lesser General - Public License junto com esse software, - se não, veja em . - - Diretrizes - ]] +-- +-- Mod gestor +-- +-- Diretrizes +-- -- Variavel de Diretrizes gestor.diretrizes = {} --- Estruturas -gestor.diretrizes.estruturas = { - -- arquivo, largura, altura - -- Centro - ["centro"] = { 10, 10 }, - -- Vilas -} - -- Lista de vilas (lista de estruturas ja salvas) -gestor.vilas = { - -- "exemplo", -} - +gestor.vilas = {} +do + local list = minetest.get_dir_list(minetest.get_worldpath() .. "/gestor/estruturas") + for n, arq in ipairs(list) do + if string.find(arq, ".mts") then + arq = string.gsub(arq, ".mts", "") + if arq ~= "centro" then + table.insert(gestor.vilas, arq) + end + end + end +end diff --git a/estruturador.lua b/estruturador.lua index 23d5df1..60e60be 100644 --- a/estruturador.lua +++ b/estruturador.lua @@ -1,16 +1,51 @@ ---[[ - Mod Gestor para Minetest - Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) - - Recebeste uma cópia da GNU Lesser General - Public License junto com esse software, - se não, veja em . - - Estruturador - ]] +-- +-- Mod gestor +-- +-- Estruturador +-- + +-- Diretorio do Mundo +local worldpath = minetest.get_worldpath() + +-- Nodes que podem ter metadados serializados +local meta_ok = { + "terrenos:livre", + "default:sign_wall_wood", + "default:sign_wall_steel", + "bau_comunitario:bau", + "antipvp:placa", + "portais:bilheteria", + "macromoney:caixa_de_banco", +} + +-- Assegurar pasta de estruturas +do + local list = minetest.get_dir_list(worldpath, true) + local r = false + for n, ndir in ipairs(list) do + if ndir == "gestor" then + r = true + break + end + end + if r == false then + minetest.mkdir(worldpath.."/gestor") + end + + list = minetest.get_dir_list(worldpath.."/gestor", true) + r = false + for n, ndir in ipairs(list) do + if ndir == "estruturas" then + r = true + break + end + end + if r == false then + minetest.mkdir(worldpath.."/gestor/estruturas") + end + +end --- Diretorio do Mod -local modpath = minetest.get_modpath("gestor") -- Variavel global de estruturador gestor.estruturador = {} @@ -37,184 +72,119 @@ local arredondar = function(pos) return r end --- Restaurar as refenrencias em relacao a uma pos -local restaurar_pos = function(pos, ref) - local r = {} - r.x, r.y, r.z = (pos.x+ref.x), (pos.y+ref.y), (pos.z+ref.z) - return r -end - --- calcular o deslocamento de ref em relacao a pos -local ref_pos = function(pos, ref) - local r = {} - r.x, r.y, r.z = (ref.x-pos.x), (ref.y-pos.y), (ref.z-pos.z) - return r -end - --- metodo melhorado para pegar nodes (pega nodes ainda nao carregados) -local function pegar_node(pos) - local resp = {} - local node = minetest.get_node(pos) - if node.name == "ignore" then - minetest.get_voxel_manip():read_from_map(pos, pos) - node = minetest.get_node(pos) - end - resp = {node=node} - --[[ - Para salvar os metadados é criada um valor meta (node.meta) - para que alguns dados possam ser mantidos de forma serializada - no node e posteriormente serem restaurados quando a estrutura - for restaurada - ]] - local meta = minetest.get_meta(pos) - if node.name == "placa_terreno:livre" then -- placas de terreno - local ref1 = "" - local ref2 = "" - if meta:get_string("ref1") ~= "" then - -- Mantem os antigos ref's caso existam no metadado - ref1 = minetest.deserialize(meta:get_string("ref1")) - ref2 = minetest.deserialize(meta:get_string("ref2")) - else - -- Calcula os ref's - ref1 = minetest.serialize(ref_pos(pos, minetest.deserialize(meta:get_string("pos1")))) - ref2 = minetest.serialize(ref_pos(pos, minetest.deserialize(meta:get_string("pos2")))) - end - local custo = meta:get_string("custo") - local altura = meta:get_string("altura") - resp = {node=node,meta={ref1=ref1,ref2=ref2,custo=custo,altura=altura}} - elseif node.name == "default:sign_wall" then -- placas normais de parede - local text = meta:get_string("text") - local infotext = meta:get_string("infotext") - resp = {node=node,meta={text=text,infotext=infotext}} - end - return resp -end - -- Serializar estrutura -gestor.estruturador.salvar = function(pos, nome, largura, altura, modp, silencio) +gestor.estruturador.salvar = function(pos, nome, largura, altura, path, silencio) if not pos or not nome then return false end -- arredondar posicao + local as = pos.x pos = arredondar(pos) - if modp == nil then - modp = modpath + if path == nil then + path = worldpath .. "/gestor/estruturas" end largura = largura or gestor.diretrizes.estruturas[nome][1] altura = altura or gestor.diretrizes.estruturas[nome][1] if not largura or not altura then return false end - -- Criar estrutura - if silencio == nil or silencio == false then minetest.chat_send_all("Serializando estrutura. Aguarde...") end - local estrutura = {} - local ix, iy, iz = 1, 1, 1 - local x, y, z = pos.x, pos.y, pos.z - local limx, limy, limz = (pos.x+largura-1), (pos.y+altura-1), (pos.z+largura-1) - local i = 0 - while (x <= limx) do - while (y <= limy) do - while (z <= limz) do - estrutura[ix.." "..iy.." "..iz] = pegar_node({x = x, y = y, z = z}) - i = i + 1 - z = z + 1 - iz = iz + 1 - end - z = pos.z - iz = 1 - y = y + 1 - iy = iy + 1 - end - y = pos.y - iy = 1 - x = x + 1 - ix = ix + 1 + + -- Coordenada do extremo oposto da estrutura + local pmax = {x=pos.x+largura, y=pos.y+altura, z=pos.z+largura} + + -- Criar arquivo schematic + if silencio == nil or silencio == false then minetest.chat_send_all("Criando arquivo esquematico da estrutura ...") end + minetest.create_schematic(pos, pmax, {}, path .. "/"..nome..".mts") + + -- Metadados de alguns nodes + local metadados = {} + + -- Metadados dos nodes + metadados.nodes = {} + + -- Armazena as dimensoes + metadados.altura = altura + metadados.largura = largura + + -- Pegar nodes quem podem ter seus metadados serializados + local nodes = minetest.find_nodes_in_area(pos, pmax, meta_ok) + + -- Pegar metadados dos nodes encontrados + for _,pn in ipairs(nodes) do + -- Serializa os metadados + local meta = minetest.get_meta(pn):to_table() + + -- Calcula a posicao relativa a coordenada extremo-negativa + local pr = {x=pn.x-pos.x, y=pn.y-pos.y, z=pn.z-pos.z} + metadados.nodes[pr.x.." "..pr.y.." "..pr.z] = meta end - -- Criar arquivo - local output = io.open(modp .. "/estruturas/"..nome, "w") - output:write(minetest.serialize(estrutura)) + -- Criar arquivo de metadados + local output = io.open(path .. "/"..nome..".meta", "w") + + -- Serializa os metadados + if silencio == nil or silencio == false then minetest.chat_send_all("Serializando metadados ...") end + metadados = minetest.serialize(metadados) + + if silencio == nil or silencio == false then minetest.chat_send_all("Escrevendo metadados serializados em arquivo ...") end + output:write(metadados) io.close(output) -- Estrutura serializada com sucesso - if silencio == nil or silencio == false then minetest.chat_send_all("Serializacao concluida.") end return true end + -- Deserializar uma estrutura -gestor.estruturador.carregar = function(pos, nome, largura, altura, modp, silencio) +gestor.estruturador.carregar = function(pos, nome, largura, altura, path, silencio) if pos == nil or nome == nil then return false end if silencio == nil or silencio == false then minetest.chat_send_all("Criando estrutura. Aguarde...") end -- Coleta de dados local dados = {} - if modp == nil then - dados = gestor.diretrizes.estruturas[nome] or {} - largura = dados[1] or largura - altura = dados[2] or altura - modp = modpath + if path == nil then + path = worldpath .. "/gestor/estruturas" end - if largura == nil or altura == nil or nome == nil then return false end - local input = io.open(modp .. "/estruturas/"..nome, "r") + + -- Obter metadados + local metadados = "" + local input = io.open(path .. "/"..nome..".meta", "r") if input then - dados.estrutura = minetest.deserialize(input:read("*l")) + metadados = input:read("*l") else return false end + if not metadados then + minetest.chat_send_all("Erro. Faltou o arquivo de metadados") + return false + end io.close(input) - -- Criar estrutura - local ix, iy, iz = 1, 1, 1 - local x, y, z = pos.x, pos.y, pos.z - local limx, limy, limz = (pos.x+largura-1), (pos.y+altura-1), (pos.z+largura-1) - local i = 0 - while (x <= limx) do - while (y <= limy) do - while (z <= limz) do - local PosNode = dados.estrutura[ix.." "..iy.." "..iz] or {node={name="air"}} - minetest.set_node({x = x, y = y, z = z}, PosNode.node) - if PosNode.meta then - if PosNode.node.name == "placa_terreno:livre" then - local meta = minetest.get_meta({x = x, y = y, z = z}) - --[[ - Tenta restaurar pos1 e pos2 mas devido a um erro - desconhecido as vezes desloca 1 node de distancia - para alguma direção - ]] - meta:set_string("pos1", - minetest.serialize(restaurar_pos(minetest.deserialize(PosNode.meta.ref1), - {x = x, y = y, z = z})) - ) - meta:set_string("pos2", - minetest.serialize(restaurar_pos(minetest.deserialize(PosNode.meta.ref2), - {x = x, y = y, z = z})) - ) - --[[ - Mantes ref1 e ref2 no meto do bloco para evitar distorções maiores - usando sempre esses ref's a distorção pode ser no maximo 1 node - ]] - meta:set_string("ref1", minetest.serialize(PosNode.meta.ref1)) - meta:set_string("ref2", minetest.serialize(PosNode.meta.ref2)) - meta:set_string("custo", PosNode.meta.custo) - meta:set_string("altura", PosNode.meta.altura) - meta:set_string("status", "livre") - meta:set_string("infotext", "Terreno a Venda") - elseif PosNode.node.name == "default:sign_wall" then - local meta = minetest.get_meta({x = x, y = y, z = z}) - meta:set_string("text", PosNode.meta.text) - meta:set_string("infotext", PosNode.meta.infotext) - end - end - i = i + 1 - z = z + 1 - iz = iz + 1 - end - z = pos.z - iz = 1 - y = y + 1 - iy = iy + 1 - end - y = pos.y - iy = 1 - x = x + 1 - ix = ix + 1 - end + + -- Deserializar metadados + metadados = minetest.deserialize(metadados) + + altura = metadados.altura + largura = metadados.largura + + + + -- Coordenada do extremo oposto da estrutura + local pmax = {x=pos.x+largura, y=pos.y+altura, z=pos.z+largura} + + -- Colocar estrutura esquematica + minetest.place_schematic(pos, path.."/"..nome..".mts", nil, nil, true) + + -- Restaurar metadados nos nodes + for pos_string,meta in pairs(metadados.nodes) do + + -- Obter pos em tabela + local pos_tb = string.split(pos_string, " ") + pos_tb = {x=tonumber(pos_tb[1]),y=tonumber(pos_tb[2]),z=tonumber(pos_tb[3])} + + -- Calcular pos real do node + local pn = {x=pos.x+pos_tb.x, y=pos.y+pos_tb.y, z=pos.z+pos_tb.z} + + -- Salva metadados + minetest.get_meta(pn):from_table(meta) + + end -- Estrutura construida com sucesso if silencio == nil or silencio == false then minetest.chat_send_all("Estrutura construida. Aguarde o mapa ser renderizado.") end @@ -276,3 +246,17 @@ minetest.register_node("gestor:escadaria", { -------- ----- -- + +-- Pegar metadados da estrutura +gestor.estruturador.get_meta = function(nome) + local path = worldpath .. "/gestor/estruturas" + + -- Obter metadados + local metadados = "" + local input = io.open(path .. "/"..nome..".meta", "r") + if not input then return nil end + metadados = input:read("*l") + io.close(input) + + return minetest.deserialize(metadados) +end diff --git a/estruturas/blocopolis.meta b/estruturas/blocopolis.meta new file mode 100644 index 0000000..42d4826 --- /dev/null +++ b/estruturas/blocopolis.meta @@ -0,0 +1 @@ +return {["30 11 43"] = {["ref2"] = {["y"] = 9, ["x"] = 12, ["z"] = -10}, ["altura"] = "10", ["custo"] = "60", ["ref1"] = {["y"] = -1, ["x"] = 1, ["z"] = 0}}, ["26 8 2"] = {["ref2"] = {["y"] = 9, ["x"] = 21, ["z"] = 7}, ["altura"] = "10", ["custo"] = "70", ["ref1"] = {["y"] = -1, ["x"] = 1, ["z"] = 0}}, ["35 8 22"] = {["ref2"] = {["y"] = 9, ["x"] = 0, ["z"] = -1}, ["altura"] = "10", ["custo"] = "40", ["ref1"] = {["y"] = -1, ["x"] = -8, ["z"] = -9}}, ["11 8 36"] = {["ref2"] = {["y"] = 9, ["x"] = -9, ["z"] = -7}, ["altura"] = "10", ["custo"] = "40", ["ref1"] = {["y"] = -1, ["x"] = -1, ["z"] = 0}}, ["15 8 11"] = {["ref2"] = {["y"] = 9, ["x"] = 7, ["z"] = -9}, ["altura"] = "10", ["custo"] = "40", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = -1}}, ["11 8 47"] = {["ref2"] = {["y"] = 9, ["x"] = -9, ["z"] = -7}, ["altura"] = "10", ["custo"] = "40", ["ref1"] = {["y"] = -1, ["x"] = -1, ["z"] = 0}}, ["11 8 11"] = {["ref2"] = {["y"] = 9, ["x"] = 0, ["z"] = -1}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = -9, ["z"] = -9}}, ["11 8 25"] = {["ref2"] = {["y"] = 9, ["x"] = -9, ["z"] = -10}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = -1, ["z"] = 0}}, ["39 8 22"] = {["ref2"] = {["y"] = 9, ["x"] = 8, ["z"] = -9}, ["altura"] = "10", ["custo"] = "40", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = -1}}} \ No newline at end of file diff --git a/estruturas/blocopolis.mts b/estruturas/blocopolis.mts new file mode 100644 index 0000000..95333cb Binary files /dev/null and b/estruturas/blocopolis.mts differ diff --git a/estruturas/centro.meta b/estruturas/centro.meta new file mode 100644 index 0000000..90d9aef --- /dev/null +++ b/estruturas/centro.meta @@ -0,0 +1 @@ +return {["14 8 12"] = {["ref2"] = {["y"] = 9, ["x"] = 8, ["z"] = -7}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = -1}}, ["44 8 34"] = {["ref2"] = {["y"] = 9, ["x"] = -7, ["z"] = 10}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = 1}}, ["25 8 12"] = {["ref2"] = {["y"] = 9, ["x"] = 8, ["z"] = -7}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = -1}}, ["36 8 12"] = {["ref2"] = {["y"] = 9, ["x"] = 8, ["z"] = -7}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = -1}}, ["39 9 16"] = {["infotext"] = "\"Abrigo\"", ["text"] = "Abrigo"}, ["36 9 23"] = {["infotext"] = "\"Abrigo\"", ["text"] = "Abrigo"}, ["5 8 12"] = {["ref2"] = {["y"] = 9, ["x"] = 6, ["z"] = -7}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = 0, ["z"] = -1}}, ["27 8 33"] = {["ref2"] = {["y"] = 9, ["x"] = 7, ["z"] = 10}, ["altura"] = "10", ["custo"] = "50", ["ref1"] = {["y"] = -1, ["x"] = 1, ["z"] = 0}}} \ No newline at end of file diff --git a/estruturas/centro.mts b/estruturas/centro.mts new file mode 100644 index 0000000..7960bd0 Binary files /dev/null and b/estruturas/centro.mts differ diff --git a/estruturas/estruturas_aqui.txt b/estruturas/estruturas_aqui.txt deleted file mode 100644 index 5b88569..0000000 --- a/estruturas/estruturas_aqui.txt +++ /dev/null @@ -1 +0,0 @@ -As estruturas serializadas devem ficar aqui diff --git a/gestor-anticrash-minetest.sh b/gestor-anticrash-minetest.sh deleted file mode 100755 index 47aff5b..0000000 --- a/gestor-anticrash-minetest.sh +++ /dev/null @@ -1,141 +0,0 @@ -#!/bin/bash - -##################################################### -## SCRIPT ANTICRASH v1.1 Copyright (C) 2016 ## -## LICENÇA: LGPL v3.0 ## -## Por ## -## Lunovox ## -## BrunoMine ## -##################################################### -## Recebeste uma cópia da GNU Lesser General ## -## Public License junto com esse software. ## -## Se não, veja em . ## -##################################################### - -# Caminho para dados do mod -dados_path="./../mods/gestor/dados" - -# Intervalo de verificação (em segundos) -interval=$(cat "$dados_path"/interval) - -# Vezes que o servidor pode cair seguidamente -lim_quedas=$(cat "$dados_path"/quedas) - -# Nome do processo -processo="minetest --server" #"minetest --server" - -# Comando de abertura do servidor -bin_args=$(cat "$dados_path"/bin_args) - -# Caminho do diretório do mundo -world_path=$(cat "$dados_path"/world_path) - -# Variáveis de Email -from_email=$(cat "$dados_path"/from_email) # Endereço de origem que envia email -from_login=$(cat "$dados_path"/from_login) # Loggin do email de origem -from_senha=$(cat "$dados_path"/from_senha) # Senha do email de origem -from_smtp=$(cat "$dados_path"/from_smtp) # Protocolo de SMTP do seu servidor de email -from_subject=$(cat "$dados_path"/from_subject) # Titulo do email que será enviado -from_text=$(cat "$dados_path"/from_text) # Texto do corpo da mensagem de email enviada -to_email=$(cat "$dados_path"/to_email) # Endereço de destinatário que recebe email -# Mensagens de alerta emergencial -from_subject_em=$(cat "$dados_path"/from_subject_em) -from_text_em=$(cat "$dados_path"/from_text_em) - -# Status de Sistemas -status_email=$(cat "$dados_path"/status_email) # Se o sistema de email deve funcionar -status_backup=$(cat "$dados_path"/status_backup) # Se o sistema de email deve funcionar - -# AVISO de autenticidade dos dados -echo -e "\033[01;34m###_AVISO_#################################################\033[00;00m" -echo "Para evitar erros nesse anticrash, abra e feche o servidor (no mundo desejado) normalmente uma vez para atualizar dados (para o caso de troca de diretorios e/ou nomes)" - -# AVISO servidor so pode ser fechado pelo gestor -echo -e "\033[01;34m###_AVISO_#################################################\033[00;00m" -echo "Uma vez iniciado o anticrash o servidor pode ser fechado apenas pelo botao de desligamento no painel administrativo do gestor" -echo "on" > $dados_path/status # anticrash trabalha - -echo -e "\033[01;35m###########################################################\033[00;00m" -echo -e "\033[01;35m## ___ _ _____ ___ ___ ___ ___ v1.1 ##\033[00;00m" -echo -e "\033[01;35m## | | |\ | | | | | \ | | | | | ##\033[00;00m" -echo -e "\033[01;35m## |___| | \ | | | | |___/ |___| \___ |___| ##\033[00;00m" -echo -e "\033[01;35m## | | | \| | | |___ | \ | | ___| | | ##\033[00;00m" -echo -e "\033[01;35m###########################################################\033[00;00m" -echo -e "\033[01;35m## Gestor Copyright (C) 2016. ##\033[00;00m" -echo -e "\033[01;35m## Esse programa não tem ABSOLUTAMENTE NENHUMA GARANTIA. ##\033[00;00m" -echo -e "\033[01;35m###########################################################\033[00;00m" - -# INFO Abre o servidor normalmente -echo -e "\033[01;32m###_INFO_##################################################\033[00;00m" -echo "Abrindo servidor..." -nohup $bin_args >> debug.out & - - -# INFO Inicia loopde verificação -echo -e "\033[01;32m###_INFO_##################################################\033[00;00m" -echo -e "[\033[01;32m$(date '+%Y-%m-%d %H:%M:%S')\033[00;00m] Iniciando verificação de processo '$processo' a cada $interval segundos..." - -quedas=0 # contador de quedas - -# Laço de verificação infinito -while [ true == true ]; do - if ! [ "$(pgrep -f "$processo")" ]; then # verificar processo - - quando="$(date '+%Y-%m-%d %H-%M-%S')" - - # Verificar se o servidor desligou corretamente - if [ $(cat "$dados_path"/status) == off ]; then - echo -e "[\033[01;32m$quando\033[00;00m] Servidor foi desligado normalmente..." - echo "Desligando anticrash..." - break - fi - - # Servidor parou abruptamente - echo -e "\033[01;32m###_INFO_##################################################\033[00;00m" - echo -e "[\033[01;32m$quando\033[00;00m] Servidor parou abruptamente (ou de modo inconveniente)..." - - # Soma ao contador de quedas - let quedas++ - - # Renomeia arquivo de depuração - echo "Renomenado 'debug.txt' para 'debug ($quando).txt'..." - mv "debug.txt" "debug ($quando).txt" - - # Faz backup do mundo - if [ $status_backup == "true" ]; then - echo "Fazendo backup do mapa em '$world_path($quando).tar.gz'..." - tar -czf "$world_path($quando).tar.gz" "$world_path" - fi - - if [ $quedas -ge $lim_quedas ]; then - # AVISO Atingiu limite de quedas sucessivas - echo -e "\033[01;34m###_AVISO_#################################################\033[00;00m" - echo "Atingiu o limite de quedas sucessivas." - if [ $status_email == "true" ]; then - # Enviando relatorio para email - echo "Enviando relatório para '$to_email'..." - sendemail -s "$from_smtp" -xu "$from_login" -xp "$from_senha" -f "$from_email" -t "$to_email" -u "$from_subject_em" -m "$from_text_em" -o message-charset=UTF-8 -a "debug ($quando).txt" - fi - # Desligando anticrash - echo "Desligando anticrash..." - echo "off" > $dados_path/status # anticrash parou - break - else - if [ $status_email == "true" ]; then - # Enviando relatorio para email - echo "Enviando relatório para '$to_email'..." - sendemail -s "$from_smtp" -xu "$from_login" -xp "$from_senha" -f "$from_email" -t "$to_email" -u "$from_subject" -m "$from_text" -o message-charset=UTF-8 -a "debug ($quando).txt" - fi - fi - - # Reativando servidor - echo "Reativando servidor de minetest ..." - nohup $bin_args >> debug.out & - - else - quedas=0 # zerar o contador de quedas apos 1 intervalo/loop sem queda - fi - - sleep $interval -done - diff --git a/init.lua b/init.lua index ba1f35c..225121b 100644 --- a/init.lua +++ b/init.lua @@ -30,7 +30,8 @@ dofile(modpath.."/diretrizes.lua") dofile(modpath.."/estruturador.lua") dofile(modpath.."/protetor.lua") dofile(modpath.."/lugares_avulsos.lua") +dofile(modpath.."/vilas.lua") dofile(modpath.."/menu_principal.lua") dofile(modpath.."/comandos.lua") -dofile(modpath.."/anticrash.lua") +dofile(modpath.."/alerta_de_crash.lua") notificar("OK") diff --git a/lugares_avulsos.lua b/lugares_avulsos.lua index fa4d6be..f63b19e 100644 --- a/lugares_avulsos.lua +++ b/lugares_avulsos.lua @@ -1,13 +1,8 @@ ---[[ - Mod Gestor para Minetest - Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) - - Recebeste uma cópia da GNU Lesser General - Public License junto com esse software, - se não, veja em . - - Lugares avulsos - ]] +-- +-- Mod gestor +-- +-- Lugares avulsos (gerenciamento) +-- -- Variavel global gestor.lugares_avulsos = {} diff --git a/menu_principal.lua b/menu_principal.lua index ebd1492..8f982db 100644 --- a/menu_principal.lua +++ b/menu_principal.lua @@ -38,7 +38,7 @@ end local aba = {} -- salva em que aba o jogador esta gestor.menu_principal = function(name, inicio) if inicio == true then aba[name] = "inicio" end - + local formspec = "size[14,11]" ..default.gui_bg ..default.gui_bg_img @@ -46,7 +46,7 @@ gestor.menu_principal = function(name, inicio) .."button[0,1;3,1;desligar;Desligar]" -- Botao 1 .."button[0,2;3,1;lugares;Lugares]" -- Botao 2 .."button[0,3;3,1;conf;Diretrizes]" -- Botao 3 - .."button[0,4;3,1;anticrash;AntiCrash]" -- Botao 4 + .."button[0,4;3,1;alerta_de_crash;Alerta de Crash]" -- Botao 4 --.."button[0,5;3,1;;]" -- Botao 5 --.."button[0,6;3,1;;]" -- Botao 6 --.."button[0,7;3,1;;]" -- Botao 7 @@ -113,56 +113,49 @@ gestor.menu_principal = function(name, inicio) .."field[4.3,4.1;3,1;slots;Limite de Jogadores;"..minetest.setting_get("max_users").."]" .."button_exit[7,3.8;3,1;definir_slots;Redefinir Limite]" - -- AntiCrash - elseif aba[name] == "anticrash" then + -- Alerta de crash + elseif aba[name] == "alerta_de_crash" then - local status_senha = "" - if gestor.bd:pegar("anticrash", "from_senha") then status_senha = " (Salva)" end + -- Pegar dados + local status_alerta_de_crash = minetest.setting_getbool("gestor_alerta_de_crash") or false + local servidor_smtp = minetest.setting_get("gestor_servidor_smtp") or "-" + local login_smtp = minetest.setting_get("gestor_login_smtp") or "-" + local senha_login_smtp = minetest.setting_get("gestor_senha_login_smtp") + local email_destinatario = minetest.setting_get("gestor_email_destinatario") or "-" + local titulo = minetest.setting_get("gestor_titulo_email") or "-" + local texto = minetest.setting_get("gestor_texto_email") or "-" - local status_email = "1" - if gestor.bd:pegar("anticrash", "status_email") == "true" then status_email = "2" end + local status_senha = "nenhuma" + if senha_login_smtp then + status_senha = "salva" + end - local status_backup = "1" - if gestor.bd:pegar("anticrash", "status_backup") == "true" then status_backup = "2" end - --[[ - local bin_paths = io.popen"locate bin/minetest":read"*all" - bin_paths = string.gsub(bin_paths, "bin/minetest", "bin") - bin_paths = string.gsub(bin_paths, "\n", ",") - local path_selecionado = gestor.bd:pegar("anticrash", "bin_path") or "-" - ]] - local comando_selecionado = 1 - local co = gestor.bd:pegar("anticrash", "comando_abertura") - for n, c in ipairs(string.split("minetest --server,minetestserver", ",")) do - if c == co then - comando_selecionado = n - break - end + if status_alerta_de_crash == false then + status_alerta_de_crash = "1" + else + status_alerta_de_crash = "2" end formspec = formspec - .."label[4,1;AntiCrash]" + + .."label[4,1;Alerta de Crash]" + -- Sistema Verificador AntiCrash .."label[4,2;Sistema Verificador AntiCrash]" .."button[4,2.6;3,1;salvar;Salvar Dados]" - .."field[7.4,3;3.2,1;quedas;Lim. quedas seguidas;"..gestor.bd:pegar("anticrash", "quedas").."]" - .."field[10.6,3;3.3,1;interval;Intervalo de verif. (s);"..gestor.bd:pegar("anticrash", "interval").."]" - .."textarea[4.3,3.8;9.6,1.5;comando;Comando de abertura do servidor (digite no terminal UNIX);$ cd \""..string.gsub(modpath, " ", " ").."\"\n$ ./../mod/gestor/./gestor-anticrash-minetest.sh]" -- Sistema Notificador via Email .."label[4,5;Sistema Notificador via Email]" .."label[4,5.4;Estado]" - .."dropdown[4,5.8;2,1;status_email;Inativo,Ativo;"..status_email.."]" - .."field[6.3,6;4.3,1;from_email;Email emissor;"..gestor.bd:pegar("anticrash", "from_email").."]" - .."pwdfield[10.6,6;3.3,1;from_senha;Senha"..status_senha.."]" - .."field[4.3,7;4,1;from_login;Login do SMTP;"..gestor.bd:pegar("anticrash", "from_login").."]" - .."field[8.3,7;4,1;from_smtp;SMTP do email emissor;"..gestor.bd:pegar("anticrash", "from_smtp").."]" - .."field[12.3,7;1.6,1;from_smtp_port;Porta;"..gestor.bd:pegar("anticrash", "from_smtp_port").."]" - .."field[4.3,8;5,1;from_subject;Titulo da mensagem de email enviada;"..gestor.bd:pegar("anticrash", "from_subject").."]" - .."field[9.3,8;4.6,1;to_email;Email do destinatario;"..gestor.bd:pegar("anticrash", "to_email").."]" - -- Sistema de Backup - .."label[4,8.8;Sistema de Backup]" - .."dropdown[4,9.3;3,1;status_backup;Inativo,Ativo;"..status_backup.."]" - .."button[10.6,8.6;3,1;testar_email;Enviar email teste]" -- Testar email + + .."dropdown[4,5.8;2,1;status_email;Inativo,Ativo;"..status_alerta_de_crash.."]" + .."field[6.3,6;4.3,1;login_smtp;Login emissor;"..login_smtp.."]" + .."pwdfield[10.6,6;3.3,1;senha;Senha ("..status_senha..")]" + .."field[4.3,7.2;9.6,1;servidor_smtp;Servidor SMTP de envio (host:porta);"..servidor_smtp.."]" + .."field[4.3,8.4;5,1;titulo;Titulo da mensagem de email enviada;"..titulo.."]" + .."field[9.3,8.4;4.6,1;email_destinatario;Email do destinatario;"..email_destinatario.."]" + .."field[4.3,9.6;9.6,1;texto;Texto;"..texto.."]" + .."button[4,10;5,1;testar_email;Enviar mensagem de teste]" end @@ -190,8 +183,8 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) aba[name] = "diretrizes" gestor.menu_principal(name) return true - elseif fields.anticrash then -- AntiCrash - aba[name] = "anticrash" + elseif fields.alerta_de_crash then -- Alerta de Crash + aba[name] = "alerta_de_crash" gestor.menu_principal(name) return true end @@ -224,14 +217,15 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) ) elseif fields.construir_vila then escolha_vila[name] = fields.vila - minetest.show_formspec(name, "gestor:aviso_construir_vila", "size[4,3.8]".. + minetest.show_formspec(name, "gestor:aviso_construir_vila", "size[4,4.8]".. default.gui_bg.. default.gui_bg_img.. "label[0,0;Tem certeza que quer \nconstruir essa vila?]".. - "field[0.25,1.2;4,1;nome_vila;;Nome da Vila]".. + "label[0,1;"..core.colorize("#FF0000", "Fique na faixa de altura \n") .. core.colorize("#FF0000", "maxima dos picos em volta").."]".. + "field[0.25,3.2;4,1;nome_vila;;Nome da Vila]".. "label[0,2;Arquivo de midia: \n"..escolha_vila[name].."]".. - "button[0,3;2,1;cancelar;Cancelar]".. - "button_exit[2,3;2,1;ok;Sim]" + "button[0,4;2,1;cancelar;Cancelar]".. + "button_exit[2,4;2,1;ok;Sim]" ) elseif fields.tp_vila then if fields.vila then @@ -281,127 +275,76 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) end end - -- Anticrash - elseif aba[name] == "anticrash" then + -- Alerta de Crash + elseif aba[name] == "alerta_de_crash" then if fields.salvar then + + -- Salvar todos os dados - -- Salvar dados gerais - if fields.from_email == "" then fields.from_email = "-" end - if fields.from_login == "" then fields.from_login = "-" end - if fields.from_smtp == "" then fields.from_smtp = "-" end - if fields.from_smtp_port == "" then fields.from_smtp_port = "-" end - if fields.from_subject == "" then fields.from_subject = "-" end - if fields.to_email == "" then fields.to_email = "-" end - if fields.quedas == "" or not tonumber(fields.quedas) then fields.quedas = "5" end - if fields.interval == "" or not tonumber(fields.interval) then fields.interval = "300" end - gestor.bd:salvar("anticrash", "from_email", fields.from_email) - gestor.bd:salvar("anticrash", "from_login", fields.from_login) - gestor.bd:salvar("anticrash", "from_smtp", fields.from_smtp) - gestor.bd:salvar("anticrash", "from_smtp_port", fields.from_smtp_port) - gestor.bd:salvar("anticrash", "from_subject", fields.from_subject) - gestor.bd:salvar("anticrash", "to_email", fields.to_email) - gestor.bd:salvar("anticrash", "quedas", fields.quedas) - gestor.bd:salvar("anticrash", "interval", fields.interval) - if fields.from_senha ~= "" then - gestor.bd:salvar("anticrash", "from_senha", fields.from_senha) - end - -- Salva todos os dados para o shell - gestor.anticrash.salvar_dados() - - -- Verificar sistema de email + -- Status de alerta de email if fields.status_email == "Ativo" then - -- Verificando dados - if fields.from_email == "-" - or fields.from_smtp == "-" - or fields.from_smtp_port == "-" - or fields.from_subject == "-" - or fields.to_email == "-" - or gestor.bd:verif("anticrash", "from_senha") ~= true - then - minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. - default.gui_bg.. - default.gui_bg_img.. - "label[0,0;AVISO \nFaltam dados no sistema \nde emails]" - ) - minetest.after(2, gestor.menu_principal, name) - gestor.bd:salvar("anticrash", "status_email", "false") - return - end - -- Verificando se sendemail esta instalado - local verif_sendemail = os.execute("sendemail --help") - if verif_sendemail ~= 0 and verif_sendemail ~= 256 then - minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. - default.gui_bg.. - default.gui_bg_img.. - "label[0,0;AVISO \nFalta o software sendEmail \nno computador para usar \no Sistema de Email]" - ) - minetest.after(3, gestor.menu_principal, name) - gestor.bd:salvar("anticrash", "status_email", "false") - return - end - - gestor.bd:salvar("anticrash", "status_email", "true") + minetest.setting_setbool("gestor_alerta_de_crash", true) else - gestor.bd:salvar("anticrash", "status_email", "false") + minetest.setting_setbool("gestor_alerta_de_crash", false) end - -- Verificar sistema de backup - if fields.status_backup == "Ativo" then - -- Verificando se compactador TAR esta instalado - local verif_tar = os.execute("tar --help") - if verif_tar ~= 0 and verif_tar ~= 256 then - minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. - default.gui_bg.. - default.gui_bg_img.. - "label[0,0;AVISO \nFalta o compactador TAR\nno computador para usar \no Sistema de Backups]" - ) - minetest.after(3, gestor.menu_principal, name) - gestor.bd:salvar("anticrash", "status_backup", "false") - return - end - - gestor.bd:salvar("anticrash", "status_backup", "true") - else - gestor.bd:salvar("anticrash", "status_backup", "false") + -- Servidor SMTP + if fields.servidor_smtp and fields.servidor_smtp ~= "-" then + minetest.setting_set("gestor_servidor_smtp", fields.servidor_smtp) + end + + -- Login SMTP + if fields.login_smtp and fields.login_smtp ~= "-" then + minetest.setting_set("gestor_login_smtp", fields.login_smtp) + end + + -- Senha de Login SMTP + if fields.senha and fields.senha ~= "" then + minetest.setting_set("gestor_senha_login_smtp", fields.senha) + end + + -- Email do Destinatario + if fields.email_destinatario and fields.email_destinatario ~= "-" then + minetest.setting_set("gestor_email_destinatario", fields.email_destinatario) + end + + -- Titulo da mensagem de Email + if fields.titulo and fields.titulo ~= "-" then + minetest.setting_set("gestor_titulo_email", fields.titulo) + end + + -- Texto da mensagem de Email + if fields.texto and fields.texto ~= "-" then + minetest.setting_set("gestor_texto_email", fields.texto) end minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. default.gui_bg.. default.gui_bg_img.. - "label[0,0;DADOS SALVOS \nTodos os dados foram \nsalvos com sucesso]" + "label[0,0;SUCESSO \nOs dados validos foram \nsalvos.]" ) - minetest.after(2, gestor.menu_principal, name) return - + + elseif fields.testar_email then - if gestor.bd:pegar("anticrash", "status_email") == "false" then + + if gestor.alerta_de_crash.enviar_email() then minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. default.gui_bg.. default.gui_bg_img.. - "label[0,0;AVISO \nO sistema de emails \nprecisa estar ativo para \nenviar email teste]" + "label[0,0;FEITO \nComando de envio feito.\nVeja o arquivo de relatorio\ngestor_envios_de_alerta.out]" + ) + else + minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. + default.gui_bg.. + default.gui_bg_img.. + "label[0,0;FALHA \nFaltam dados para\nrealizar o comando de envio.\n]" ) - minetest.after(2, gestor.menu_principal, name) - return end - local comando = "sendemail " - .."-s \""..gestor.bd:pegar("anticrash", "from_smtp")..":"..gestor.bd:pegar("anticrash", "from_smtp_port").."\" " - .."-xu \""..gestor.bd:pegar("anticrash", "from_login").."\" " - .."-xp \""..gestor.bd:pegar("anticrash", "from_senha").."\" " - .."-f \""..gestor.bd:pegar("anticrash", "from_email").."\" " - .."-t \""..gestor.bd:pegar("anticrash", "to_email").."\" " - .."-u \"Gestor - Email teste\" " - .."-m \"Essa mensagem foi um teste enviado pelo mod gestor\" " - .."-o message-charset=UTF-8 &" - minetest.show_formspec(name, "gestor:aviso", "size[4,1.8]".. - default.gui_bg.. - default.gui_bg_img.. - "label[0,0;AVISO \nEmail de teste enviado \nverifique a caixa de \nentrada do destinatario]" - ) - os.execute(comando) minetest.after(2, gestor.menu_principal, name) - return + end end end @@ -415,7 +358,6 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) local name = player:get_player_name() if fields.ok then - gestor.anticrash.serializar("status", "off") minetest.chat_send_all("*** Servidor desligando em 3 segundos. (Por "..name..")") minetest.after(3, minetest.chat_send_all, "*** Servidor Desligado") minetest.after(3, minetest.request_shutdown) @@ -432,9 +374,9 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) if fields.ok then -- adquirindo dados local pos = player:getpos() - local dados_estrutura = gestor.diretrizes.estruturas["centro"] + local dados_estrutura = gestor.estruturador.get_meta("centro") if not dados_estrutura then return minetest.chat_send_player(name, "Estrutura nao encontrada") end - local pos_c = {x=pos.x-(dados_estrutura[1]/2), y=pos.y-2, z=pos.z-(dados_estrutura[1]/2)} + local pos_c = {x=pos.x-(dados_estrutura.largura/2), y=pos.y-8, z=pos.z-(dados_estrutura.largura/2)} local n_spawn = {x=pos.x, y=pos.y+2, z=pos.z} -- Construir estrutura if gestor.estruturador.carregar(pos_c, "centro") == false then return minetest.chat_send_player(name, "Estrutura nao encontrada") end @@ -443,8 +385,8 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) name, -- Quem registra name, -- Quem vai ser o dono "Centro", -- Nome(etiqueta) da area - {x=pos.x-(dados_estrutura[1]/2)-10, y=2000, z=pos.z-(dados_estrutura[1]/2)-10}, -- um dos cantos opostos - {x=pos.x+(dados_estrutura[1]/2)+10, y=pos.y-60, z=pos.z+(dados_estrutura[1]/2)+10} -- outro dos cantos opostos + {x=pos.x-(dados_estrutura.largura/2)-100, y=2000, z=pos.z-(dados_estrutura.largura/2)-100}, -- um dos cantos opostos + {x=pos.x+(dados_estrutura.largura/2)+100, y=pos.y-60, z=pos.z+(dados_estrutura.largura/2)+100} -- outro dos cantos opostos ) if resp ~= true then minetest.chat_send_player(name, "Falha ao proteger: "..resp) end -- Salvar dados @@ -466,31 +408,36 @@ minetest.register_on_player_receive_fields(function(player, formname, fields) local name = player:get_player_name() if fields.ok then - -- Verificando se ja existe essa vila - local vila = escolha_vila[name] - if gestor.bd:verif("vilas", vila) then return minetest.chat_send_player(name, "Vila ja existente") end - -- Adquirindo dados + local pos = player:getpos() - local dados_estrutura = gestor.diretrizes.estruturas[vila] - if not dados_estrutura then return minetest.chat_send_player(name, "Estrutura nao encontrada") end - local pos_c = {x=pos.x-(dados_estrutura[1]/2), y=pos.y-2, z=pos.z-(dados_estrutura[1]/2)} - local n_spawn = {x=pos.x, y=pos.y+10, z=pos.z} - -- Construir estrutura - if gestor.estruturador.carregar(pos_c, vila) == false then return minetest.chat_send_player(name, "Estrutura nao encontrada") end + local vila = escolha_vila[name] + + -- Montar vila + local r = gestor.montar_vila(pos, vila) + if r ~= true then + return minetest.chat_send_player(name, r) + end + + + local dados_estrutura = gestor.estruturador.get_meta(vila) + local n_spawn = pos + -- Proteger area da estrutura local resp = gestor.proteger_area( name, -- Quem registra name, -- Quem vai ser o dono fields.vila, -- Nome(etiqueta) da area - {x=pos.x-(dados_estrutura[1]/2)-10, y=2000, z=pos.z-(dados_estrutura[1]/2)-10}, -- um dos cantos opostos - {x=pos.x+(dados_estrutura[1]/2)+10, y=pos.y-60, z=pos.z+(dados_estrutura[1]/2)+10} -- outro dos cantos opostos + {x=pos.x-(dados_estrutura.largura/2)-10, y=2000, z=pos.z-(dados_estrutura.largura/2)-50}, -- um dos cantos opostos + {x=pos.x+(dados_estrutura.largura/2)+10, y=pos.y-60, z=pos.z+(dados_estrutura.largura/2)+50} -- outro dos cantos opostos ) if resp ~= true then minetest.chat_send_player(name, "Falha ao proteger: "..resp) end + -- Salvar dados gestor.bd:salvar("vilas", vila, {nome=fields.nome_vila,pos=n_spawn}) + -- Finalizando player:moveto(n_spawn) - minetest.chat_send_player(name, "*** Vila construida quase pronta. Ajuste as entradas da vila e o ponto de TP(spawn) perto da bilheteria. Configure lojas e bancos existentes.") + minetest.chat_send_player(name, "*** Vila construida quase pronta. Ajuste as entradas da vila e o ponto de TP(spawn) perto da bilheteria.") end if fields.cancelar then gestor.menu_principal(name) diff --git a/protetor.lua b/protetor.lua index 8d5821f..bd23eab 100644 --- a/protetor.lua +++ b/protetor.lua @@ -1,13 +1,8 @@ ---[[ - Mod Gestor para Minetest - Gestor v1.0 Copyright (C) 2016 BrunoMine (https://github.com/BrunoMine) - - Recebeste uma cópia da GNU Lesser General - Public License junto com esse software, - se não, veja em . - - Protetor - ]] +-- +-- Mod gestor +-- +-- Protetor +-- -- Proteger uma area gestor.proteger_area = function(name, PlayerName, AreaName, pos1, pos2, silencio) diff --git a/textures/gestor.png b/textures/gestor.png index 532a84c..c3b7d36 100644 Binary files a/textures/gestor.png and b/textures/gestor.png differ diff --git a/vilas.lua b/vilas.lua new file mode 100644 index 0000000..3e4e326 --- /dev/null +++ b/vilas.lua @@ -0,0 +1,100 @@ +-- +-- Mod gestor +-- +-- Vilas +-- + + +-- Encontrar altura de um bloco alvo (em uma coluna) +local pegar_altura_solo = function(pos, alvos, amplitude) + if not pos then + minetest.log("error", "[Plagen] Tabela 'pos' nula (em pegar_altura_solo)") + return false + end + + local y = pos.y + amplitude + local resp = pos.y + while y >= pos.y - amplitude do + if table.maxn(minetest.find_nodes_in_area({x=pos.x,y=y,z=pos.z}, {x=pos.x,y=y,z=pos.z}, alvos)) == 1 then + resp = y + break + end + y = y - 1 + end + return resp +end + + +-- Comando para colocar vila +--[[ + Esse metodo monta uma vila no mapa e retorna + uma mensagem de erro quando ocorre alguma falha + ou algo impede + Retorno: + Pode ser true (booleano) caso de tudo certo e + uma string de mensagem de erro caso ocorra algum problema + Argumentos: + <> + ]] +gestor.montar_vila = function(pos, vila) + + -- Verificar dados + if not pos then + minetest.log("error", "[Plagen] Tabela 'pos' nula (em gestor.montar_vila)") + return "Erro interno" + end + if not vila then + minetest.log("error", "[Plagen] String de 'vila' nula (em gestor.montar_vila)") + return "Erro interno" + end + + -- Destacar tabela pos (evitar bugs) + pos = {x=pos.x, y=pos.y, z=pos.z} + + -- Verificando se ja existe essa vila + + if gestor.bd:verif("vilas", vila) then return "Vila ja existente" end + + -- Pegar material do solo + local p_solo = {x=pos.x, y=pos.y, z=pos.z} + p_solo.y = pegar_altura_solo(pos, {"default:dirt", "default:desert_sand"}, 15) + local node_solo = minetest.get_node(p_solo) + if pos == false then return "Impossivel encontrar solo" end + if node_solo.name == "default:dirt" then + p_solo.y = p_solo.y + 1 + elseif node_solo.name == "default:desert_sand" then + p_solo.y = p_solo.y + else + return "Solo inapropriado" + end + local solo = minetest.get_node({x=p_solo.x, y=p_solo.y, z=p_solo.z}).name + local subsolo = minetest.get_node({x=p_solo.x, y=p_solo.y-1, z=p_solo.z}).name + local rocha = "default:stone" + local materiais = {solo=solo,subsolo=subsolo,rocha=rocha} + if solo.name == "air" then return "Falha ao pegar solo" end + + + -- Adquirindo dados + + local dados = gestor.diretrizes.estruturas[vila] + + if not dados then return "Estrutura nao encontrada" end + + -- Planificar + if plagen.planificar(pos, "quadrada", dados[1]+2, 15, materiais, 15, true, true) ~= true then + return "Falha ao planificar" + end + + pos.y = pegar_altura_solo(pos, {solo}, 15) + 1 + + -- Variaveis auxiliares + + local minp = {x=pos.x-(dados[1]/2), y=pos.y-dados[3], z=pos.z-(dados[1]/2)} + + + -- Construir estrutura + + if gestor.estruturador.carregar(minp, vila) == false then return "Estrutura nao encontrada" end + + return true +end