From dd32a5a0c1838e3e464e8fdbe80a4d1a9c2f8235 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 13 Apr 2022 12:31:36 -0300 Subject: [PATCH 001/106] woodpecker --- .woodpecker.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .woodpecker.yml diff --git a/.woodpecker.yml b/.woodpecker.yml new file mode 100644 index 00000000..81af8efb --- /dev/null +++ b/.woodpecker.yml @@ -0,0 +1,26 @@ +pipeline: + publish: + image: plugins/docker + settings: + registry: registry.nulo.in + username: sutty + repo: registry.nulo.in/sutty/panel + tags: + - ${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH} + - latest + build_args: + - RUBY_VERSION=${RUBY_VERSION} + - RUBY_PATCH=${RUBY_PATCH} + - ALPINE_VERSION=${ALPINE_VERSION} + - BASE_IMAGE=registry.nulo.in/sutty/rails + purge: false + secrets: + - docker_password + when: + branch: antifascista + event: push +matrix: + include: + - ALPINE_VERSION: 3.13.10 + RUBY_VERSION: 2.7 + RUBY_PATCH: 6 From d9a5f7ff238b10795022b160dfbabb1716ce4c29 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 13 Apr 2022 12:34:42 -0300 Subject: [PATCH 002/106] actualizar pandoc --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index ecf43cbc..68ec6188 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ FROM registry.nulo.in/sutty/rails:3.13.6-2.7.5 -ARG PANDOC_VERSION=2.17.1.1 +ARG PANDOC_VERSION=2.18 ENV RAILS_ENV production # Instalar las dependencias, separamos la librería de base de datos para From 244a8de406b6afaf471da8934e4ce9bec300701c Mon Sep 17 00:00:00 2001 From: f Date: Wed, 13 Apr 2022 12:37:13 -0300 Subject: [PATCH 003/106] ramas que provocan deploys --- .woodpecker.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 81af8efb..db2b307d 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -17,7 +17,9 @@ pipeline: secrets: - docker_password when: - branch: antifascista + branch: + - rails + - panel.sutty.nl event: push matrix: include: From d9e2291f264b273b53ecfe579d7b7d610045752a Mon Sep 17 00:00:00 2001 From: f Date: Wed, 13 Apr 2022 16:44:52 -0300 Subject: [PATCH 004/106] usar argumentos --- Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 68ec6188..ac90a548 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,8 @@ -FROM registry.nulo.in/sutty/rails:3.13.6-2.7.5 +ARG RUBY_VERSION=2.7 +ARG RUBY_PATCH=6 +ARG ALPINE_VERSION=3.13.10 +ARG BASE_IMAGE=registry.nulo.in/sutty/rails +FROM ${BASE_IMAGE}:${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH} ARG PANDOC_VERSION=2.18 ENV RAILS_ENV production From 44de5227646c3ae0549e863bb5b2c0a9b0918c94 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 5 Oct 2022 18:44:23 -0300 Subject: [PATCH 005/106] soportar distributed press apiv0 #7839 --- app/models/deploy.rb | 15 ++++++++++ app/models/deploy_distributed_press.rb | 34 +++++++++++++++++++++++ app/models/deploy_local.rb | 38 ++++++++++++++++++-------- 3 files changed, 76 insertions(+), 11 deletions(-) create mode 100644 app/models/deploy_distributed_press.rb diff --git a/app/models/deploy.rb b/app/models/deploy.rb index 3f034ad5..c7e83539 100644 --- a/app/models/deploy.rb +++ b/app/models/deploy.rb @@ -75,6 +75,13 @@ class Deploy < ApplicationRecord r&.success? end + # Variables de entorno + # + # @return [Hash] + def local_env + @local_env ||= {} + end + private # @param [String] @@ -82,4 +89,12 @@ class Deploy < ApplicationRecord def readable_cmd(cmd) cmd.split(' -', 2).first.tr(' ', '_') end + + def deploy_local + @deploy_local ||= site.deploys.find_by(type: 'DeployLocal') + end + + def non_local_deploys + @non_local_deploys ||= site.deploys.where.not(type: 'DeployLocal') + end end diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb new file mode 100644 index 00000000..51788865 --- /dev/null +++ b/app/models/deploy_distributed_press.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +# Soportar Distributed Press APIv0 +# +# No se realiza ninguna acción porque el deploy se hace desde el plugin +# local. +class DeployDistributedPress < Deploy + store :values, accessors: %i[api_key hostname], coder: JSON + + def deploy; end + + def limit; end + + def size + deploy_local.size + end + + # TODO: Devolver hyper:// y otras + def url + "ipfs://#{hostname}/" + end + + # Devuelve variables de entorno para enviarle a DeployLocal + # + # @return [Hash] + def local_env + { + 'DISTRIBUTED_PRESS_PROJECT_DOMAIN' => hostname, + 'DISTRIBUTED_PRESS_API_KEY' => api_key + } + end + + def destination; end +end diff --git a/app/models/deploy_local.rb b/app/models/deploy_local.rb index 4fa588f5..4b22d728 100644 --- a/app/models/deploy_local.rb +++ b/app/models/deploy_local.rb @@ -50,21 +50,24 @@ class DeployLocal < Deploy end # Un entorno que solo tiene lo que necesitamos + # + # @return [Hash] def env # XXX: This doesn't support Windows paths :B paths = [File.dirname(`which bundle`), '/usr/bin', '/bin'] - { - 'HOME' => home_dir, - 'PATH' => paths.join(':'), - 'SPREE_API_KEY' => site.tienda_api_key, - 'SPREE_URL' => site.tienda_url, - 'AIRBRAKE_PROJECT_ID' => site.id.to_s, - 'AIRBRAKE_PROJECT_KEY' => site.airbrake_api_key, - 'JEKYLL_ENV' => Rails.env, - 'LANG' => ENV['LANG'], - 'YARN_CACHE_FOLDER' => yarn_cache_dir - } + # Las variables de entorno extra no pueden superponerse al local. + extra_env.merge({ + 'HOME' => home_dir, + 'PATH' => paths.join(':'), + 'SPREE_API_KEY' => site.tienda_api_key, + 'SPREE_URL' => site.tienda_url, + 'AIRBRAKE_PROJECT_ID' => site.id.to_s, + 'AIRBRAKE_PROJECT_KEY' => site.airbrake_api_key, + 'JEKYLL_ENV' => Rails.env, + 'LANG' => ENV['LANG'], + 'YARN_CACHE_FOLDER' => yarn_cache_dir + }) end def yarn_cache_dir @@ -112,4 +115,17 @@ class DeployLocal < Deploy def remove_destination! FileUtils.rm_rf destination end + + # Consigue todas las variables de entorno configuradas por otros + # deploys. + # + # @return [Hash] + def extra_env + @extra_env ||= + non_local_deploys.reduce({}) do |extra_env, deploy| + extra_env.tap do |e| + e.merge! deploy.local_env + end + end + end end From 2dc01cef9c1aedc27a46e4f898fabd216da4e1d1 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 4 Nov 2022 14:13:44 -0300 Subject: [PATCH 006/106] fix: actualizar contenedor a alpine 3.14 #8369 --- .woodpecker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index db2b307d..087b2e90 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -23,6 +23,6 @@ pipeline: event: push matrix: include: - - ALPINE_VERSION: 3.13.10 + - ALPINE_VERSION: 3.14.8 RUBY_VERSION: 2.7 RUBY_PATCH: 6 From d05b93d85ef3830e51131a6c09f48f47e2fd164b Mon Sep 17 00:00:00 2001 From: f Date: Fri, 18 Nov 2022 15:56:59 -0300 Subject: [PATCH 007/106] feat: poder modificar la url de distributed press --- app/models/deploy_distributed_press.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 51788865..a24ae62c 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -5,7 +5,7 @@ # No se realiza ninguna acción porque el deploy se hace desde el plugin # local. class DeployDistributedPress < Deploy - store :values, accessors: %i[api_key hostname], coder: JSON + store :values, accessors: %i[api_url api_key hostname], coder: JSON def deploy; end @@ -26,7 +26,8 @@ class DeployDistributedPress < Deploy def local_env { 'DISTRIBUTED_PRESS_PROJECT_DOMAIN' => hostname, - 'DISTRIBUTED_PRESS_API_KEY' => api_key + 'DISTRIBUTED_PRESS_API_KEY' => api_key, + 'DISTRIBUTED_PRESS_API_URL' => api_url } end From 3ec546eb82890490ad761014a23c6ea157c9fe1d Mon Sep 17 00:00:00 2001 From: f Date: Thu, 29 Dec 2022 14:55:30 -0300 Subject: [PATCH 008/106] fix: dependencias faltantes --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index ac90a548..871e6fb0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,7 @@ ENV RAILS_ENV production # principal RUN apk add --no-cache libxslt libxml2 postgresql-libs libssh2 \ rsync git jpegoptim vips tectonic oxipng git-lfs openssh-client \ - yarn daemonize ruby-webrick + yarn daemonize ruby-webrick postgresql-client dateutils file RUN gem install --no-document --no-user-install foreman RUN wget https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz -O - | tar --strip-components 1 -xvzf - pandoc-${PANDOC_VERSION}/bin/pandoc && mv /bin/pandoc /usr/bin/pandoc From 5da4c796e0e9fc3afe0767822e4ed6b78d5feb7c Mon Sep 17 00:00:00 2001 From: Maki Date: Tue, 17 Jan 2023 18:31:54 -0300 Subject: [PATCH 009/106] agrego toggler para distributed press --- app/models/site.rb | 2 +- .../deploys/_deploy_distributed_press.haml | 21 +++++++++++++++++++ config/locales/en.yml | 4 ++++ config/locales/es.yml | 4 ++++ 4 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 app/views/deploys/_deploy_distributed_press.haml diff --git a/app/models/site.rb b/app/models/site.rb index 638b3f47..fc012d7d 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -17,7 +17,7 @@ class Site < ApplicationRecord # TODO: Hacer que los diferentes tipos de deploy se auto registren # @see app/services/site_service.rb - DEPLOYS = %i[local private www zip hidden_service].freeze + DEPLOYS = %i[local private www zip hidden_service distributed_press].freeze validates :name, uniqueness: true, hostname: { allow_root_label: true diff --git a/app/views/deploys/_deploy_distributed_press.haml b/app/views/deploys/_deploy_distributed_press.haml new file mode 100644 index 00000000..d7d54db0 --- /dev/null +++ b/app/views/deploys/_deploy_distributed_press.haml @@ -0,0 +1,21 @@ +-# Publicar a la web distribuida + +.row + .col + = deploy.hidden_field :id + = deploy.hidden_field :type + .custom-control.custom-switch + -# + El checkbox invierte la lógica de destrucción porque queremos + crear el deploy si está activado y destruirlo si está + desactivado. + = deploy.check_box :_destroy, + { checked: deploy.object.persisted?, class: 'custom-control-input' }, + '0', '1' + = deploy.label :_destroy, class: 'custom-control-label' do + %h3= t('.title') + = sanitize_markdown t('.help', public_url: deploy.object.site.url), + tags: %w[p strong em a] + + +%hr/ diff --git a/config/locales/en.yml b/config/locales/en.yml index 530a9381..e7fb4f76 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -248,6 +248,10 @@ en: Only accessible through [Tor Browser](https://www.torproject.org/download/) + deploy_distributed_press: + title: 'Publish on Distributed Press' + help: | + ipfs stats: index: title: Statistics diff --git a/config/locales/es.yml b/config/locales/es.yml index eaa23137..18cf5326 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -253,6 +253,10 @@ es: Sólo será accesible a través del [Navegador Tor](https://www.torproject.org/es/download/). + deploy_distributed_press: + title: 'Alojar en la web distribuida' + help: | + Es para que esté en la web distribuida stats: index: title: Estadísticas From 67c0b29029d5f8731f0eb82c6b2c8c7d02e333e7 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 20 Jan 2023 18:22:08 -0300 Subject: [PATCH 010/106] feat: almacenar y renovar tokens de distributed press --- Gemfile | 1 + Gemfile.lock | 40 ++++++++++- Procfile | 1 + .../renew_distributed_press_tokens_job.rb | 17 +++++ app/models/distributed_press_publisher.rb | 68 +++++++++++++++++++ ...5420_create_distributed_press_publisher.rb | 14 ++++ lib/tasks/distributed_press.rake | 10 +++ monit.conf | 5 ++ 8 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 app/jobs/renew_distributed_press_tokens_job.rb create mode 100644 app/models/distributed_press_publisher.rb create mode 100644 db/migrate/20230119165420_create_distributed_press_publisher.rb create mode 100644 lib/tasks/distributed_press.rake diff --git a/Gemfile b/Gemfile index 2b304ee0..f317487b 100644 --- a/Gemfile +++ b/Gemfile @@ -38,6 +38,7 @@ gem 'commonmarker' gem 'devise' gem 'devise-i18n' gem 'devise_invitable' +gem 'distributed-press-api-client', '~> 0.2.0' gem 'email_address', git: 'https://github.com/fauno/email_address', branch: 'i18n' gem 'exception_notification' gem 'fast_blank' diff --git a/Gemfile.lock b/Gemfile.lock index 8df2d77e..cdfe7183 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -124,6 +124,7 @@ GEM xpath (>= 2.0, < 4.0) chartkick (4.1.2) childprocess (4.1.0) + climate_control (1.2.0) coderay (1.1.3) colorator (1.1.0) commonmarker (0.21.2-x86_64-linux-musl) @@ -162,12 +163,45 @@ GEM devise_invitable (2.0.5) actionmailer (>= 5.0) devise (>= 4.6) + distributed-press-api-client (0.2.0) + addressable (~> 2.3, >= 2.3.0) + climate_control + dry-schema + httparty (~> 0.18) + json (~> 2.1, >= 2.1.0) + jwt (~> 2.6.0) dotenv (2.7.6) dotenv-rails (2.7.6) dotenv (= 2.7.6) railties (>= 3.2) down (5.2.4) addressable (~> 2.8) + dry-configurable (1.0.1) + dry-core (~> 1.0, < 2) + zeitwerk (~> 2.6) + dry-core (1.0.0) + concurrent-ruby (~> 1.0) + zeitwerk (~> 2.6) + dry-inflector (1.0.0) + dry-initializer (3.1.1) + dry-logic (1.5.0) + concurrent-ruby (~> 1.0) + dry-core (~> 1.0, < 2) + zeitwerk (~> 2.6) + dry-schema (1.13.0) + concurrent-ruby (~> 1.0) + dry-configurable (~> 1.0, >= 1.0.1) + dry-core (~> 1.0, < 2) + dry-initializer (~> 3.0) + dry-logic (>= 1.5, < 2) + dry-types (>= 1.7, < 2) + zeitwerk (~> 2.6) + dry-types (1.7.0) + concurrent-ruby (~> 1.0) + dry-core (~> 1.0, < 2) + dry-inflector (~> 1.0, < 2) + dry-logic (>= 1.4, < 2) + zeitwerk (~> 2.6) ed25519 (1.2.4-x86_64-linux-musl) editorial-autogestiva-jekyll-theme (0.3.4) jekyll (~> 4) @@ -244,8 +278,8 @@ GEM thor hiredis (0.6.3-x86_64-linux-musl) http_parser.rb (0.8.0-x86_64-linux-musl) - httparty (0.18.1) - mime-types (~> 3.0) + httparty (0.21.0) + mini_mime (>= 1.0.0) multi_xml (>= 0.5.2) i18n (1.8.11) concurrent-ruby (~> 1.0) @@ -320,6 +354,7 @@ GEM jekyll-write-and-commit-changes (0.2.1) jekyll (~> 4) rugged (~> 1) + jwt (2.6.0) kaminari (1.2.1) activesupport (>= 4.1.0) kaminari-actionview (= 1.2.1) @@ -669,6 +704,7 @@ DEPENDENCIES devise devise-i18n devise_invitable + distributed-press-api-client (~> 0.2.0) dotenv-rails down ed25519 diff --git a/Procfile b/Procfile index b308ffd5..1a4580d3 100644 --- a/Procfile +++ b/Procfile @@ -5,3 +5,4 @@ blazer_1h: bundle exec rake blazer:run_checks SCHEDULE="1 hour" blazer_1d: bundle exec rake blazer:run_checks SCHEDULE="1 day" blazer: bundle exec rake blazer:send_failing_checks prometheus: bundle exec prometheus_exporter -b 0.0.0.0 --prefix "sutty_" +distributed_press_renew_tokens: bundle exec rake distributed_press:tokens:renew diff --git a/app/jobs/renew_distributed_press_tokens_job.rb b/app/jobs/renew_distributed_press_tokens_job.rb new file mode 100644 index 00000000..5664d9fa --- /dev/null +++ b/app/jobs/renew_distributed_press_tokens_job.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +# Renueva los tokens de Distributed Press antes que se venzan, +# activando los callbacks que hacen que se refresque el token. +class RenewDistributedPressTokensJob < ApplicationJob + # Renueva todos los tokens a punto de vencer o informa el error sin + # detener la tarea si algo pasa. + def perform + DistributedPressPublisher.with_about_to_expire_tokens.find_each do |publisher| + publisher.touch + rescue DistributedPress::V1::Error => e + data = { instance: publisher.instance, expires_at: publisher.client.token.expires_at } + + ExceptionNotifier.notify_exception(e, data: data) + end + end +end diff --git a/app/models/distributed_press_publisher.rb b/app/models/distributed_press_publisher.rb new file mode 100644 index 00000000..c120811e --- /dev/null +++ b/app/models/distributed_press_publisher.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +require 'distributed_press/v1' + +# Almacena el token de autenticación y la URL, por ahora solo vamos +# a tener uno, pero queda abierta la posibilidad de agregar más. +class DistributedPressPublisher < ApplicationRecord + # Cifrar la información del token en la base de datos + has_encrypted :token + + # La instancia es única + validates_uniqueness_of :instance + + # El token es necesario + validates_presence_of :token + + # Mantener la fecha de vencimiento actualizada + before_save :update_expires_at_from_token!, :update_token_from_client! + + # Devuelve todos los tokens que vencen en una hora + scope :with_about_to_expire_tokens, -> do + where('expires_at > ? and expires_at < ?', Time.now, Time.now + 1.hour) + end + + # Al cambiar el token genera un cliente nuevo + # + # @return [String] + def token=(new_token) + @client = nil + super + end + + # Al cambiar la instancia genera un cliente nuevo + # + # @return [String] + def instance=(new_instance) + @client = nil + super + end + + # Instancia un cliente de Distributed Press a partir del token. Al + # cargar un token a punto de vencer se renueva automáticamente. + # + # @return [DistributedPress::V1::Client] + def client + @client ||= DistributedPress::V1::Client.new(url: instance, token: token) + end + + private + + # Actualiza o desactiva la fecha de vencimiento a partir de la + # información del token. + # + # @return [nil] + def update_expires_at_from_token! + self.expires_at = client.token.forever? ? nil : client.token.expires_at + nil + end + + # Actualiza el token a partir del cliente, que ya actualiza el token + # automáticamente. + # + # @return [nil] + def update_token_from_client! + self.token = client.token.to_s + nil + end +end diff --git a/db/migrate/20230119165420_create_distributed_press_publisher.rb b/db/migrate/20230119165420_create_distributed_press_publisher.rb new file mode 100644 index 00000000..8d8de37a --- /dev/null +++ b/db/migrate/20230119165420_create_distributed_press_publisher.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Crea la tabla de publishers de Distributed Press que contiene las +# instancias y tokens +class CreateDistributedPressPublisher < ActiveRecord::Migration[6.1] + def change + create_table :distributed_press_publishers do |t| + t.timestamps + t.string :instance, unique: true + t.text :token_ciphertext, null: false + t.datetime :expires_at, null: true + end + end +end diff --git a/lib/tasks/distributed_press.rake b/lib/tasks/distributed_press.rake new file mode 100644 index 00000000..8ba270ec --- /dev/null +++ b/lib/tasks/distributed_press.rake @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +namespace :distributed_press do + namespace :tokens do + desc 'Renew tokens' + task renew: :environment do + RenewDistributedPressTokensJob.perform_now + end + end +end diff --git a/monit.conf b/monit.conf index 96c08d8a..b785964d 100644 --- a/monit.conf +++ b/monit.conf @@ -25,3 +25,8 @@ check program blazer with path "/usr/local/bin/sutty blazer" every 61 cycles if status != 0 then alert + +check program distributed_press_tokens_renew + with path "/usr/bin/foreman run -f /srv/Procfile -d /srv distributed_press_tokens_renew" as uid "rails" gid "www-data" + every "0 3 * * *" + if status != 0 then alert From cbf7b5892746b544668c6043915da783a13b00d0 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 20 Jan 2023 18:28:29 -0300 Subject: [PATCH 011/106] fixup! feat: almacenar y renovar tokens de distributed press --- app/models/distributed_press_publisher.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/distributed_press_publisher.rb b/app/models/distributed_press_publisher.rb index c120811e..610d698d 100644 --- a/app/models/distributed_press_publisher.rb +++ b/app/models/distributed_press_publisher.rb @@ -18,9 +18,9 @@ class DistributedPressPublisher < ApplicationRecord before_save :update_expires_at_from_token!, :update_token_from_client! # Devuelve todos los tokens que vencen en una hora - scope :with_about_to_expire_tokens, -> do + scope :with_about_to_expire_tokens, lambda { where('expires_at > ? and expires_at < ?', Time.now, Time.now + 1.hour) - end + } # Al cambiar el token genera un cliente nuevo # From 932355fa2e331ac7e4bf142e21b1b879aa161a39 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 20 Jan 2023 20:34:27 -0300 Subject: [PATCH 012/106] feat: crear y publicar el sitio en distributed press v1 --- app/models/deploy_distributed_press.rb | 143 ++++++++++++++++++---- app/models/distributed_press_publisher.rb | 5 + 2 files changed, 125 insertions(+), 23 deletions(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index a24ae62c..09ba0364 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -1,13 +1,43 @@ # frozen_string_literal: true -# Soportar Distributed Press APIv0 -# -# No se realiza ninguna acción porque el deploy se hace desde el plugin -# local. -class DeployDistributedPress < Deploy - store :values, accessors: %i[api_url api_key hostname], coder: JSON +require 'distributed_press/v1/client/auth' +require 'distributed_press/v1/client/site' - def deploy; end +# Soportar Distributed Press APIv1 +# +# Usa tokens de publicación efímeros para todas las acciones. +# +# Al ser creado, genera el sitio en la instancia de Distributed Press +# configurada y almacena el ID. +# +# Al ser publicado, envía los archivos en un tarball y actualiza la +# información. +class DeployDistributedPress < Deploy + store :values, accessors: %i[hostname remote_site_id remote_info], coder: JSON + + before_create :create_remote_site! + + # Actualiza la información y luego envía los cambios + # + # @param :output [Bool] + # @return [Bool] + def deploy + time_start + + status = false + + site_client.tap do |c| + update remote_info: c.show(publishing_site).to_h + + status = c.publish(publishing_site, deploy_local.destination) + end + + time_stop + + create_stat! status + + status + end def limit; end @@ -15,21 +45,88 @@ class DeployDistributedPress < Deploy deploy_local.size end - # TODO: Devolver hyper:// y otras - def url - "ipfs://#{hostname}/" - end - - # Devuelve variables de entorno para enviarle a DeployLocal - # - # @return [Hash] - def local_env - { - 'DISTRIBUTED_PRESS_PROJECT_DOMAIN' => hostname, - 'DISTRIBUTED_PRESS_API_KEY' => api_key, - 'DISTRIBUTED_PRESS_API_URL' => api_url - } - end - def destination; end + + private + + # El cliente de la API + # + # TODO: cuando soportemos más, tiene que haber una relación entre + # DeployDistributedPress y DistributedPressPublisher. + # + # @return [DistributedPressPublisher] + def publisher + @publisher ||= DistributedPressPublisher.first + end + + # El cliente de autenticación se encarga de intercambiar un token por + # otro + # + # @return [DistributedPress::V1::Client::Auth] + def auth_client + DistributedPress::V1::Client::Auth.new(publisher.client) + end + + # Genera un token con permisos de publicación + # + # @return [DistributedPress::V1::Schemas::NewTokenPayload] + def publishing_token_payload + DistributedPress::V1::Schemas::NewTokenPayload.new.call(capabilities: %w[publisher]) + end + + # Genera un token efímero para publicar el sitio + # + # @return [DistributedPress::V1::Token] + def publishing_token + auth_client.exchange(publishing_token_payload) + end + + # Genera un cliente para publicar el sitio + # + # @return [DistributedPress::V1::Client] + def publishing_client + DistributedPress::V1::Client.new(url: publisher.instance, token: publishing_token) + end + + # El cliente para actualizar el sitio + # + # @return [DistributedPress::V1::Client::Site] + def site_client + DistributedPress::V1::Client::Site.new(publishing_client) + end + + # Genera el esquema de datos para poder publicar el sitio + # + # @return [DistributedPress::V1::Schemas::PublishingSite] + def publishing_site + DistributedPress::V1::Schemas::PublishingSite.new.call(id: remote_site_id) + end + + # Genera el esquema de datos para crear el sitio + # + # @return [DistributedPressPublisher::V1::Schemas::NewSite] + def create_site + DistributedPress::V1::Schemas::NewSite.new.call(domain: hostname, protocols: { http: true, ipfs: true, hyper: true }) + end + + # Crea el sitio en la instancia con el hostname especificado + # + # @return [nil] + def create_remote_site! + created_site = site_client.create(create_site) + + self.remote_site_id = created_site[:id] + self.remote_info = created_site.to_h + + nil + end + + # Registra lo que sucedió + # + # @param status [Bool] + # @return [nil] + def create_stat!(status) + build_stats.create action: publisher.to_s, seconds: time_spent_in_seconds, bytes: size, status: status + nil + end end diff --git a/app/models/distributed_press_publisher.rb b/app/models/distributed_press_publisher.rb index 610d698d..5358e738 100644 --- a/app/models/distributed_press_publisher.rb +++ b/app/models/distributed_press_publisher.rb @@ -46,6 +46,11 @@ class DistributedPressPublisher < ApplicationRecord @client ||= DistributedPress::V1::Client.new(url: instance, token: token) end + # @return [String] + def to_s + "Distributed Press <#{instance}>" + end + private # Actualiza o desactiva la fecha de vencimiento a partir de la From 8006bd03538dee1285ef7746db382958b6cabce7 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 20 Jan 2023 20:35:39 -0300 Subject: [PATCH 013/106] fix: permitir modificar el token estos parches hacian que no se pueda modificar el token --- app/models/distributed_press_publisher.rb | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/app/models/distributed_press_publisher.rb b/app/models/distributed_press_publisher.rb index 5358e738..acfc4226 100644 --- a/app/models/distributed_press_publisher.rb +++ b/app/models/distributed_press_publisher.rb @@ -22,22 +22,6 @@ class DistributedPressPublisher < ApplicationRecord where('expires_at > ? and expires_at < ?', Time.now, Time.now + 1.hour) } - # Al cambiar el token genera un cliente nuevo - # - # @return [String] - def token=(new_token) - @client = nil - super - end - - # Al cambiar la instancia genera un cliente nuevo - # - # @return [String] - def instance=(new_instance) - @client = nil - super - end - # Instancia un cliente de Distributed Press a partir del token. Al # cargar un token a punto de vencer se renueva automáticamente. # From b28d7946460d8bed6400a6f13d6f0911a12a8f53 Mon Sep 17 00:00:00 2001 From: f Date: Mon, 23 Jan 2023 18:39:10 -0300 Subject: [PATCH 014/106] =?UTF-8?q?feat:=20no=20vamos=20a=20expedir=20toke?= =?UTF-8?q?ns=20ef=C3=ADmeros=20por=20ahora?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/deploy_distributed_press.rb | 31 +------------------------- 1 file changed, 1 insertion(+), 30 deletions(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 09ba0364..38cb59e3 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -59,40 +59,11 @@ class DeployDistributedPress < Deploy @publisher ||= DistributedPressPublisher.first end - # El cliente de autenticación se encarga de intercambiar un token por - # otro - # - # @return [DistributedPress::V1::Client::Auth] - def auth_client - DistributedPress::V1::Client::Auth.new(publisher.client) - end - - # Genera un token con permisos de publicación - # - # @return [DistributedPress::V1::Schemas::NewTokenPayload] - def publishing_token_payload - DistributedPress::V1::Schemas::NewTokenPayload.new.call(capabilities: %w[publisher]) - end - - # Genera un token efímero para publicar el sitio - # - # @return [DistributedPress::V1::Token] - def publishing_token - auth_client.exchange(publishing_token_payload) - end - - # Genera un cliente para publicar el sitio - # - # @return [DistributedPress::V1::Client] - def publishing_client - DistributedPress::V1::Client.new(url: publisher.instance, token: publishing_token) - end - # El cliente para actualizar el sitio # # @return [DistributedPress::V1::Client::Site] def site_client - DistributedPress::V1::Client::Site.new(publishing_client) + DistributedPress::V1::Client::Site.new(publisher.client) end # Genera el esquema de datos para poder publicar el sitio From ebf1390bdf962c49f2fab7a914a3944060c0c461 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 26 Jan 2023 15:41:54 -0300 Subject: [PATCH 015/106] fix: actualizar api --- Gemfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile.lock b/Gemfile.lock index cdfe7183..534ad298 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -163,7 +163,7 @@ GEM devise_invitable (2.0.5) actionmailer (>= 5.0) devise (>= 4.6) - distributed-press-api-client (0.2.0) + distributed-press-api-client (0.2.1) addressable (~> 2.3, >= 2.3.0) climate_control dry-schema From 928bc45920cfbf10a46e088ccbbcece043d24dd5 Mon Sep 17 00:00:00 2001 From: f Date: Mon, 6 Feb 2023 16:09:51 -0300 Subject: [PATCH 016/106] feat: usar pnpm si existe relacionado con sutty/jekyll/sutty-base-jekyll-theme#53 --- Dockerfile | 2 ++ app/models/deploy_local.rb | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/Dockerfile b/Dockerfile index ecf43cbc..b2f96612 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,8 @@ RUN apk add --no-cache libxslt libxml2 postgresql-libs libssh2 \ RUN gem install --no-document --no-user-install foreman RUN wget https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz -O - | tar --strip-components 1 -xvzf - pandoc-${PANDOC_VERSION}/bin/pandoc && mv /bin/pandoc /usr/bin/pandoc +RUN apk add npm && npm install -g pnpm && apk del npm + VOLUME "/srv" EXPOSE 3000 diff --git a/app/models/deploy_local.rb b/app/models/deploy_local.rb index 4b22d728..51baf492 100644 --- a/app/models/deploy_local.rb +++ b/app/models/deploy_local.rb @@ -15,6 +15,7 @@ class DeployLocal < Deploy def deploy return false unless mkdir return false unless yarn + return false unless pnpm return false unless bundle jekyll_build @@ -74,6 +75,10 @@ class DeployLocal < Deploy Rails.root.join('_yarn_cache').to_s end + def pnpm_cache_dir + Rails.root.join('_pnpm_cache').to_s + end + def yarn_lock File.join(site.path, 'yarn.lock') end @@ -82,6 +87,14 @@ class DeployLocal < Deploy File.exist? yarn_lock end + def pnpm_lock + File.join(site.path, 'pnpm-lock.yaml') + end + + def pnpm_lock? + File.exist? pnpm_lock + end + def gem run %(gem install bundler --no-document) end @@ -93,6 +106,13 @@ class DeployLocal < Deploy run 'yarn install --production' end + def pnpm + return true unless pnpm_lock? + + run %(pnpm config set store-dir "#{pnpm_cache_dir}") + run 'pnpm install --production' + end + def bundle if Rails.env.production? run %(bundle install --no-cache --path="#{gems_dir}") From a73100a436a283533236989c58f162c0fe8dbd4f Mon Sep 17 00:00:00 2001 From: f Date: Mon, 6 Feb 2023 16:16:27 -0300 Subject: [PATCH 017/106] fix: pnpm se instala localmente --- app/models/deploy_local.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/deploy_local.rb b/app/models/deploy_local.rb index 51baf492..e4845d7c 100644 --- a/app/models/deploy_local.rb +++ b/app/models/deploy_local.rb @@ -55,7 +55,7 @@ class DeployLocal < Deploy # @return [Hash] def env # XXX: This doesn't support Windows paths :B - paths = [File.dirname(`which bundle`), '/usr/bin', '/bin'] + paths = [File.dirname(`which bundle`), '/usr/local/bin', '/usr/bin', '/bin'] # Las variables de entorno extra no pueden superponerse al local. extra_env.merge({ From 464ff4841b68affaa694ab0e8e348035cf565a38 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 7 Feb 2023 18:15:25 -0300 Subject: [PATCH 018/106] feat: textos para el panel --- config/locales/en.yml | 16 ++++++++++++++-- config/locales/es.yml | 16 ++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/config/locales/en.yml b/config/locales/en.yml index e7fb4f76..2bbf58ea 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -249,9 +249,21 @@ en: Only accessible through [Tor Browser](https://www.torproject.org/download/) deploy_distributed_press: - title: 'Publish on Distributed Press' + title: 'Publish to the distributed Web' help: | - ipfs + Make your site available through peer-to-peer protocols, + Inter-Planetary File System (IPFS), Hypercore, and via + BitTorrent, so your site is more resilient and can be available + offline, including in community mesh networks. + + **Important:** Only use this option if you would like your data + to be permanently available. If you decide to undo this + selection, a cleared version of the site will be shared in its + place. However, it is possible that nodes on the distributed + storage network may continue retaining copies of the data + indefinitely. + + [Learn more](#) stats: index: title: Statistics diff --git a/config/locales/es.yml b/config/locales/es.yml index 18cf5326..e3b24957 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -254,9 +254,21 @@ es: Sólo será accesible a través del [Navegador Tor](https://www.torproject.org/es/download/). deploy_distributed_press: - title: 'Alojar en la web distribuida' + title: 'Publicar a la Web distribuida' help: | - Es para que esté en la web distribuida + Utiliza protocolos de pares, Inter-Planetary File System (IPFS), + Hypercore y torrents, para que tu sitio sea más resiliente y + esté disponible _offline_, inclusive en redes _mesh_ + comunitarias. + + **Importante:** Sólo usa esta opción si te parece correcto que + tu contenido esté disponible permanentemente. Cuando elijas + des-hacer esta acción, una versión "vacía" del sitio será + compartida en su lugar. Sin embargo, es posible que algunos + nodos en la red de almacenamiento distribuida puedan retener + copias de tu contenido indefinidamente. + + [Saber más](#) stats: index: title: Estadísticas From 9661a34a04396c647f5ad1fe5d6ea75fc3b513ac Mon Sep 17 00:00:00 2001 From: f Date: Wed, 8 Feb 2023 09:38:36 -0300 Subject: [PATCH 019/106] fix: faltaban algunos require --- Gemfile | 2 +- Gemfile.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index f317487b..694358a6 100644 --- a/Gemfile +++ b/Gemfile @@ -38,7 +38,7 @@ gem 'commonmarker' gem 'devise' gem 'devise-i18n' gem 'devise_invitable' -gem 'distributed-press-api-client', '~> 0.2.0' +gem 'distributed-press-api-client', '~> 0.2.1' gem 'email_address', git: 'https://github.com/fauno/email_address', branch: 'i18n' gem 'exception_notification' gem 'fast_blank' diff --git a/Gemfile.lock b/Gemfile.lock index 534ad298..5c074a7b 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -704,7 +704,7 @@ DEPENDENCIES devise devise-i18n devise_invitable - distributed-press-api-client (~> 0.2.0) + distributed-press-api-client (~> 0.2.1) dotenv-rails down ed25519 From 6683f80aba504c2edca9bcb4ca5f3ce4f24eba9c Mon Sep 17 00:00:00 2001 From: f Date: Wed, 8 Feb 2023 11:55:07 -0300 Subject: [PATCH 020/106] fix: no fallar si tarda mucho dp --- Gemfile | 2 +- Gemfile.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Gemfile b/Gemfile index 694358a6..7f4cc6ca 100644 --- a/Gemfile +++ b/Gemfile @@ -38,7 +38,7 @@ gem 'commonmarker' gem 'devise' gem 'devise-i18n' gem 'devise_invitable' -gem 'distributed-press-api-client', '~> 0.2.1' +gem 'distributed-press-api-client', '~> 0.2.2' gem 'email_address', git: 'https://github.com/fauno/email_address', branch: 'i18n' gem 'exception_notification' gem 'fast_blank' diff --git a/Gemfile.lock b/Gemfile.lock index 5c074a7b..b5b6fd18 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -163,7 +163,7 @@ GEM devise_invitable (2.0.5) actionmailer (>= 5.0) devise (>= 4.6) - distributed-press-api-client (0.2.1) + distributed-press-api-client (0.2.2) addressable (~> 2.3, >= 2.3.0) climate_control dry-schema @@ -704,7 +704,7 @@ DEPENDENCIES devise devise-i18n devise_invitable - distributed-press-api-client (~> 0.2.1) + distributed-press-api-client (~> 0.2.2) dotenv-rails down ed25519 From ccfd77d9568dce55ea8ce29ea114b2487f7bc0b9 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 8 Feb 2023 17:08:02 -0300 Subject: [PATCH 021/106] =?UTF-8?q?feat:=20guardar=20un=20log=20y=20mostra?= =?UTF-8?q?rlo=20en=20output=20tambi=C3=A9n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/deploy_distributed_press.rb | 24 ++++++++++++++++++----- app/models/distributed_press_publisher.rb | 22 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 38cb59e3..d805e923 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -22,19 +22,32 @@ class DeployDistributedPress < Deploy # @param :output [Bool] # @return [Bool] def deploy + status = false + log = [] + time_start - status = false - site_client.tap do |c| + stdout = Thread.new(publisher.logger_out) do |io| + until io.eof? + line = io.gets + + puts line if output + log << line + end + end + update remote_info: c.show(publishing_site).to_h status = c.publish(publishing_site, deploy_local.destination) + + publisher.logger.close + stdout.join end time_stop - create_stat! status + create_stat! status, log.join status end @@ -95,9 +108,10 @@ class DeployDistributedPress < Deploy # Registra lo que sucedió # # @param status [Bool] + # @param log [String] # @return [nil] - def create_stat!(status) - build_stats.create action: publisher.to_s, seconds: time_spent_in_seconds, bytes: size, status: status + def create_stat!(status, log) + build_stats.create action: publisher.to_s,log: log, seconds: time_spent_in_seconds, bytes: size, status: status nil end end diff --git a/app/models/distributed_press_publisher.rb b/app/models/distributed_press_publisher.rb index acfc4226..089f63c6 100644 --- a/app/models/distributed_press_publisher.rb +++ b/app/models/distributed_press_publisher.rb @@ -8,6 +8,11 @@ class DistributedPressPublisher < ApplicationRecord # Cifrar la información del token en la base de datos has_encrypted :token + # La salida del log + # + # @return [IO] + attr_reader :logger_out + # La instancia es única validates_uniqueness_of :instance @@ -27,7 +32,7 @@ class DistributedPressPublisher < ApplicationRecord # # @return [DistributedPress::V1::Client] def client - @client ||= DistributedPress::V1::Client.new(url: instance, token: token) + @client ||= DistributedPress::V1::Client.new(url: instance, token: token, logger: logger) end # @return [String] @@ -35,8 +40,23 @@ class DistributedPressPublisher < ApplicationRecord "Distributed Press <#{instance}>" end + # @return [Logger] + def logger + @logger ||= + begin + @logger_out, @logger_in = IO.pipe + ::Logger.new @logger_in, formatter: formatter + end + end + private + def formatter + @formatter ||= lambda do |_, _, _, msg| + "#{msg}\n" + end + end + # Actualiza o desactiva la fecha de vencimiento a partir de la # información del token. # From 89f5ed90ebe60b2b9132c8bdad1e9ee3a310e970 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 8 Feb 2023 17:44:35 -0300 Subject: [PATCH 022/106] =?UTF-8?q?fix:=20link=20a=20saber=20m=C3=A1s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/locales/en.yml | 2 +- config/locales/es.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/config/locales/en.yml b/config/locales/en.yml index 2bbf58ea..f37afa7c 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -263,7 +263,7 @@ en: storage network may continue retaining copies of the data indefinitely. - [Learn more](#) + [Learn more](https://ffdweb.org/building-distributed-press-a-publishing-tool-for-the-decentralized-web/) stats: index: title: Statistics diff --git a/config/locales/es.yml b/config/locales/es.yml index e3b24957..fef3b6eb 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -268,7 +268,7 @@ es: nodos en la red de almacenamiento distribuida puedan retener copias de tu contenido indefinidamente. - [Saber más](#) + [Saber más (en inglés)](https://ffdweb.org/building-distributed-press-a-publishing-tool-for-the-decentralized-web/) stats: index: title: Estadísticas From 15e6696bcf7b645b59a246c8fcd908db9671ad74 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 8 Feb 2023 18:49:37 -0300 Subject: [PATCH 023/106] feat: un deploy puede tener varias urls --- app/models/deploy_distributed_press.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index d805e923..d3474d50 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -60,6 +60,15 @@ class DeployDistributedPress < Deploy def destination; end + # Devuelve las URLs de todos los protocolos + def urls + remote_info[:links].values.map do |protocol| + [ protocol[:link], protocol[:gateway] ] + end.flatten.compact.select do |link| + link.include? '://' + end + end + private # El cliente de la API From 7ff284d547cd8e0ce8f0f30d4172db182e439430 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 8 Feb 2023 18:52:48 -0300 Subject: [PATCH 024/106] =?UTF-8?q?feat:=20texto=20para=20el=20correo=20de?= =?UTF-8?q?=20notificaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/locales/en.yml | 4 ++++ config/locales/es.yml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/config/locales/en.yml b/config/locales/en.yml index f37afa7c..ac8d7289 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -102,6 +102,10 @@ en: title: Alternative domain name success: Success! error: Error + deploy_distributed_press: + title: Distributed Web + success: Success! + error: Error help: You can contact us by replying to this e-mail maintenance_mailer: notice: diff --git a/config/locales/es.yml b/config/locales/es.yml index fef3b6eb..335fca66 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -102,6 +102,10 @@ es: title: Dominio alternativo success: ¡Éxito! error: Hubo un error + deploy_distributed_press: + title: Web distribuida + success: ¡Éxito! + error: Hubo un error help: Por cualquier duda, responde este correo para contactarte con nosotres. maintenance_mailer: notice: From 3f7b2484d04bee63bff7877f746721703043e217 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 9 Feb 2023 20:01:22 -0300 Subject: [PATCH 025/106] feat: crear temporalmente los dominios en njalla el problema es que no podemos delegar `_dnslink.*.sutty.nl` hacia distributed press, con lo que es necesario crear un subdominio por cada sitio que lo active. --- Gemfile | 1 + Gemfile.lock | 4 ++++ app/models/deploy_distributed_press.rb | 18 ++++++++++++++++++ app/models/distributed_press_publisher.rb | 7 +++++++ 4 files changed, 30 insertions(+) diff --git a/Gemfile b/Gemfile index 7f4cc6ca..8f742348 100644 --- a/Gemfile +++ b/Gemfile @@ -39,6 +39,7 @@ gem 'devise' gem 'devise-i18n' gem 'devise_invitable' gem 'distributed-press-api-client', '~> 0.2.2' +gem 'njalla-api-client' gem 'email_address', git: 'https://github.com/fauno/email_address', branch: 'i18n' gem 'exception_notification' gem 'fast_blank' diff --git a/Gemfile.lock b/Gemfile.lock index b5b6fd18..6469b2db 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -419,6 +419,9 @@ GEM nokogiri (1.12.5-x86_64-linux-musl) mini_portile2 (~> 2.6.1) racc (~> 1.4) + njalla-api-client (0.1.0) + dry-schema + httparty (~> 0.18) orm_adapter (0.5.0) parallel (1.21.0) parser (3.0.2.0) @@ -741,6 +744,7 @@ DEPENDENCIES minima mobility net-ssh + njalla-api-client nokogiri pg pg_search diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index d3474d50..6f2b2c78 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -111,6 +111,12 @@ class DeployDistributedPress < Deploy self.remote_site_id = created_site[:id] self.remote_info = created_site.to_h + # XXX: Esto depende de nuestro DNS actual, cuando lo migremos hay + # que eliminarlo. + self.remote_info['njalla'] = {} + self.remote_info['njalla']['a'] = njalla.add_record(name: site.name, type: 'CNAME', content: "#{Site.domain}.").to_h + self.remote_info['njalla']['ns'] = njalla.add_record(name: "_dnslink.#{site.name}", type: 'NS', content: "#{publisher.hostname}.").to_h + nil end @@ -123,4 +129,16 @@ class DeployDistributedPress < Deploy build_stats.create action: publisher.to_s,log: log, seconds: time_spent_in_seconds, bytes: size, status: status nil end + + # Actualizar registros en Njalla + # + # @return [Njalla::V1::Domain] + def njalla + @njalla ||= + begin + client = Njalla::V1::Client.new(token: ENV['NJALLA_TOKEN']) + + Njalla::V1::Domain.new(domain: Site.domain, client: client) + end + end end diff --git a/app/models/distributed_press_publisher.rb b/app/models/distributed_press_publisher.rb index 089f63c6..6139db93 100644 --- a/app/models/distributed_press_publisher.rb +++ b/app/models/distributed_press_publisher.rb @@ -40,6 +40,13 @@ class DistributedPressPublisher < ApplicationRecord "Distributed Press <#{instance}>" end + # Devuelve el hostname de la instancia + # + # @return [String] + def hostname + @hostname ||= URI.parse(instance).hostname + end + # @return [Logger] def logger @logger ||= From a849eac17962a645a70b8fd5b5546aa8d285a46e Mon Sep 17 00:00:00 2001 From: f Date: Thu, 9 Feb 2023 20:08:56 -0300 Subject: [PATCH 026/106] fix: no crear subdominios para dominios personalizados esto es por retrocompatibilidad para sitios que no usan DeployAlternativeDomain --- app/models/deploy_distributed_press.rb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 6f2b2c78..1ae7a2f2 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -113,9 +113,11 @@ class DeployDistributedPress < Deploy # XXX: Esto depende de nuestro DNS actual, cuando lo migremos hay # que eliminarlo. - self.remote_info['njalla'] = {} - self.remote_info['njalla']['a'] = njalla.add_record(name: site.name, type: 'CNAME', content: "#{Site.domain}.").to_h - self.remote_info['njalla']['ns'] = njalla.add_record(name: "_dnslink.#{site.name}", type: 'NS', content: "#{publisher.hostname}.").to_h + unless site.name.end_with? '.' + self.remote_info['njalla'] = {} + self.remote_info['njalla']['a'] = njalla.add_record(name: site.name, type: 'CNAME', content: "#{Site.domain}.").to_h + self.remote_info['njalla']['ns'] = njalla.add_record(name: "_dnslink.#{site.name}", type: 'NS', content: "#{publisher.hostname}.").to_h + end nil end From a3c1d7193f8112006cffa60f830e38d9e8d669f2 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 9 Feb 2023 20:11:17 -0300 Subject: [PATCH 027/106] fix: requires --- app/models/deploy_distributed_press.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 1ae7a2f2..41054b99 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'distributed_press/v1/client/auth' require 'distributed_press/v1/client/site' +require 'njalla/v1' # Soportar Distributed Press APIv1 # From bbd19f44aee1686defc5039df36378ff8bc75c89 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 25 Jan 2023 14:27:14 -0300 Subject: [PATCH 028/106] ci: compilar assets cuando cambian las dependencias --- .woodpecker.yml | 17 +++++++++++++++++ package.json | 1 + 2 files changed, 18 insertions(+) diff --git a/.woodpecker.yml b/.woodpecker.yml index 087b2e90..b3406f39 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -1,4 +1,21 @@ pipeline: + assets: + image: "registry.nulo.in/sutty/panel:3.14.8-2.7.6" + commands: + - "apk add python2" + - "yarn" + - "RAILS_GROUPS=assets bundle install --path=vendor" + - "RAILS_GROUPS=assets bundle exec rails assets:precompile assets:clean" + - "git add assets && git commit -m \"[skip ci] JS\" || true" + when: + branch: + - "rails" + - "panel.sutty.nl" + path: + include: + - "app/assets/**/*" + - "package.json" + - "yarn.lock" publish: image: plugins/docker settings: diff --git a/package.json b/package.json index d520c8f5..6a5f159f 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { "name": "sutty", + "author": "Sutty ", "private": true, "dependencies": { "@airbrake/browser": "^1.4.1", From 1b0c3cb0acf7d6aca045b253e2022065e60a152b Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 19:11:18 -0300 Subject: [PATCH 029/106] ci: compilar en cambios de javascript tambien --- .woodpecker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.woodpecker.yml b/.woodpecker.yml index b3406f39..a2289c12 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -14,6 +14,7 @@ pipeline: path: include: - "app/assets/**/*" + - "app/javascript/**/*" - "package.json" - "yarn.lock" publish: From 0b63ebdd278051ba1b3b5c29fec87b67a6cedb60 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 19:15:26 -0300 Subject: [PATCH 030/106] chore: yaml --- .woodpecker.yml | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index a2289c12..de760284 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -18,29 +18,29 @@ pipeline: - "package.json" - "yarn.lock" publish: - image: plugins/docker + image: "plugins/docker" settings: - registry: registry.nulo.in - username: sutty - repo: registry.nulo.in/sutty/panel + registry: "registry.nulo.in" + username: "sutty" + repo: "registry.nulo.in/sutty/panel" tags: - - ${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH} - - latest + - "${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" + - "latest" build_args: - - RUBY_VERSION=${RUBY_VERSION} - - RUBY_PATCH=${RUBY_PATCH} - - ALPINE_VERSION=${ALPINE_VERSION} - - BASE_IMAGE=registry.nulo.in/sutty/rails + - "RUBY_VERSION=${RUBY_VERSION}" + - "RUBY_PATCH=${RUBY_PATCH}" + - "ALPINE_VERSION=${ALPINE_VERSION}" + - "BASE_IMAGE=registry.nulo.in/sutty/rails" purge: false secrets: - - docker_password + - "docker_password" when: branch: - - rails - - panel.sutty.nl - event: push + - "rails" + - "panel.sutty.nl" + event: "push" matrix: include: - - ALPINE_VERSION: 3.14.8 - RUBY_VERSION: 2.7 - RUBY_PATCH: 6 + - ALPINE_VERSION: "3.14.8" + RUBY_VERSION: "2.7" + RUBY_PATCH: "6" From 6d25d71dd13d2dda59f7b8ae493cac597de383aa Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 19:17:16 -0300 Subject: [PATCH 031/106] fix: solo compilar el container cuando cambia --- .woodpecker.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.woodpecker.yml b/.woodpecker.yml index de760284..aef70024 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -39,6 +39,10 @@ pipeline: - "rails" - "panel.sutty.nl" event: "push" + path: + include: + - "Dockerfile" + - ".dockerignore" matrix: include: - ALPINE_VERSION: "3.14.8" From 25e6cd62dd797be25c38e35124c8bce3ec11b3c1 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 19:20:13 -0300 Subject: [PATCH 032/106] fix: aplicar una master key --- .woodpecker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index aef70024..07f18570 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -5,7 +5,7 @@ pipeline: - "apk add python2" - "yarn" - "RAILS_GROUPS=assets bundle install --path=vendor" - - "RAILS_GROUPS=assets bundle exec rails assets:precompile assets:clean" + - "RAILS_GROUPS=assets RAILS_MASTER_KEY=nada bundle exec rails assets:precompile assets:clean" - "git add assets && git commit -m \"[skip ci] JS\" || true" when: branch: From 4b575801c539351f640a9cb36bcbebd902724780 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 19:30:58 -0300 Subject: [PATCH 033/106] fix: usar .env --- .env.example | 3 ++- .woodpecker.yml | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.env.example b/.env.example index fb086224..3d134dc2 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,8 @@ +RAILS_MASTER_KEY=CHANGEME RAILS_GROUPS=assets DELEGATE=athshe.sutty.nl HAINISH=../haini.sh/haini.sh -DATABASE= +DATABASE_URL=postgres://suttier@postgresql.sutty.local/sutty RAILS_ENV=development IMAP_SERVER= DEFAULT_FROM= diff --git a/.woodpecker.yml b/.woodpecker.yml index 07f18570..1ad83060 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -2,10 +2,11 @@ pipeline: assets: image: "registry.nulo.in/sutty/panel:3.14.8-2.7.6" commands: - - "apk add python2" + - "apk add python2 dotenv" - "yarn" - - "RAILS_GROUPS=assets bundle install --path=vendor" - - "RAILS_GROUPS=assets RAILS_MASTER_KEY=nada bundle exec rails assets:precompile assets:clean" + - "cp .env.example .env" + - "dotenv bundle install --path=vendor" + - "dotenv RAILS_ENV=production bundle exec rails assets:precompile assets:clean" - "git add assets && git commit -m \"[skip ci] JS\" || true" when: branch: From cacd37348f0022c459fe3a59ddc88b3d40ceabb3 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 19:51:46 -0300 Subject: [PATCH 034/106] fix: credenciales de prueba --- .env.example | 3 ++- .gitignore | 1 - config/credentials.yml.enc | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 config/credentials.yml.enc diff --git a/.env.example b/.env.example index 3d134dc2..f3cf48d9 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,5 @@ -RAILS_MASTER_KEY=CHANGEME +# pwgen -1 32 +RAILS_MASTER_KEY=11111111111111111111111111111111 RAILS_GROUPS=assets DELEGATE=athshe.sutty.nl HAINISH=../haini.sh/haini.sh diff --git a/.gitignore b/.gitignore index 496b66cb..baf85364 100644 --- a/.gitignore +++ b/.gitignore @@ -32,7 +32,6 @@ # Ignore master key for decrypting credentials and more. /config/master.key -/config/credentials.yml.enc /public/packs /public/packs-test diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 00000000..ad215f22 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +r7drFxABS9885DuIhjg3ErL++9dkHZdO6/kBlBNlML20R2R2hhYkE1C2Q9fO7zGaHQX3y51FKu9nRAI9Bomp5JCF/RR3oEzP24Je9DsN/Q2lg3smTNuXKV5J8NuqZPRVBZIp7FsyR66xThzI6ZSrk0IFXRpTwQkW83v3Z+FqLKCAFBAiJ84occonkLUxppL0W0IYN4FzNAK0KiPixZDTg/oAqG17pY0suyJRCe86OYkdrvblI/EEmoxKzSPzT4fml4wka26z4KYeRYDjaQmlTJ8/zLK82AruxhYvL9abdtjsUYIVVWHdNrlRRZaVhFP79YIa0AFfHK1KviMKAAfb8EfDar1fivtzW9mb46dzZcEu0ynJB+HDdM1JFiVw33INI6BY8I604pu5B5ebd9Djd1nIP2wNZNu7ZBOgvbPnDJUdenVAnWYZAqmPVAryK1MfwvaG0RmVYnhlIZoQ2HTLENHV9AyAfUOUiZUse7GQ85iOqrn3yk2KxEh7i4U5yqZu2tuMBBmQK8jpDWiu6hEtIIDgL2327EUNTw1uDvMfpD64I9pBwHGXhKBr3Qi02rNwOI6wJBTLTaSHv15oAolVmiI3kWtQca+UO7LfMaU+mLb6xZ4jm3/maNmugKKHD4Ud7FO2nJ6m2FPUB7uolQPiiSY4cnkd2uKNn7aQPMDcWlQn1CQuwriGwhJD27YfYzyJRD5PG33bmR3JSSjUe4BI9cBTv3UZ7XS/B7Z7SEzqef09hpMUVzEsEsw5yW6Qm1MV8AhYaxPuWLOElwiATcObehJ7LyjeKQSwoTioEG4GBlvgujcNTxI5O0RkU7hP6I/A3Q==--3br8yafpyHA5Y6YU--Aq+HRsZsGTHm4pOfvQYyoA== \ No newline at end of file From 12a85bc5856424ed5ee87c9715410e4a05a6d694 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 20:05:57 -0300 Subject: [PATCH 035/106] fix: credentials must be strings --- config/credentials.yml.enc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc index ad215f22..4add450d 100644 --- a/config/credentials.yml.enc +++ b/config/credentials.yml.enc @@ -1 +1 @@ -r7drFxABS9885DuIhjg3ErL++9dkHZdO6/kBlBNlML20R2R2hhYkE1C2Q9fO7zGaHQX3y51FKu9nRAI9Bomp5JCF/RR3oEzP24Je9DsN/Q2lg3smTNuXKV5J8NuqZPRVBZIp7FsyR66xThzI6ZSrk0IFXRpTwQkW83v3Z+FqLKCAFBAiJ84occonkLUxppL0W0IYN4FzNAK0KiPixZDTg/oAqG17pY0suyJRCe86OYkdrvblI/EEmoxKzSPzT4fml4wka26z4KYeRYDjaQmlTJ8/zLK82AruxhYvL9abdtjsUYIVVWHdNrlRRZaVhFP79YIa0AFfHK1KviMKAAfb8EfDar1fivtzW9mb46dzZcEu0ynJB+HDdM1JFiVw33INI6BY8I604pu5B5ebd9Djd1nIP2wNZNu7ZBOgvbPnDJUdenVAnWYZAqmPVAryK1MfwvaG0RmVYnhlIZoQ2HTLENHV9AyAfUOUiZUse7GQ85iOqrn3yk2KxEh7i4U5yqZu2tuMBBmQK8jpDWiu6hEtIIDgL2327EUNTw1uDvMfpD64I9pBwHGXhKBr3Qi02rNwOI6wJBTLTaSHv15oAolVmiI3kWtQca+UO7LfMaU+mLb6xZ4jm3/maNmugKKHD4Ud7FO2nJ6m2FPUB7uolQPiiSY4cnkd2uKNn7aQPMDcWlQn1CQuwriGwhJD27YfYzyJRD5PG33bmR3JSSjUe4BI9cBTv3UZ7XS/B7Z7SEzqef09hpMUVzEsEsw5yW6Qm1MV8AhYaxPuWLOElwiATcObehJ7LyjeKQSwoTioEG4GBlvgujcNTxI5O0RkU7hP6I/A3Q==--3br8yafpyHA5Y6YU--Aq+HRsZsGTHm4pOfvQYyoA== \ No newline at end of file +1jEfzfldP9tT4+HWfhP48I9hw31gYCnnxHWpYjPrcTm/pgkFdiG+mDa6y31EOxzs50w6FEw2GO127BnyBSUIPIxuWY0cR96xL5pVrS3vjyzM84QN4lJF9ER0Tz1AQ9S7NJ54CelSkMfFt/rf+O4YM8cLtdSVsVC/HlGbp16p3D1pm4MFo5cQb0hEmlyyYlzEn4oJtsp/MCIwI4+z8oFhxKdMIxdbiw+KS/7PBRfMm1h5rdGORCnD69iVmnXseMvVtZn9A7N7uR6+gFlhxlD5yyEW0pwTj3tbu9NeIOVbtmYOL5ZhLW9REXtGTqR5Op/LN+ukIXbDNEScKltJXUdWfa9Pd/QjVT8IMURZ04POEMDgs1cw363yz4f+WQForhSco9oYLDOd5hTGRXoZ9fnjnfJSTjINM62hkfDY3w3+s844nNbjbj+lPTJHU/QjRhcuNqBDDxWUfwTmRIqm5zrelnHnZnuFmFwCNet6NChC6EFUAFjrals6kTSQllyMt4xImqA+HL7DnjWj6VURSH+nGQTA4tQvDdfbDwTzg/PvRkJcsy2dRd135RQdmRZ+8KXBviLabwdR256vaCqSO1j+jyeUPGLll35ghyLxncyBkkAKt1zaDRPDWgVafg0gJ3v7hVV5TYgToPzlv4w88KPCY7cBhkb1qGoXAhtO6iAuZYK9eyZd1gNQJKyqbcLqA5aTTX/ylfdbptWhaZ8ibB8KBgVyn2RmrOHEhB38rDSMHHNfK3Xs4/hhqMFIGHGTGCUYVmjCzhVFd15yRurU32d3YtP8W4L77H7qkFsF1gnvsZx+R084LcJqknwY94dmjtUE4x2u+Qh3ElFj--lr8JoUq1WH9xXNsB--mE8hxHADL7SbDWabAPY1+Q== \ No newline at end of file From 723b8e7974f5a04d1bd775a40e3c9f2c5944ba4a Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 20:26:07 -0300 Subject: [PATCH 036/106] ci: publicar los assets --- .woodpecker.yml | 51 +++++++++++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 1ad83060..3f3c510c 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -1,23 +1,4 @@ pipeline: - assets: - image: "registry.nulo.in/sutty/panel:3.14.8-2.7.6" - commands: - - "apk add python2 dotenv" - - "yarn" - - "cp .env.example .env" - - "dotenv bundle install --path=vendor" - - "dotenv RAILS_ENV=production bundle exec rails assets:precompile assets:clean" - - "git add assets && git commit -m \"[skip ci] JS\" || true" - when: - branch: - - "rails" - - "panel.sutty.nl" - path: - include: - - "app/assets/**/*" - - "app/javascript/**/*" - - "package.json" - - "yarn.lock" publish: image: "plugins/docker" settings: @@ -44,6 +25,38 @@ pipeline: include: - "Dockerfile" - ".dockerignore" + assets: + image: "registry.nulo.in/sutty/panel:${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" + commands: + - "apk add python2 dotenv openssh-client" + - "mkdir ~/.ssh/" + - "echo \"$${KNOW_HOSTS}\" | base64 -d >> ~/.ssh/known_hosts" + - "eval $(ssh-agent -s)" + - "echo \"$${SSH_KEY}\" | base64 -d | ssh-add -" + - "git config user.name Woodpecker" + - "git config user.email ci@sutty.coop.ar" + - "git remote add origin ${ORIGIN}" + - "git checkout -B ${CI_COMMIT_BRANCH}" + - "yarn" + - "cp .env.example .env" + - "dotenv bundle install --path=vendor" + - "dotenv RAILS_ENV=production bundle exec rails assets:precompile assets:clean" + - "git add public && git commit -m \"ci: assets [skip ci]\"" + - "git push origin ${CI_COMMIT_BRANCH}" + secrets: + - "SSH_KEY" + - "KNOWN_HOSTS" + - "ORIGIN" + when: + branch: + - "rails" + - "panel.sutty.nl" + path: + include: + - "app/assets/**/*" + - "app/javascript/**/*" + - "package.json" + - "yarn.lock" matrix: include: - ALPINE_VERSION: "3.14.8" From 08cad58b77f418b983d03317e0a748153f336e07 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 14 Mar 2023 20:29:58 -0300 Subject: [PATCH 037/106] fixup! ci: publicar los assets --- .woodpecker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 3f3c510c..198f5a99 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -35,7 +35,7 @@ pipeline: - "echo \"$${SSH_KEY}\" | base64 -d | ssh-add -" - "git config user.name Woodpecker" - "git config user.email ci@sutty.coop.ar" - - "git remote add origin ${ORIGIN}" + - "git remote add origin $${ORIGIN}" - "git checkout -B ${CI_COMMIT_BRANCH}" - "yarn" - "cp .env.example .env" From 9773285e9f4d060473eafb16a1b76edbf171b475 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 15 Mar 2023 11:23:35 -0300 Subject: [PATCH 038/106] fix: no duplicar el remote --- .woodpecker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 198f5a99..41dc85a3 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -35,14 +35,14 @@ pipeline: - "echo \"$${SSH_KEY}\" | base64 -d | ssh-add -" - "git config user.name Woodpecker" - "git config user.email ci@sutty.coop.ar" - - "git remote add origin $${ORIGIN}" + - "git remote add upstream $${ORIGIN}" - "git checkout -B ${CI_COMMIT_BRANCH}" - "yarn" - "cp .env.example .env" - "dotenv bundle install --path=vendor" - "dotenv RAILS_ENV=production bundle exec rails assets:precompile assets:clean" - "git add public && git commit -m \"ci: assets [skip ci]\"" - - "git push origin ${CI_COMMIT_BRANCH}" + - "git push upstream ${CI_COMMIT_BRANCH}" secrets: - "SSH_KEY" - "KNOWN_HOSTS" From c9d7ac437bd5e88531dac3d375250a2bb096a5cd Mon Sep 17 00:00:00 2001 From: f Date: Thu, 16 Mar 2023 09:51:28 -0300 Subject: [PATCH 039/106] =?UTF-8?q?ci:=20probar=20conexi=C3=B3n=20a=20ssh?= =?UTF-8?q?=20antes=20de=20perder=20tiempo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .woodpecker.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 41dc85a3..84101fdf 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -29,10 +29,12 @@ pipeline: image: "registry.nulo.in/sutty/panel:${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" commands: - "apk add python2 dotenv openssh-client" - - "mkdir ~/.ssh/" - - "echo \"$${KNOW_HOSTS}\" | base64 -d >> ~/.ssh/known_hosts" + - "install -d -m 700 ~/.ssh/" + - "echo \"$${KNOWN_HOSTS}\" | base64 -d >> ~/.ssh/known_hosts" + - "chmod 600 ~/.ssh/known_hosts" - "eval $(ssh-agent -s)" - "echo \"$${SSH_KEY}\" | base64 -d | ssh-add -" + - "ssh $${ORIGIN%:*}" - "git config user.name Woodpecker" - "git config user.email ci@sutty.coop.ar" - "git remote add upstream $${ORIGIN}" From b51748ddcbc903838fb76c4d1c3df1ee490153bf Mon Sep 17 00:00:00 2001 From: f Date: Thu, 16 Mar 2023 10:18:42 -0300 Subject: [PATCH 040/106] ci: limpiar assets por separado --- .woodpecker.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 84101fdf..e550afbe 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -42,7 +42,8 @@ pipeline: - "yarn" - "cp .env.example .env" - "dotenv bundle install --path=vendor" - - "dotenv RAILS_ENV=production bundle exec rails assets:precompile assets:clean" + - "dotenv RAILS_ENV=production bundle exec rails assets:precompile" + - "dotenv RAILS_ENV=production bundle exec rails assets:clean" - "git add public && git commit -m \"ci: assets [skip ci]\"" - "git push upstream ${CI_COMMIT_BRANCH}" secrets: From 4de942a7ca5536260a092c0e2aa07e57f4f1d283 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 16 Mar 2023 10:23:11 -0300 Subject: [PATCH 041/106] ci: eliminar packs antes de recompilarlos --- .woodpecker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.woodpecker.yml b/.woodpecker.yml index e550afbe..0492cee2 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -42,6 +42,7 @@ pipeline: - "yarn" - "cp .env.example .env" - "dotenv bundle install --path=vendor" + - "dotenv RAILS_ENV=production bundle exec rails webpacker:clobber" - "dotenv RAILS_ENV=production bundle exec rails assets:precompile" - "dotenv RAILS_ENV=production bundle exec rails assets:clean" - "git add public && git commit -m \"ci: assets [skip ci]\"" From 800386e52ccbe6d40dfe08469d83f1bfa8696040 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 16 Mar 2023 11:24:38 -0300 Subject: [PATCH 042/106] =?UTF-8?q?ci:=20no=20hacer=20conflicto=20con=20la?= =?UTF-8?q?s=20credenciales=20de=20producci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .woodpecker.yml | 1 + config/{credentials.yml.enc => credentials.yml.enc.ci} | 0 2 files changed, 1 insertion(+) rename config/{credentials.yml.enc => credentials.yml.enc.ci} (100%) diff --git a/.woodpecker.yml b/.woodpecker.yml index 0492cee2..ab4887ac 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -39,6 +39,7 @@ pipeline: - "git config user.email ci@sutty.coop.ar" - "git remote add upstream $${ORIGIN}" - "git checkout -B ${CI_COMMIT_BRANCH}" + - "mv config/credentials.yml.enc.ci config/credentials.yml.enc" - "yarn" - "cp .env.example .env" - "dotenv bundle install --path=vendor" diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc.ci similarity index 100% rename from config/credentials.yml.enc rename to config/credentials.yml.enc.ci From a97da5b821768a1a2fdcf0eba185835d70cc2ee7 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 16 Mar 2023 12:22:37 -0300 Subject: [PATCH 043/106] fix: volver a ignorar los secretos --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index baf85364..496b66cb 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ # Ignore master key for decrypting credentials and more. /config/master.key +/config/credentials.yml.enc /public/packs /public/packs-test From f2e79a733d26f1cf578d1f49f995aea14376a246 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 17 Mar 2023 17:33:52 -0300 Subject: [PATCH 044/106] fix: no fallar si hay errores remotos closes #10467 closes #10506 closes #10509 --- app/models/deploy_distributed_press.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 41054b99..09410201 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -118,7 +118,9 @@ class DeployDistributedPress < Deploy self.remote_info['njalla']['a'] = njalla.add_record(name: site.name, type: 'CNAME', content: "#{Site.domain}.").to_h self.remote_info['njalla']['ns'] = njalla.add_record(name: "_dnslink.#{site.name}", type: 'NS', content: "#{publisher.hostname}.").to_h end - + rescue DistributedPress::V1::Error, HTTParty::Error => e + ExceptionNotifier.notify_exception(e, data: { site: site.name }) + ensure nil end From 0c674d6ca12fc0f98645a922e18efd13de85cd09 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 17 Mar 2023 17:37:48 -0300 Subject: [PATCH 045/106] fix: crear el sitio remoto si no se pudo crear antes --- app/models/deploy_distributed_press.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 09410201..bd80dca4 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -27,6 +27,11 @@ class DeployDistributedPress < Deploy time_start + if remote_site_id.blank? || remote_info['njalla'].blank? + create_remote_site! + save + end + site_client.tap do |c| stdout = Thread.new(publisher.logger_out) do |io| until io.eof? From 698b3a0bf6bbbaf6b84a8c0c961de081e2c1989b Mon Sep 17 00:00:00 2001 From: f Date: Fri, 17 Mar 2023 17:39:41 -0300 Subject: [PATCH 046/106] =?UTF-8?q?feat:=20separar=20la=20creaci=C3=B3n=20?= =?UTF-8?q?de=20DP=20de=20njalla?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/deploy_distributed_press.rb | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index bd80dca4..9afc6a5d 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -15,7 +15,7 @@ require 'njalla/v1' class DeployDistributedPress < Deploy store :values, accessors: %i[hostname remote_site_id remote_info], coder: JSON - before_create :create_remote_site! + before_create :create_remote_site!, :create_njalla_records! # Actualiza la información y luego envía los cambios # @@ -27,10 +27,9 @@ class DeployDistributedPress < Deploy time_start - if remote_site_id.blank? || remote_info['njalla'].blank? - create_remote_site! - save - end + create_remote_site! if remote_site_id.blank? + create_njalla_records! if remote_info['njalla'].blank? + save site_client.tap do |c| stdout = Thread.new(publisher.logger_out) do |io| @@ -115,7 +114,16 @@ class DeployDistributedPress < Deploy self.remote_site_id = created_site[:id] self.remote_info = created_site.to_h + rescue DistributedPress::V1::Error + ExceptionNotifier.notify_exception(e, data: { site: site.name }) + ensure + nil + end + # Crea los registros en Njalla + # + # @return [nil] + def create_njalla_records! # XXX: Esto depende de nuestro DNS actual, cuando lo migremos hay # que eliminarlo. unless site.name.end_with? '.' @@ -123,7 +131,7 @@ class DeployDistributedPress < Deploy self.remote_info['njalla']['a'] = njalla.add_record(name: site.name, type: 'CNAME', content: "#{Site.domain}.").to_h self.remote_info['njalla']['ns'] = njalla.add_record(name: "_dnslink.#{site.name}", type: 'NS', content: "#{publisher.hostname}.").to_h end - rescue DistributedPress::V1::Error, HTTParty::Error => e + rescue HTTParty::Error => e ExceptionNotifier.notify_exception(e, data: { site: site.name }) ensure nil From b297800933ae0556845f1e710ce181a6d4e158cb Mon Sep 17 00:00:00 2001 From: f Date: Fri, 17 Mar 2023 17:44:13 -0300 Subject: [PATCH 047/106] fix: volver a fallar si al hacer deploy todavia estan caidos los servicios --- app/models/deploy_distributed_press.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index 9afc6a5d..e8d8b095 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -31,6 +31,10 @@ class DeployDistributedPress < Deploy create_njalla_records! if remote_info['njalla'].blank? save + if remote_site_id.blank? || remote_info['njalla'].blank? + raise DeployJob::DeployException, '' + end + site_client.tap do |c| stdout = Thread.new(publisher.logger_out) do |io| until io.eof? @@ -133,6 +137,7 @@ class DeployDistributedPress < Deploy end rescue HTTParty::Error => e ExceptionNotifier.notify_exception(e, data: { site: site.name }) + self.remote_info['njalla'] = nil ensure nil end From 16ed7db1d76ff24ee5c8a6d88b6c35788c22441a Mon Sep 17 00:00:00 2001 From: f Date: Mon, 20 Mar 2023 12:13:51 -0300 Subject: [PATCH 048/106] =?UTF-8?q?fix:=20capturar=20la=20excepci=C3=B3n?= =?UTF-8?q?=20#10546?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/deploy_distributed_press.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/deploy_distributed_press.rb b/app/models/deploy_distributed_press.rb index e8d8b095..6940a83e 100644 --- a/app/models/deploy_distributed_press.rb +++ b/app/models/deploy_distributed_press.rb @@ -118,7 +118,7 @@ class DeployDistributedPress < Deploy self.remote_site_id = created_site[:id] self.remote_info = created_site.to_h - rescue DistributedPress::V1::Error + rescue DistributedPress::V1::Error => e ExceptionNotifier.notify_exception(e, data: { site: site.name }) ensure nil From 823ac94e7434282a55a9d6a71fb235a7af553b2c Mon Sep 17 00:00:00 2001 From: Nulo Date: Mon, 2 May 2022 18:55:35 +0000 Subject: [PATCH 049/106] Arreglar scroll al reordenar posts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Utilizaba https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded que es propietario. Ahora usa scrollIntoView siempre, configurado para que prácticamente siempre se pueda ver el post al reordenar. --- app/javascript/controllers/reorder_controller.js | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/app/javascript/controllers/reorder_controller.js b/app/javascript/controllers/reorder_controller.js index dca6e166..2cba4163 100644 --- a/app/javascript/controllers/reorder_controller.js +++ b/app/javascript/controllers/reorder_controller.js @@ -103,11 +103,7 @@ export default class extends Controller { this.reorder() // Mantenemos el primero a la vista - if ("scrollIntoViewIfNeeded" in rows[0].row) { - rows[0].row.scrollIntoViewIfNeeded() - } else { - rows[0].row.scrollIntoView() - } + rows[0].row.scrollIntoView({ block: "center" }); } counter () { @@ -146,7 +142,7 @@ export default class extends Controller { this.reorder() // Mantenemos el primero a la vista - rows[0].row.scrollIntoViewIfNeeded() + rows[0].row.scrollIntoView({ block: "center" }); } bottom (event) { @@ -167,7 +163,7 @@ export default class extends Controller { this.reorder() // Mantenemos el primero a la vista - rows[0].row.scrollIntoViewIfNeeded() + rows[0].row.scrollIntoView({ block: "center" }); } /* From 88c1ffe4b8f1ff60bca474cf1ffe5263f8d417e9 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 13:43:13 -0300 Subject: [PATCH 050/106] fix: hacer que los locales sean bidireccionales #10491 #12064 --- app/models/metadata_locales.rb | 11 +----- app/views/posts/attributes/_locales.haml | 48 +++++++----------------- 2 files changed, 16 insertions(+), 43 deletions(-) diff --git a/app/models/metadata_locales.rb b/app/models/metadata_locales.rb index 4d540efc..702e1902 100644 --- a/app/models/metadata_locales.rb +++ b/app/models/metadata_locales.rb @@ -1,21 +1,14 @@ # frozen_string_literal: true # Los valores de este metadato son artículos en otros idiomas -class MetadataLocales < MetadataTemplate - def default_value - super || [] - end - +class MetadataLocales < MetadataHasAndBelongsToMany # Todos los valores posibles para cada idioma disponible # - # TODO: Optimizar? - # TODO: Mantener sincronizados - # # @return { lang: { title: uuid } } def values @values ||= site.locales.map do |locale| [locale, site.posts(lang: locale).map do |post| - [post.title.value, post.uuid.value] + [title(post), post.uuid.value] end.to_h] end.to_h end diff --git a/app/views/posts/attributes/_locales.haml b/app/views/posts/attributes/_locales.haml index 8dd7adf6..6d4d3326 100644 --- a/app/views/posts/attributes/_locales.haml +++ b/app/views/posts/attributes/_locales.haml @@ -1,39 +1,19 @@ --# +%fieldset + %legend= post_label_t(attribute, post: post) - Crea un input-map para cada idioma por separado. Podríamos hacer uno - solo que tenga todos los idiomas pero puede ser una interfaz confusa. + = render 'posts/attribute_feedback', + post: post, attribute: attribute, metadata: metadata - TODO: Esto permite seleccionar más de una traducción por idioma... + - site.locales.each do |locale| + - next if post.lang.value == locale + - locale_t = t("locales.#{locale}.name") -- site.locales.each do |locale| - -# Ignorar el idioma actual - - next if post.lang.value == locale - - locale_t = t("locales.#{locale}.name") - - values = metadata.value.select do |x| - - metadata.values[locale].values.include? x + .form-group + = label_tag "#{base}_#{attribute}_#{locale}", locale_t - .form-group - = label_tag "#{base}_#{attribute}_#{locale}", locale_t + = select_tag("#{plain_field_name_for(base, attribute)}[]", + options_for_select(metadata.values[locale]), + **field_options(attribute, metadata), include_blank: t('.empty')) - .mapable{ dir: t("locales.#{locale}.dir"), lang: locale, - data: { values: values.to_json, - 'default-values': metadata.values[locale].to_json, - name: "#{base}[#{attribute}][]", - list: id_for_datalist(attribute, locale), - button: t('posts.attributes.add'), - remove: 'false', legend: locale_t, - described: id_for_help(attribute, locale) } } - - = text_field(*field_name_for(base, attribute, '[]'), - value: values.join(', '), - dir: t("locales.#{locale}.dir"), lang: locale, - **field_options(attribute, metadata)) - - = render 'posts/attribute_feedback', - post: post, - attribute: [attribute, 'mapable'].flatten, - metadata: metadata - - %datalist{ id: id_for_datalist(attribute, locale) } - - metadata.values[locale].keys.each do |value| - %option{ value: value } + = render 'posts/attribute_feedback', + post: post, attribute: attribute, metadata: metadata From ad1d59d6a4616da92048d84587896dcc8041932d Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 13:55:51 -0300 Subject: [PATCH 051/106] fix: recuperar el valor --- app/views/posts/attributes/_locales.haml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/app/views/posts/attributes/_locales.haml b/app/views/posts/attributes/_locales.haml index 6d4d3326..21d410be 100644 --- a/app/views/posts/attributes/_locales.haml +++ b/app/views/posts/attributes/_locales.haml @@ -7,13 +7,12 @@ - site.locales.each do |locale| - next if post.lang.value == locale - locale_t = t("locales.#{locale}.name") + - value = metadata.value.find do |v| + - metadata.values[locale].values.include? v .form-group = label_tag "#{base}_#{attribute}_#{locale}", locale_t = select_tag("#{plain_field_name_for(base, attribute)}[]", - options_for_select(metadata.values[locale]), + options_for_select(metadata.values[locale], value), **field_options(attribute, metadata), include_blank: t('.empty')) - - = render 'posts/attribute_feedback', - post: post, attribute: attribute, metadata: metadata From 034015938bd07dd9471f006164cba6a6e564af8f Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 14:14:55 -0300 Subject: [PATCH 052/106] =?UTF-8?q?fix:=20mostrar=20el=20idioma=20si=20no?= =?UTF-8?q?=20existe=20una=20traducci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/posts/attributes/_locales.haml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/posts/attributes/_locales.haml b/app/views/posts/attributes/_locales.haml index 21d410be..23f66700 100644 --- a/app/views/posts/attributes/_locales.haml +++ b/app/views/posts/attributes/_locales.haml @@ -6,7 +6,7 @@ - site.locales.each do |locale| - next if post.lang.value == locale - - locale_t = t("locales.#{locale}.name") + - locale_t = t("locales.#{locale}.name", default: locale.to_s.humanize) - value = metadata.value.find do |v| - metadata.values[locale].values.include? v From 6d59d79e2a086bc653565cb93c9ef6406a9b910c Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 14:26:06 -0300 Subject: [PATCH 053/106] =?UTF-8?q?fix:=20establecer=20relaci=C3=B3n=20bid?= =?UTF-8?q?ireccional=20#10491?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/metadata_locales.rb | 36 +++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/app/models/metadata_locales.rb b/app/models/metadata_locales.rb index 702e1902..2e9080c9 100644 --- a/app/models/metadata_locales.rb +++ b/app/models/metadata_locales.rb @@ -7,9 +7,43 @@ class MetadataLocales < MetadataHasAndBelongsToMany # @return { lang: { title: uuid } } def values @values ||= site.locales.map do |locale| - [locale, site.posts(lang: locale).map do |post| + [locale, posts.where(lang: locale).map do |post| [title(post), post.uuid.value] end.to_h] end.to_h end + + # Siempre hay una relación inversa + # + # @return [True] + def inverse? + true + end + + # El campo inverso se llama igual en el otro post + # + # @return [Symbol] + def inverse + :locales + end + + private + + # Obtiene todos los locales distintos a este post + # + # @return [Array] + def other_locales + site.locales.reject do |locale| + locale == post.lang.value.to_sym + end + end + + # Obtiene todos los posts de los otros locales con el mismo layout + # + # @return [PostRelation] + def posts + other_locales.map do |locale| + site.posts(lang: locale).where(layout: post.layout.value) + end.reduce(&:concat) + end end From fc14889d0eeb579e2b86aa6fd2250889d3ae0227 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 14:35:47 -0300 Subject: [PATCH 054/106] fix: soporte para urdu --- config/locales/en.yml | 3 +++ config/locales/es.yml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/config/locales/en.yml b/config/locales/en.yml index 10a4793b..eb7ef1ec 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -13,6 +13,9 @@ en: ar: name: Arabic dir: rtl + ur: + name: Urdu + dir: rtl login: email: E-mail address password: Password diff --git a/config/locales/es.yml b/config/locales/es.yml index 02973de5..665fb350 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -13,6 +13,9 @@ es: ar: name: Árabe dir: rtl + ur: + name: Urdu + dir: rtl login: email: Correo electrónico password: Contraseña From 59606f32639fd48f849a0e27fcb1ac3fa8d6c589 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 14:38:18 -0300 Subject: [PATCH 055/106] fix: reducir el alto de la leyenda --- app/assets/stylesheets/application.scss | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index b756759a..ba8de715 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -154,6 +154,12 @@ ol.breadcrumb { transition: all 3s; } +fieldset { + legend { + font-size: 1rem; + } +} + .mapable, .taggable { .input-map, From 758f9de36dde570f619d4f56faf6d9d56144981d Mon Sep 17 00:00:00 2001 From: Nulo Date: Mon, 2 May 2022 18:55:35 +0000 Subject: [PATCH 056/106] Arreglar scroll al reordenar posts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Utilizaba https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded que es propietario. Ahora usa scrollIntoView siempre, configurado para que prácticamente siempre se pueda ver el post al reordenar. --- app/javascript/controllers/reorder_controller.js | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/app/javascript/controllers/reorder_controller.js b/app/javascript/controllers/reorder_controller.js index dca6e166..2cba4163 100644 --- a/app/javascript/controllers/reorder_controller.js +++ b/app/javascript/controllers/reorder_controller.js @@ -103,11 +103,7 @@ export default class extends Controller { this.reorder() // Mantenemos el primero a la vista - if ("scrollIntoViewIfNeeded" in rows[0].row) { - rows[0].row.scrollIntoViewIfNeeded() - } else { - rows[0].row.scrollIntoView() - } + rows[0].row.scrollIntoView({ block: "center" }); } counter () { @@ -146,7 +142,7 @@ export default class extends Controller { this.reorder() // Mantenemos el primero a la vista - rows[0].row.scrollIntoViewIfNeeded() + rows[0].row.scrollIntoView({ block: "center" }); } bottom (event) { @@ -167,7 +163,7 @@ export default class extends Controller { this.reorder() // Mantenemos el primero a la vista - rows[0].row.scrollIntoViewIfNeeded() + rows[0].row.scrollIntoView({ block: "center" }); } /* From abacabff8efa261f79855cdd22c6217806a096fe Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 18:39:56 -0300 Subject: [PATCH 057/106] fix: agregar licencia con layout --- app/services/site_service.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 22423bb8..436bc1c3 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -104,11 +104,10 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do def add_licencia(lang:) params = ActionController::Parameters.new( post: { + layout: 'license', lang: lang, title: site.licencia.name, description: I18n.t('sites.form.licencia.title'), - author: %w[Sutty], - permalink: "#{I18n.t('activerecord.models.licencia').downcase}/", content: CommonMarker.render_html(site.licencia.deed) } ) From 46c20cae7de41225b63ba5ff44eb7e5484a0e4ab Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 18:41:12 -0300 Subject: [PATCH 058/106] feat: no agregar licencia si la plantilla no lo soporta --- app/services/site_service.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 436bc1c3..87a08652 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -92,6 +92,8 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do # Crea la licencia del sitio para cada locale disponible en el sitio def add_licencias + return unless site.layout? :license + site.locales.each do |locale| next unless I18n.available_locales.include? locale From 0b353466a4c8113ed7c3fd57bed9f622ca298643 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 18:43:20 -0300 Subject: [PATCH 059/106] fix: solo cambiar la licencia si existe una #159 --- app/services/site_service.rb | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 87a08652..b4fa2fa0 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -119,18 +119,14 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do # Encuentra la licencia a partir de su enlace permanente y le cambia # el contenido - # - # TODO: Crear un layout específico para licencias así es más certera - # la búsqueda. def change_licencias site.locales.each do |locale| next unless I18n.available_locales.include? locale Mobility.with_locale(locale) do - permalink = "#{I18n.t('activerecord.models.licencia').downcase}/" - post = site.posts(lang: locale).find_by(permalink: permalink) + post = site.posts(lang: locale).find_by(layout: 'license') - post ? change_licencia(post: post) : add_licencia(lang: locale) + change_licencia(post: post) if post end end end From 7b68bc15692ba4032e7ec9b660f6fc624512250d Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 18:45:41 -0300 Subject: [PATCH 060/106] =?UTF-8?q?fix:=20crear=20las=20licencias=20despu?= =?UTF-8?q?=C3=A9s=20de=20crear=20el=20t=C3=ADtulo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit y los commits también se harían en el idioma de le usuarie --- app/services/site_service.rb | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index b4fa2fa0..e98d2487 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -14,11 +14,10 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do I18n.with_locale(usuarie&.lang&.to_sym || I18n.default_locale) do site.save && site.config.write && - commit_config(action: :create) + commit_config(action: :create) && + add_licencias end - add_licencias - site end @@ -27,11 +26,10 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do I18n.with_locale(usuarie&.lang&.to_sym || I18n.default_locale) do site.update(params) && site.config.write && - commit_config(action: :update) + commit_config(action: :update) && + change_licencias end - change_licencias - site end From ddd2bc07ff62b24745e74af4d6ce7284263e8117 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:04:15 -0300 Subject: [PATCH 061/106] =?UTF-8?q?feat:=20incorporar=20los=20c=C3=B3digos?= =?UTF-8?q?=20de=20conducta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/code_of_conduct.rb | 14 + app/services/site_service.rb | 34 +- config/initializers/inflections.rb | 4 + .../20230322214924_add_code_of_conduct.rb | 22 + db/seeds/codes_of_conduct.yml | 613 ++++++++++++++++++ 5 files changed, 686 insertions(+), 1 deletion(-) create mode 100644 app/models/code_of_conduct.rb create mode 100644 db/migrate/20230322214924_add_code_of_conduct.rb create mode 100644 db/seeds/codes_of_conduct.yml diff --git a/app/models/code_of_conduct.rb b/app/models/code_of_conduct.rb new file mode 100644 index 00000000..87c24c7f --- /dev/null +++ b/app/models/code_of_conduct.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Códigos de conducta +class CodeOfConduct < ApplicationRecord + extend Mobility + + translates :title, type: :string, locale_accessors: true + translates :description, type: :text, locale_accessors: true + translates :content, type: :text, locale_accessors: true + + validates :title, presence: true, uniqueness: true + validates :description, presence: true + validates :content, presence: true +end diff --git a/app/services/site_service.rb b/app/services/site_service.rb index e98d2487..19b95302 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -15,7 +15,8 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do site.save && site.config.write && commit_config(action: :create) && - add_licencias + add_licencias && + add_code_of_conduct end site @@ -141,10 +142,41 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do params: params).update end + def add_code_of_conduct + # TODO: soportar más códigos de conducta + coc = CodeOfConduct.first + + with_all_locales do |locale| + params = ActionController::Parameters.new( + post: { + layout: 'code_of_conduct', + lang: locale.to_s, + title: coc.title, + description: coc.description, + content: CommonMarker.render_html(coc.content) + } + ) + + PostService.new(site: site, usuarie: usuarie, params: params).create + end + end + # Crea los deploys necesarios para sincronizar a otros nodos de Sutty def sync_nodes Rails.application.nodes.each do |node| site.deploys.build(type: 'DeployRsync', destination: "sutty@#{node}:#{site.hostname}") end end + + private + + def with_all_locales(&block) + site.locales.each do |locale| + next unless I18n.available_locales.include? locale + + Mobility.with_locale(locale) do + yield locale + end + end + end end diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb index 0e18b987..46cb9d78 100644 --- a/config/initializers/inflections.rb +++ b/config/initializers/inflections.rb @@ -13,6 +13,8 @@ ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.singular 'roles', 'rol' inflect.plural 'rollup', 'rollups' inflect.singular 'rollups', 'rollup' + inflect.plural 'code_of_conduct', 'codes_of_conduct' + inflect.singular 'codes_of_conduct', 'code_of_conduct' end ActiveSupport::Inflector.inflections(:es) do |inflect| @@ -28,4 +30,6 @@ ActiveSupport::Inflector.inflections(:es) do |inflect| inflect.singular 'licencias', 'licencia' inflect.plural 'rollup', 'rollups' inflect.singular 'rollups', 'rollup' + inflect.plural 'code_of_conduct', 'codes_of_conduct' + inflect.singular 'codes_of_conduct', 'code_of_conduct' end diff --git a/db/migrate/20230322214924_add_code_of_conduct.rb b/db/migrate/20230322214924_add_code_of_conduct.rb new file mode 100644 index 00000000..f859b08c --- /dev/null +++ b/db/migrate/20230322214924_add_code_of_conduct.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +# Crea códigos de conducta +class AddCodeOfConduct < ActiveRecord::Migration[6.1] + def up + create_table :codes_of_conduct do |t| + t.timestamps + t.string :title + t.text :description + t.text :content + end + + # XXX: En lugar de ponerlo en las seeds + YAML.safe_load(File.read('db/seeds/codes_of_conduct.yml')).each do |coc| + CodeOfConduct.new(**coc).save! + end + end + + def down + drop_table :codes_of_conduct + end +end diff --git a/db/seeds/codes_of_conduct.yml b/db/seeds/codes_of_conduct.yml new file mode 100644 index 00000000..64582072 --- /dev/null +++ b/db/seeds/codes_of_conduct.yml @@ -0,0 +1,613 @@ +--- +- title_en: "Codes for sharing" + title_es: "Códigos para compartir" + description_en: "Codes of conduct allow inclusive communities." + description_es: "Los códigos de convivencia nos permiten alojar comunidades inclusivas." + content_en: | + # Code for sharing + + > This code of conduct is based in "[Códigos para compartir, hackear, + > piratear en + > libertad](https://utopia.partidopirata.com.ar/zines/codigos_para_compartir.html)" + > published by [Partido Interdimensional + > Pirata](https://partidopirata.com.ar/). + + > We use gender neutral pronouns to include all peoples. In this sense, + > we encourage different forms, strategies and tools used to embody + > practices that aren't anthropocentric, sexist, cis-sexist in our + > language. + + ## Introduction + + This is an example code that strives to give a consensual frame to + enable asistance, permanence and confortable stay to everyone using and + inhabiting [Sutty](https://sutty.nl/), and to welcome new users and + potential allies as well. It sets the floor for desirable and + acceptable, and undesirable and intolerable conducts for its community. + You can use it with or without changes, adapting it to your activities. + This code is in permanent and collective mutation and feeds, copies and + inspires on the following sources: + + * + + * + + * + + * + + We strive to sustain and foment an open community, that invites and + attains participation from more people, in all their diversity. We know + that spaces related to computing and free software are mostly inhabited + by middle class cis white males, even when there's an acknowledgement of + the need to close the gender gap. In this sense, this is our little + contribution, made from collective practices on multiple dimentions, + reflections, readings, and experiences that grow every day. + + ## That everyone needs to be well treated + + Every being that we share space with deserves good treatment, respect + and compassion. Here we share basic criteria for introduction and care. + + ### Towards humans + + Everyone is deserving of care and greetings and we have a right to + assume good intentions from others. + + When we refer to other humans, we try to be careful and respectul + towards their gender identity. For this, these principles are useful: + + * Don't assume, judge or try to "interpret" the gender of others. + + * Don't use gender beforehand. It's related to the previous item, but + puts emphasis towards naturalized gendering behaviour (ie. assuming + someone wearing a dress uses female pronouns...). The proposal is to + discard them. + + * If a person explicits their pronouns and mode in which they want to be + referenced, we respect them, by listening and trying to use their + prefered pronouns. + + * When presentations don't include pronouns, we can ask respectfully + for prefered pronouns. But be careful! This question must be asked + to everyone, otherwise the "suspicion" is loaded towards a person, and + it can become a form of harrassment. + + * Do we need to know the gender of a person to relate with them? Maybe + a better practice is to evade gendering others. But if this means to + use "them" compulsively, some people may be made to feel bad. (For + instance, trans\* people who use female or male pronouns may feel + upset or outed when refering to them as "them", specially if they're + the only ones to be gendered like this in a group! + + * When in doubt, asking and apologizing respectfully is a good way of + being careful towards each other. + + ## Important points to guarantee our space from being expulsive + + **Listening to and between everyone in a caring climate** + + * Listen to what everyone has to say, being mindful that everyone has + something valuable to communicate. + + * For active listening, we prefer to ask first, before making judgement. + + * Sometimes being silent is a condition for others to be able to talk. + To listen is an exercise that requires practice. Also talking. + + * We're interested in what everyone has to say. If you're more trained + in participating, talking, and having opinions, take into account that + not everyone does. Give them space if they want to take it. But + remember that encouraging is not the same as pressuring! + + * We try to check and stop offensive practices to add to the respectful + climate. This doesn't mean to be submissive or to agree to + everything. At the least, it sets a floor of respect towards enabling + a dialogue when necessary. + + * It's at the very least disrepectful to repeat damaging behaviour when + it was already identified as such. It can make others unconfortable, + or hurt and expel them. We'll make this point every time that is + needed and tolerable. + + * We avoid this behaviour ourselves and we help others to notice their + own. + + * When raising attention becomes insufficient, we need to review this + agreements to keep the coexistence. This implies to act in accord to + them, and that this code can be revised and updated when deemed + necessary (there's no consensus). + + * One of the ways in which free software spaces can be and are expulsive + is with attitudes that don't contemplate diversity in knowledges and + interlocutors. By appealing to technicisms, many comrades are kept + out of what's happening, and no one verifies if everyone is keeping up + with the conversation. + + Our fervent recommendation is to be attentive to this dynamic so we + can avoid or revert them. + + * The counter to the previous situation is "mansplaining": a cis-male + person assuming the authoritative place of knowledge to (over-)explain + everything to others, in a patronizing way and without taking into + account what others want to listen or not, to say, what already know + or do, etc. + + * We believe there's no "authoritative voice" to have an opinion and to + participate. Free culture is for everyone to share. + + * "Sharing is caring" v. "Google is your friend". Meritocracy and other + traditional codes in cyber-communities work against free culture. We + support the pirate culture that onboards ever more pirates to their + ships. We believe that culture is for everyone and we defy elitisms. + + * We don't assume that other people shares our likings, beliefs, class + position, sexuality, etc. We can be violent when we misread others. + We recommend to ask respectfully and to avoid comments or jokes that + can be hurtful to others. + + * We speak and act gently and inclusively. + + * We respect different points of view, experiences, beliefs, etc. and we + take them into account when we act collectively so it reflects in our + attitudes. + + * We welcome criticism, specially the constructive kind ;) + + * We focus in what's best for the community, without losing warmth, + respect and diversity amongst ourselves. + + * We show empathy toward others. We want to share and communicate. + + * It's useful to think everyone has different abilities, stories, + experiences... It's possible to not understand some comments. We try + to avoid acting in bad faith and to use every accessibility tool we + can. + + * The last item includes neurodiverse people and those that have + experienced trauma. Sometimes, sarcasm or irony is not well received + or understood by others. We take this into our strategies to include + everyone in our communications. Even more, if we think some topics + could be sensitive to others (memory-triggering, phobias, untolerable, + explicit violence or body images, etc.), we use content warnings (cw) + before what we wanted to share. For instance: "cw: comments about + sexual and physical violence". This allows everyone to opt in to the + content instead of being taken by surprise. + + * We're respectful of limits established by others (personal space, + physical contact, interaction mood, privacy, being photographed, etc.) + + * We want to and believe in welcoming more pirates! + + ## Consent for documenting and sharing in media + + * If you're going to take pictures or record video, ask consent from + people involved. + + * If there're minors, ask their responsible families. + + ## Our commitment against harassment + + In the interest of fomenting an open, diverse and welcoming community, + we contributors and admins make a commitment against harassment in our + projects and community for everyone, without regard of age, body + diversity, capacity, neuro-diversity, ethnicity, gender identity and + expression, experience level, nationality, physical appearance, + religion, sexual identity or orientation. + + Examples of unacceptable behaviour from participants: + + * Offensive comments about gender/s, gender identity and expression, + sexual orientation, capacity, mental sickness, neuro-(a)tipicality, + physical appearance, body size, ethnicity or religion. + + * Unwelcomed comments related to personal and life choices, including + amongst others, those related to food, health, children upbringing, + drug use and employment. + + * Insulting or despective comments and personal or political attacks. + **Trolling**. + + * Assuming others' gender. If you're in doubt, ask politely about + pronouns. Don't use the name(s) that people don't use anymore, use + the name, _nickname_ or pseudonym that they prefer. Do you really + need the name, ID number, biometric data, birth certificate of others? + + * Sexual comments, images or behaviour, unneeded or in spaces where they + weren't appropiate. + + * Unconsented physical contact or repeated after being asked to stop. + + * Threatening others. + + * Inciting violence towards others, including self-damage. + + * Deliberate intimidation. + + * Stalking. + + * To harass by photographing or recording without consent, including + uploading personal information to the Internet. + + * Interrupting a conversation constantly. + + * Making unwanted sexual comments. + + * Unappropiate patterns of social contact, like asking/assuming + inappropiate intimacy levels with others. + + * Trying to interact with a person after being asked not to. + + * Exposing deliberately any aspect of a person identity without consent, + except when necessary for protecting others against intentional abuse. + + * Making public any kind of private conversation. + + * Other kinds of conduct that can be considered inappropiate in an + environment of camaraderie. + + * Repeating attitudes that others find offensive or violatory of this + code. + + ## Consequences + + * Any person that has been asked to stop offensive behaviour is expected + to respond immediately, even when in disagreement. + + * Admins can take any action deemed necessary and adequate, including + expelling the person or removing their site without advertence. This + decision is taken by consensus between admins and is reserved for + extreme cases that compromise the community or the permanence of + others without feeling wronged or threatened. + + * Admins reserve the right to forbid participation to any future + activity or publication. + + As we mentioned before, this code is in permanent collective mutation. + It's main objective is to generate an inclusive and non-expulsive + environment that is also transparent and open without [missing + stairs](https://en.wikipedia.org/wiki/Missing_stair) ("the missing stair + from a house that everyone knows about but no one wants to take + responsibility for"). It's important to adapt it to different + activities and that it nurtures from contributions from its users. + Receiving your comments and input will help us to achieve this + objective. + + ## Let's keep in contact! + + Si pasaste por alguna situación que quieras compartir --te hayas animado + o no a decirlo en el momento--, podés ponerte en contacto con nosotres. + + Con respecto a quejas o avisos acerca de situaciones de violencia, + acoso, abuso o repetición de conductas que se advirtieron como + intolerables, tomamos la responsabilidad de tenerlas en cuenta y + trabajar en ellas para que el resultado sea el favorable al espíritu de + colectiva que elegimos y describimos aquí. Si bien consideramos que las + prácticas punitivistas no van con nosotres, nuestra decisión explícita + es escuchar a la persona que se manifiesta como violentada o víctima y + acompañarla. + + You can contact us if you were part of a situation you want to share + --even if you didn't pointed it in the moment. + + In regards to complaints or notices about violence, harassment, abuse or + repeated untolerable conducts, we take the responsibility of working on + them for a favorable result towards the collective spirit we defined + here. Even when we don't condone punitivist practices, our explicit + decision is for the victim to be listened and accompanied. + content_es: | + # Códigos para compartir + + > Este código de convivencia está basado en los "[Códigos para + > compartir, hackear, piratear en + > libertad](https://utopia.partidopirata.com.ar/zines/codigos_para_compartir.html)" + > publicados por el [Partido Interdimensional + > Pirata](https://partidopirata.com.ar/). + + > Utilizamos preferentemente la 'e' para referirnos a las personas en + > general. En ese sentido, alentamos las diferentes formas, estrategias + > y herramientas para incorporar prácticas no antropocéntricas, + > sexistas, ni cisexistas en la lengua. Otras alternativas que apoyamos + > --y eventualmente usamos-- son el uso del femenino, la letra e, arrobas, + > equis, asteriscos, etc. + + ## Introducción + + Este es un ejemplo de código que busca aportar un marco de consenso para + garantizar la asistencia, permanencia y cómoda estadía de todas las + personas que habitan y utilizan Sutty, así como para bienvenir a nueves + usuaries y potenciales aliades. Para esto, fija un piso de conductas + deseables, aceptables, indeseables y/o intolerables para la comunidad. + Podés usarlo sin cambios o modificarlo para adaptarlo a tus actividades. + Este código está en permanente mutación colectiva y se alimenta, copia e + inspira de las siguientes fuentes: + + * + + * + + * + + * + + Procuramos mantener y fomentar una comunidad abierta, que invite y logre + la participación de cada vez más personas, en toda su diversidad. + Sabemos que los espacios de Software Libre, informática, sistemas, etc. + son habitados mayormente por varones cis, blancos y de clase media, pese + al reconocimiento de la necesidad de eliminar la brecha de géneros. En + este sentido, este es nuestro pequeño aporte, hecho de prácticas + colectivas de múltiples dimensiones, reflexiones, lecturas, experiencias + que crecen día a día. + + ## Que todes les seres sean bien tratades + + Cada ser con el que compartamos el espacio es merecedore de buen trato, + respeto y compasión. En otras palabras, compartimos a continuación los + criterios básicos de presentación y cuidados. + + Para les humanes + + Todes somos dignes de cuidados y de saludos y tenemos derecho a suponer + las buenas intenciones de le otre. + + Para referirnos a otres humanes, trataremos de ser cuidadoses y + respuestuoses de su identidad de género. Para ello, son útiles los + siguientes principios: + + * No presuponer, juzgar o "interpretar" el género de le otre. + + * No generizar de antemano. Se desprende del punto anterior, pero hace + especial énfasis en comportamientos naturalizados de generización (EJ: + presuponer que porque una persona usa un vestido se nombra en + femenino...). La propuesta es desecharlos. + + * Si la persona explicita sus pronombres y modos en que quiere ser + referenciade, lo respetamos, escuchando y procurando referirnos a elle + usando sus pronombres elegidos. + + * Si no se incluye en la presentación los pronombres preferidos, podemos + preguntar respetuosamente qué pronombres se usan. ¡Pero atención! Es + una pregunta que debe dirigirse a todes por igual, de lo contrario, + carga la "sospecha" sobre la persona señalada y puede resultar en una + forma de hostigamiento. + + * ¿Es necesario conocer el género de una persona para relacionarnos o + referirnos a ella? Quizás una buena práctica es evitar generizar para + todas las personas. Pero si esto implica el uso compulsivo de la "e" + para todes, puede ser que alguna persona se sienta molesta. (Por + ejemplo, las personas trans\* que se identifican en femenino o + masculino suelen sentirse molestas y "sacadas del clóset" u *outeadas* + si se refieren a ellas con la "e", ¡en especial si son las únicas en + ser generizadas de esta forma en un grupo!). + + * Ante cualquier duda, preguntar respetuosamente y disculparse + respetuosamente es una buena idea para ayudar a cuidarnos. + + ## Puntos importantes para garantizar que nuestro espacio no resulte expulsivo + + **Escucharnos a todas y entre todas en un clima de cuidados** + + * Escuchar lo que cada quien tiene para decir, conscientes de que todes + tenemos algo valioso para comunicar(nos). + + * Para la escucha activa, preferimos preguntar primero, en lugar de + hacer juicios. + + * Hacer silencio a veces es la condición para que otres puedan animarse + a hablar. Escuchar es un ejercicio que requiere práctica. También lo + es hablar. + + * Nos interesa lo que todes tengan para decir. Por lo tanto, si estás + más entrenade en el ejercicio de participar, hablar, opinar, tené en + cuenta que quizás haya otres que no lo estén tanto: darles el espacio + si quieren tomarlo. ¡Pero recordá que incentivar no es lo mismo que + presionar! + + * Tratamos de revisar y discontinuar alguna práctica que pueda haber + resultado ofensiva, para sumar al clima de respeto. Sin embargo, esto + no significa "bajar la cabeza" o estar necesariamente de acuerdo. Al + menos, fija un piso de respeto para comenzar un diálogo en el caso en + que sea necesario. + + * Es --al menos-- una falta de respeto repetir un comportamiento dañino + que ya se identificó como tal. Puede incomodar, lastimar y expulsar a + otres, por lo que preferimos llamar la atención sobre este punto todas + las veces que sea necesario y tolerable. + + * Evitamos esto nosotres y ayudamos a otres a darse cuenta cuando lo + están haciendo. + + * En los casos en los que los llamados de atención resulten + insuficientes, hemos de revisar estos acuerdos para sostener la + convivencia. Eso implica actuar de acuerdo a ellos. Y también que + estos códigos pueden ser revisados y actualizados en caso de que se + considere necesario (deje de haber consenso). + + * Una manera en la que los espacios de Software Libre y tecnologías + pueden y suelen ser expulsivos es mediante actitudes que no contemplan + la diversidad de saberes e interlocutor\*s. So pretexto de incluir + tecnicismos, muches compañeres quedan al margen de lo que está + sucediendo, muchas veces, sin que nadie tenga la mínima delicadeza de + verificar que todes estén siguiendo la conversación. + + Recomendamos fervientemente estar atentes a estas dinámicas para poder + evitarlas y/o revertirlas. + + * La otra cara de la situación anterior es el famoso _mansplaining_: un + tipo cis poniéndose en el lugar de la autoridad del saber para + (sobre-)explicar todo a le otre, de manera paternalista y sin tener en + cuenta lo que le otre quiere o no escuchar, decir, lo que sabe o hace, + etc. + + * Creemos que no hace falta ser "una voz autorizada" para opinar y + participar. La cultura libre se comparte entre todes. + + * "Compartir es bueno" vs. "Google es tu amigo". La meritocracia y + ciertos códigos tradicionales de ciertas ciber-comunidades suelen + operar de manera contraria a la propuesta de la cultura libre de + compartir. Apoyamos la cultura piratil que suma más piratas a los + barcos. Creemos que la cultura es para todes y desafiamos las + prácticas elitistas. + + * No damos por sentado que la persona con la que estamos interactuando + comparte gustos, creencias, pertenencias de clase, sexualidad, etc. + Podemos ser violentes si hacemos una lectura equivocada de le otre. + Recomendamos siempre preguntar de manera respetuosa y evitar + comentarios o chistes que puedan herir a les otres. + + * Usamos lenguaje amable e inclusivo y mostramos conductas amables e + inclusivas. + + * Respetamos los diferentes puntos de vista, experiencias, creencias, + etc. y lo tenemos en cuenta cuando estamos en grupo para verlo + reflejado en nuestras actitudes. + + * Aceptamos las críticas. En especial las constructivas ;) + + * Nos enfocamos en lo que es mejor para la comunidad, sin por ello + perder de vista la calidez, el respeto y la diversidad entre cada une + de nosotres. + + * Mostramos empatía con les otres. Queremos comunicarnos y compartir. + + * Es útil tener en cuenta que las personas tenemos capacidades, + historias, recorridos... diferentes. Es posible que algunos + comentarios no sean comprendidos. Trataremos de evitar la mala fe y + sumar todas las herramientas de accesibilidad para todas las personas. + + * El punto anterior incluye a personas neurodiversas y con experiencias + de trauma. A veces el sarcasmo o la ironía no es bien recibido o + comprendido por todes. Será útil tenerlo en cuenta para buscar + estrategias que no excluyan a las personas de nuestros intercambios. + Por otro lado, si creemos que determinados temas pueden ser sensibles + (desencadenantes de recuerdos, fobias, difíciles de tolerar o cargados + de violencia o imágenes corporales muy explícitas, por ejemplo) para + algunas personas y nos valemos de las advertencias de contenido o + _content warning_ (cw) (ej: "cw: comentarios de violencia sexual y + violencia física") antes del contenido a introducir. Esto permite que + cada cual pueda elegir si acceder o no a esos contenidos y que no le + tomen por sorpresa. + + * Respetamos los límites que establecen otras personas (espacio + personal, contacto físico, ganas de interactuar, no querer dar datos + de contacto o ser fotografiades, etc.) + + * ¡Queremos y (creemos) en sumar piratas! + + ## Consentimiento para documentar o compartir en medios + + * Si vas a publicar video o fotos, obtené el consentimiento de las + personas. + + * Si hay menores, consultalo con su familia responsable. + + ## Nuestro compromiso contra el acoso + + En el interés de fomentar una comunidad abierta, diversa y hospitalaria, + nosotres como contribuyentes y administradores nos comprometemos a hacer + de la participación en nuestro proyecto y nuestra comunidad una + experiencia libre de acoso para todes, independientemente de la edad, + diversidad corporal, capacidades, neuro-diversidad, etnia, identidad y + expresión de género, nivel de experiencia, nacionalidad, apariencia + física, raza, religión, identidad u orientación sexual y otras. + + Ejemplos de comportamiento inaceptable por parte de participantes: + + * Comentarios ofensivos relacionados con el/los género/s, la identidad + y expresión de género, la orientación sexual, las capacidades, las + enfermedades mentales, la neuro(a)tipicalidad, la apariencia física, + el tamaño corporal, la raza o la religión. + + * Comentarios indeseados relacionados con las elecciones y las prácticas + de estilo de vida de una persona, incluidas, entre otras, las + relacionadas con alimentos, salud, crianza de les hijes, drogas y + empleo. + + * Comentarios insultantes o despectivos (_trolling_) y ataques + personales o políticos. + + * Dar por sentado el género de las demás personas. En caso de duda, + preguntá educadamente por los pronombres. No uses nombres con los que + las personas no se identifican, usá el nombre, _nickname_ o apodo que + hayan elegido (¿Realmente necesitás el nombre y el número de DNI, + datos biométricos, carta natal, etc.?). + + * Comentarios, imágenes o comportamientos sexuales innecesarios o fuera + de lugar en espacios en los que no son apropiados. + + * Contacto físico sin consentimiento o reiterado tras un pedido de cese. + En el mismo sentido, invasión del espacio corporal (y espacios en + general). + + * Amenazas contra otras personas. + + * Incitación a la violencia contra otra persona, que también incluye + alentar a una persona a autolesionarse. + + * Intimidación deliberada. + + * Acechar (_stalkear_) o perseguir. + + * Acosar fotografiando o grabando sin consentimiento, incluyendo también + subir información personal a Internet sobre alguien para acosarle. + + * Interrumpir constantemente en una conversación. + + * Hacer comentarios sexuales indeseados. + + * Patrones de contacto social inapropiados, como por ejemplo + pedir/suponer niveles de intimidad inapropiados con les demás. + + * Seguir tratando de entablar conversación con una persona cuando se te + pidió que no lo hagas. + + * Divulgar deliberadamente cualquier aspecto de la identidad de una + persona sin su consentimiento, excepto que sea necesario para proteger + a otras personas de abuso intencional. + + * Hacer pública una conversación privada de cualquier tipo. + + * Otros tipos de conducta que pudieran considerarse inapropiadas en un + entorno de camaradería. + + * Reiteración de actitudes que les participantes señalen como ofensivas + o violatorias de este código. + + ## Consecuencias + + * Se espera que la persona a la que se la haya pedido que cese un + comportamiento que infringe este código acate el pedido de forma + inmediata, incluso si no está de acuerdo con este. + + * Les administradores pueden tomar cualquier acción que juzguen + necesaria y adecuada, incluyendo expulsar a la persona o dar de baja + sus sitios sin advertencia. Esta decisión la toman les administradores + en consenso y se reserva para casos extremos que comprometan la + continuidad de la comunidad o bien la posibilidad de permanencia en + ella de otres participantes sin sentirse agraviades o amenazades. + + * Les administradores se reservan el derecho a prohibir la asistencia a + cualquier actividad futura o publicación de sitios. + + Como mencionamos antes, este código está en permanente mutación + colectiva. El objetivo principal es generar un ambiente inclusivo y no + expulsivo, un ambiente transparente y abierto en el que no haya + escalones faltantes ("el escalón que falta en la escalera y todo el + mundo sabe y avisa pero nadie se quiere hacer cargo"). Es importante que + se adapte a las actividades y se nutra de las contribuciones de les + usuaries. Recibir tus comentarios y aportes nos ayudará a cumplir con + su objetivo principal. + + ## ¡Sigamos en contacto! + + Si pasaste por alguna situación que quieras compartir --te hayas animado + o no a decirlo en el momento--, podés ponerte en contacto con nosotres. + + Con respecto a quejas o avisos acerca de situaciones de violencia, + acoso, abuso o repetición de conductas que se advirtieron como + intolerables, tomamos la responsabilidad de tenerlas en cuenta y + trabajar en ellas para que el resultado sea el favorable al espíritu de + colectiva que elegimos y describimos aquí. Si bien consideramos que las + prácticas punitivistas no van con nosotres, nuestra decisión explícita + es escuchar a la persona que se manifiesta como violentada o víctima y + acompañarla. From 3f3ef0041092c06ade35df5a0b278a4e79fc976c Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:06:57 -0300 Subject: [PATCH 062/106] =?UTF-8?q?fix:=20solo=20crear=20el=20c=C3=B3digo?= =?UTF-8?q?=20de=20conducta=20si=20la=20plantilla=20lo=20soporta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit como fallback usamos page --- app/services/site_service.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 19b95302..e0fe17cd 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -143,13 +143,15 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do end def add_code_of_conduct + return unless site.layout?(:code_of_conduct) || site.layout?(:page) + # TODO: soportar más códigos de conducta coc = CodeOfConduct.first with_all_locales do |locale| params = ActionController::Parameters.new( post: { - layout: 'code_of_conduct', + layout: site.layout?(:code_of_conduct) ? 'code_of_conduct' : 'page', lang: locale.to_s, title: coc.title, description: coc.description, From 89ef2959e3c93a889677c3051a6987712a3434af Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:21:52 -0300 Subject: [PATCH 063/106] feat: usar un slug sino cuando cambia la licencia queda con la url de la anterior --- app/services/site_service.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index e0fe17cd..225c6292 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -106,6 +106,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do params = ActionController::Parameters.new( post: { layout: 'license', + slug: Jekyll::Utils.slugify(I18n.t('activerecord.models.licencia')), lang: lang, title: site.licencia.name, description: I18n.t('sites.form.licencia.title'), From e25b4858a01df490a66e5c818c0676828e45d539 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:23:51 -0300 Subject: [PATCH 064/106] fix: no cambiar las licencias si el sitio no las soporta --- app/services/site_service.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 225c6292..e4793453 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -120,6 +120,8 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do # Encuentra la licencia a partir de su enlace permanente y le cambia # el contenido def change_licencias + return unless site.layout? :license + site.locales.each do |locale| next unless I18n.available_locales.include? locale From 368001b341bfa0b6891a15088625c615d6839098 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:32:52 -0300 Subject: [PATCH 065/106] =?UTF-8?q?fix:=20poder=20encadenar=20licencias=20?= =?UTF-8?q?con=20c=C3=B3digos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/site_service.rb | 46 ++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index e4793453..47b532f4 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -90,18 +90,19 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do end # Crea la licencia del sitio para cada locale disponible en el sitio + # + # @return [Boolean] def add_licencias - return unless site.layout? :license + return true unless site.layout? :license - site.locales.each do |locale| - next unless I18n.available_locales.include? locale - - Mobility.with_locale(locale) do - add_licencia lang: locale - end - end + with_all_locales do |locale| + add_licencia lang: locale + end.compact.map(&:valid?).all? end + # Crea una licencia + # + # @return [Post] def add_licencia(lang:) params = ActionController::Parameters.new( post: { @@ -119,20 +120,22 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do # Encuentra la licencia a partir de su enlace permanente y le cambia # el contenido + # + # @return [Boolean] def change_licencias - return unless site.layout? :license + return true unless site.layout? :license - site.locales.each do |locale| - next unless I18n.available_locales.include? locale + with_all_locales do |locale| + post = site.posts(lang: locale).find_by(layout: 'license') - Mobility.with_locale(locale) do - post = site.posts(lang: locale).find_by(layout: 'license') - - change_licencia(post: post) if post - end - end + change_licencia(post: post) if post + end.compact.map(&:valid?).all? end + # Cambia una licencia + # + # @param :post [Post] + # @return [Post] def change_licencia(post:) params = ActionController::Parameters.new( post: { @@ -145,8 +148,11 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do params: params).update end + # Agrega un código de conducta + # + # @return [Boolean] def add_code_of_conduct - return unless site.layout?(:code_of_conduct) || site.layout?(:page) + return true unless site.layout?(:code_of_conduct) || site.layout?(:page) # TODO: soportar más códigos de conducta coc = CodeOfConduct.first @@ -163,7 +169,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do ) PostService.new(site: site, usuarie: usuarie, params: params).create - end + end.compact.map(&:valid?).all? end # Crea los deploys necesarios para sincronizar a otros nodos de Sutty @@ -176,7 +182,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do private def with_all_locales(&block) - site.locales.each do |locale| + site.locales.map do |locale| next unless I18n.available_locales.include? locale Mobility.with_locale(locale) do From 136a9e3edba9f5fe719c072c4b020996e90a9a28 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:44:17 -0300 Subject: [PATCH 066/106] =?UTF-8?q?fix:=20traducir=20la=20descripci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/site_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 47b532f4..449db16a 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -110,7 +110,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do slug: Jekyll::Utils.slugify(I18n.t('activerecord.models.licencia')), lang: lang, title: site.licencia.name, - description: I18n.t('sites.form.licencia.title'), + description: site.licencia.description, content: CommonMarker.render_html(site.licencia.deed) } ) From caa4861d79172cf6e49dab6c0e5cade15abcf023 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 19:54:04 -0300 Subject: [PATCH 067/106] fix: poder pasar el slug como parametro como slug es un atributo privado, hay que asignarlo manualmente --- app/services/post_service.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/services/post_service.rb b/app/services/post_service.rb index e448bb4c..81ebe4a1 100644 --- a/app/services/post_service.rb +++ b/app/services/post_service.rb @@ -12,6 +12,10 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do post.usuaries << usuarie params[:post][:draft] = true if site.invitade? usuarie + params.require(:post).permit(:slug).tap do |p| + post.slug.value = p[:slug] if p[:slug].present? + end + commit(action: :created, file: update_related_posts) if post.update(post_params) # Devolver el post aunque no se haya salvado para poder rescatar los From 0263169074f7795ae719d074f9f90f7aa2163d5c Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 20:00:39 -0300 Subject: [PATCH 068/106] fix: devolver true aunque no haga falta modificar la configuracion --- app/models/site/config.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/site/config.rb b/app/models/site/config.rb index 3215277e..11277a19 100644 --- a/app/models/site/config.rb +++ b/app/models/site/config.rb @@ -31,7 +31,7 @@ class Site # Escribe los cambios en el repositorio def write - return if persisted? + return true if persisted? @saved = Site::Writer.new(site: site, file: path, content: content.to_yaml).save From 0817139032ad0a93d4618fa6bcc78e474a4212bb Mon Sep 17 00:00:00 2001 From: f Date: Wed, 22 Mar 2023 21:01:29 -0300 Subject: [PATCH 069/106] =?UTF-8?q?feat:=20agregar=20pol=C3=ADtica=20de=20?= =?UTF-8?q?privacidad?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/privacy_policy.rb | 14 +++ app/services/site_service.rb | 26 +++- config/initializers/inflections.rb | 4 + .../20230322231344_add_privacy_policy.rb | 22 ++++ db/seeds/privacy_policies.yml | 113 ++++++++++++++++++ 5 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 app/models/privacy_policy.rb create mode 100644 db/migrate/20230322231344_add_privacy_policy.rb create mode 100644 db/seeds/privacy_policies.yml diff --git a/app/models/privacy_policy.rb b/app/models/privacy_policy.rb new file mode 100644 index 00000000..8805daa9 --- /dev/null +++ b/app/models/privacy_policy.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Políticas de privacidad +class PrivacyPolicy < ApplicationRecord + extend Mobility + + translates :title, type: :string, locale_accessors: true + translates :description, type: :text, locale_accessors: true + translates :content, type: :text, locale_accessors: true + + validates :title, presence: true, uniqueness: true + validates :description, presence: true + validates :content, presence: true +end diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 449db16a..64b25297 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -16,7 +16,8 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do site.config.write && commit_config(action: :create) && add_licencias && - add_code_of_conduct + add_code_of_conduct && + add_privacy_policy end site @@ -172,6 +173,29 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do end.compact.map(&:valid?).all? end + # Agrega política de privacidad + # + # @return [Boolean] + def add_privacy_policy + return true unless site.layout?(:privacy_policy) || site.layout?(:page) + + pp = PrivacyPolicy.first + + with_all_locales do |locale| + params = ActionController::Parameters.new( + post: { + layout: site.layout?(:privacy_policy) ? 'privacy_policy' : 'page', + lang: locale.to_s, + title: pp.title, + description: pp.description, + content: CommonMarker.render_html(pp.content) + } + ) + + PostService.new(site: site, usuarie: usuarie, params: params).create + end.compact.map(&:valid?).all? + end + # Crea los deploys necesarios para sincronizar a otros nodos de Sutty def sync_nodes Rails.application.nodes.each do |node| diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb index 46cb9d78..6002ee65 100644 --- a/config/initializers/inflections.rb +++ b/config/initializers/inflections.rb @@ -15,6 +15,8 @@ ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.singular 'rollups', 'rollup' inflect.plural 'code_of_conduct', 'codes_of_conduct' inflect.singular 'codes_of_conduct', 'code_of_conduct' + inflect.plural 'privacy_policy', 'privacy_policies' + inflect.singular 'privacy_policies', 'privacy_policy' end ActiveSupport::Inflector.inflections(:es) do |inflect| @@ -32,4 +34,6 @@ ActiveSupport::Inflector.inflections(:es) do |inflect| inflect.singular 'rollups', 'rollup' inflect.plural 'code_of_conduct', 'codes_of_conduct' inflect.singular 'codes_of_conduct', 'code_of_conduct' + inflect.plural 'privacy_policy', 'privacy_policies' + inflect.singular 'privacy_policies', 'privacy_policy' end diff --git a/db/migrate/20230322231344_add_privacy_policy.rb b/db/migrate/20230322231344_add_privacy_policy.rb new file mode 100644 index 00000000..e0d7ae59 --- /dev/null +++ b/db/migrate/20230322231344_add_privacy_policy.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +# Agrega políticas de privacidad +class AddPrivacyPolicy < ActiveRecord::Migration[6.1] + def up + create_table :privacy_policies do |t| + t.timestamps + t.string :title + t.text :description + t.text :content + end + + # XXX: En lugar de ponerlo en las seeds + YAML.safe_load(File.read('db/seeds/privacy_policies.yml')).each do |pp| + PrivacyPolicy.new(**pp).save! + end + end + + def down + drop_table :privacy_policies + end +end diff --git a/db/seeds/privacy_policies.yml b/db/seeds/privacy_policies.yml new file mode 100644 index 00000000..98ce8379 --- /dev/null +++ b/db/seeds/privacy_policies.yml @@ -0,0 +1,113 @@ +--- +- title_en: "Privacy Policy" + title_es: "Políticas de privacidad" + description_en: "With what care does this site handles personal data of its users and visitors?" + description_es: "¿Cuáles son los cuidados de este sitio con respecto a sus usuaries y visitantes?" + content_en: | + > We use "them" as neutral pronoun to refer to people regardless of + > gender identity. + + This document details Sutty's privacy policy, including web site, + platform, other infrastructure (support channels, etc.) and web sites + generated by users. + + ## This is too long! + + * Sutty doesn't collect any kind of personal data. + + * Sutty may only collect statistical data that doesn't identify + individuals. + + ## Analytic data + + Sutty may only collect data for analytics (number of visits, duration, + etc.), not associated to personal data. + + Analytical data collected for every web site can only be used internally + by Sutty. Sutty doesn't share any data privately with any third + parties. Selected analytical data could be used publicly. + + Sutty doesn't recommend personal data collection in any way, but it + doesn't monitor if its users use third party services with their own + privacy policies. We recommend users and visitors to inform themselves + before using third parties analytics services. + + ## No personal data collection + + Sutty doesn't collect IP addresses from users nor visitors in any way. + + Sutty doesn't ask for personal data for registering user accounts in its + platform. + + Sutty only uses session "cookies" to identify users during their use of + the platform. It doesn't use "cookies" to identify visitors of web + sites hosted by Sutty. + + The only exception where Sutty could collect personal data is during + service payment. Digital safety measures will be taken to keep this + information and to discard it if possible after needed. + + Users will be notified when their personal data is removed. + + If users decide to host their web sites with third parties, they must + inform themselves about the corresponding privacy policies. Sutty only + recommends third parties with privacy policies compatible with these. + content_es: | + > Utilizamos la e como pronombre neutro para referirnos a personas + > independientemente de su identidad de género, por ejemplo “usuarie”. + + Este documento detalla la política de privacidad de Sutty, incluyendo + sitio web, plataforma de edición, infraestructura relacionada (salas de + chat, etc.) y sitios creados por sus usuaries a través de la plataforma, + en adelante "Sutty". + + ## ¡Esto es demasiado largo! + + Un resumen: + + * Sutty no recolecta datos personales de ningún tipo + + * Sutty solo recolectaría datos analíticos que no identifican a + personas + + ## Datos analíticos + + La única recolección de datos realizada por Sutty es con fines + analíticos (cantidad de visitas, duración, etc.), no asociados a datos + personales. + + Los datos analíticos recolectados por cada sitio podrán ser utilizados + internamente por Sutty. Sutty no comparte datos analíticos con + terceros en forma privada. Datos analíticos seleccionados podrán ser + utilizados públicamente. + + Sutty no recomienda la recolección de datos personales de ninguna forma, + pero no monitorea que les usuaries utilicen servicios de terceros con + sus propias políticas de privacidad. Recomendamos a les usuaries y + visitantes informarse antes de utilizar servicios de estadísticas de + terceros. + + ## No registro de datos personales + + Sutty no registra direcciones IP de usuaries ni de visitantes de ninguna + forma. + + Sutty no solicita datos personales para el registro de cuentas de + usuarie en su plataforma. + + Sutty solo utiliza “cookies” de sesión para identificar usuaries + mientras utilicen la plataforma. No se utilizan “cookies” para + identificar visitantes a los sitios alojados por Sutty. + + El único caso en el que Sutty podría solicitar datos personales es + durante el pago de servicios. Se tomarán medidas de seguridad digital + para salvaguardar esta información y descartar lo que sea posible una + vez que ya no sea necesaria. + + Se notificará a les usuaries cuando su información personal sea + eliminada. + + Si les usuaries deciden alojar sus sitios con terceros, deberán + informarse de las políticas de privacidad correspondientes. Sutty + recomienda servicios de terceros con políticas de privacidad coherentes + con estas. From d01f4ae5e2432b7f34835a1ca50e1629d8ba96c1 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 23 Mar 2023 16:53:06 -0300 Subject: [PATCH 070/106] =?UTF-8?q?fix:=20volver=20a=20leer=20el=20sitio?= =?UTF-8?q?=20despu=C3=A9s=20de=20guardarlo=20#12755?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/site_service.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 64b25297..eaefca3a 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -15,6 +15,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do site.save && site.config.write && commit_config(action: :create) && + site.reset.nil? && add_licencias && add_code_of_conduct && add_privacy_policy @@ -29,6 +30,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do site.update(params) && site.config.write && commit_config(action: :update) && + site.reset.nil? && change_licencias end From b51eb6856c358414a7d4f86cf45db8f511e8a78d Mon Sep 17 00:00:00 2001 From: f Date: Fri, 24 Mar 2023 11:50:25 -0300 Subject: [PATCH 071/106] =?UTF-8?q?fix:=20siempre=20devolver=20una=20relac?= =?UTF-8?q?i=C3=B3n=20#12768?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/metadata_locales.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/metadata_locales.rb b/app/models/metadata_locales.rb index 2e9080c9..3790b944 100644 --- a/app/models/metadata_locales.rb +++ b/app/models/metadata_locales.rb @@ -44,6 +44,6 @@ class MetadataLocales < MetadataHasAndBelongsToMany def posts other_locales.map do |locale| site.posts(lang: locale).where(layout: post.layout.value) - end.reduce(&:concat) + end.reduce(&:concat) || PostRelation.new end end From 42b2549f09e5fe9b3f33d6c632995253155400da Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 13:46:30 -0300 Subject: [PATCH 072/106] =?UTF-8?q?feat:=20agregar=20una=20descripci=C3=B3?= =?UTF-8?q?n=20corta=20a=20la=20licencia?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit que es lo que usan las plantillas como aviso de licencia --- app/services/site_service.rb | 2 +- ...5163802_add_short_description_to_licencias.rb | 16 ++++++++++++++++ db/seeds/licencias.yml | 6 ++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20230325163802_add_short_description_to_licencias.rb diff --git a/app/services/site_service.rb b/app/services/site_service.rb index eaefca3a..2719a26c 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -113,7 +113,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do slug: Jekyll::Utils.slugify(I18n.t('activerecord.models.licencia')), lang: lang, title: site.licencia.name, - description: site.licencia.description, + description: site.licencia.short_description, content: CommonMarker.render_html(site.licencia.deed) } ) diff --git a/db/migrate/20230325163802_add_short_description_to_licencias.rb b/db/migrate/20230325163802_add_short_description_to_licencias.rb new file mode 100644 index 00000000..efcc01e4 --- /dev/null +++ b/db/migrate/20230325163802_add_short_description_to_licencias.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +# Agrega descripciones cortas a las licencias +class AddShortDescriptionToLicencias < ActiveRecord::Migration[6.1] + def up + add_column :licencias, :short_description, :string + + YAML.safe_load_file('db/seeds/licencias.yml').each do |licencia| + Licencia.find_by_icons(licencia['icons']).update licencia + end + end + + def down + remove_column :licencias, :short_description + end +end diff --git a/db/seeds/licencias.yml b/db/seeds/licencias.yml index cbe3bace..c5e2886a 100644 --- a/db/seeds/licencias.yml +++ b/db/seeds/licencias.yml @@ -1,6 +1,8 @@ --- - name_en: 'Peer Production License' name_es: 'Licencia de Producción de Pares' + short_description_en: "This work is licensed under a Peer Production License" + short_description_es: "Esta obra está bajo una Licencia de Producción de Pares" icons: "/images/ppl.png" url_en: 'https://wiki.p2pfoundation.net/Peer_Production_License' url_es: 'https://endefensadelsl.org/ppl_es.html' @@ -100,6 +102,8 @@ hacerlo es enlazar a esta página. - icons: "/images/by.png" + short_description_en: "This work is licensed under a Creative Commons Attribution 4.0 International License." + short_description_es: "Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional." name_en: 'Creative Commons Attribution 4.0 International (CC BY 4.0)' description_en: "This license gives everyone the freedom to use, adapt, and redistribute the contents of your site by requiring @@ -194,6 +198,8 @@ - icons: "/images/sa.png" name_en: "Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)" name_es: "Creative Commons Atribución-CompartirIgual 4.0 Internacional (CC BY-SA 4.0)" + short_description_en: "This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License." + short_description_es: "Esta obra está bajo una Licencia Creative Commons Atribución-CompartirIgual 4.0 Internacional." url_en: 'https://creativecommons.org/licenses/by-sa/4.0/' url_es: 'https://creativecommons.org/licenses/by-sa/4.0/deed.es' description_en: "This license is the same as the CC-BY 4.0 but it adds From c62d0d3a7254779f728fd14c224e2dc56127082e Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 13:48:30 -0300 Subject: [PATCH 073/106] =?UTF-8?q?fixup!=20feat:=20agregar=20una=20descri?= =?UTF-8?q?pci=C3=B3n=20corta=20a=20la=20licencia?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/licencia.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/models/licencia.rb b/app/models/licencia.rb index c0eb1c80..f0a542ef 100644 --- a/app/models/licencia.rb +++ b/app/models/licencia.rb @@ -7,6 +7,7 @@ class Licencia < ApplicationRecord translates :name, type: :string, locale_accessors: true translates :url, type: :string, locale_accessors: true translates :description, type: :text, locale_accessors: true + translates :short_description, type: :string, locale_accessors: true translates :deed, type: :text, locale_accessors: true has_many :sites @@ -14,5 +15,6 @@ class Licencia < ApplicationRecord validates :name, presence: true, uniqueness: true validates :url, presence: true validates :description, presence: true + validates :short_description, presence: true validates :deed, presence: true end From d44ca16f81ec09f39713a94ee74da2b28c8b91e0 Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 13:51:07 -0300 Subject: [PATCH 074/106] =?UTF-8?q?fix:=20cambiar=20la=20descripci=C3=B3n?= =?UTF-8?q?=20de=20la=20licencia=20tambi=C3=A9n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/site_service.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 2719a26c..ce596482 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -143,6 +143,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do params = ActionController::Parameters.new( post: { title: site.licencia.name, + description: site.licencia.short_description, content: CommonMarker.render_html(site.licencia.deed) } ) From 960c8dcca450a27ab410833e6c5c35bcb9b8ccbf Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 14:50:36 -0300 Subject: [PATCH 075/106] feat: implementar un servicio liviano de git-lfs #9361 --- app/services/lfs_object_service.rb | 64 ++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 app/services/lfs_object_service.rb diff --git a/app/services/lfs_object_service.rb b/app/services/lfs_object_service.rb new file mode 100644 index 00000000..65db113d --- /dev/null +++ b/app/services/lfs_object_service.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +# Representa un objeto git LFS +class LfsObjectService + attr_reader :site, :blob, :usuarie + + # @param :site [Site] + # @param :blob [ActiveStorage::Blob] + def initialize(site:, blob:, usuarie:) + @site = site + @blob = blob + @usuarie = usuarie + end + + def process + # Crear el directorio + FileUtils.mkdir_p(File.dirname(object_path)) + + # Mover el archivo + FileUtils.mv(path, object_path) unless File.exist? object_path + + # Crear el pointer + Site::Writer.new(site: site, file: path, content: pointer).save + + # Commitear el pointer + site.repository.commit(file: path, usuarie: usuarie, message: File.basename(path)) + + # Eliminar el pointer + FileUtils.rm(path) + + # Hacer link duro del objeto al archivo + FileUtils.ln(object_path, path) + end + + # @return [String] + def path + @path ||= blob.service.path_for(blob.key) + end + + # @return [String] + def digest + @digest ||= Digest::SHA256.file(path).hexdigest + end + + # @return [String] + def object_path + @git_lfs_object_path ||= File.join(site.path, '.git', 'lfs', 'objects', digest[0..1], digest[2..3], digest) + end + + # @return [Integer] + def size + @size ||= File.size(File.exist?(object_path) ? object_path : path) + end + + # @return [String] + def pointer + @pointer ||= + <<~POINTER + version https://git-lfs.github.com/spec/v1 + oid sha256:#{digest} + size #{size} + POINTER + end +end From 2215a00727d60d18147e76692dfe797a1183bd38 Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 15:22:54 -0300 Subject: [PATCH 076/106] feat: commitear el archivo en lfs al subirlo --- app/lib/active_storage/service/jekyll_service.rb | 15 +++++++++------ app/services/lfs_object_service.rb | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/app/lib/active_storage/service/jekyll_service.rb b/app/lib/active_storage/service/jekyll_service.rb index 88ffa83c..6763ee0d 100644 --- a/app/lib/active_storage/service/jekyll_service.rb +++ b/app/lib/active_storage/service/jekyll_service.rb @@ -4,11 +4,6 @@ module ActiveStorage class Service # Sube los archivos a cada repositorio y los agrega al LFS de su # repositorio git. - # - # @todo: Implementar LFS. No nos gusta mucho la idea porque duplica - # el espacio en disco, pero es la única forma que tenemos (hasta que - # implementemos IPFS) para poder transferir los archivos junto con el - # sitio. class JekyllService < Service::DiskService # Genera un servicio para un sitio determinado # @@ -27,7 +22,10 @@ module ActiveStorage # @param :checksum [String] def upload(key, io, checksum: nil, **) instrument :upload, key: key, checksum: checksum do - IO.copy_stream(io, make_path_for(key)) unless exist?(key) + unless exist?(key) + IO.copy_stream(io, make_path_for(key)) + LfsObjectService.new(site: site, usuarie: current_usuarie, blob: blob).process + end ensure_integrity_of(key, checksum) if checksum end end @@ -91,6 +89,11 @@ module ActiveStorage def path_for(key) File.join root, folder_for(key), filename_for(key) end + + # @return [Site] + def site + @site ||= Site.find_by_name(File.basename(root)) + end end end end diff --git a/app/services/lfs_object_service.rb b/app/services/lfs_object_service.rb index 65db113d..61775e12 100644 --- a/app/services/lfs_object_service.rb +++ b/app/services/lfs_object_service.rb @@ -44,7 +44,7 @@ class LfsObjectService # @return [String] def object_path - @git_lfs_object_path ||= File.join(site.path, '.git', 'lfs', 'objects', digest[0..1], digest[2..3], digest) + @object_path ||= File.join(site.path, '.git', 'lfs', 'objects', digest[0..1], digest[2..3], digest) end # @return [Integer] From 2940b5d3e818d047afedf173df0d7a2d6b6f0613 Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 15:29:49 -0300 Subject: [PATCH 077/106] =?UTF-8?q?fix:=20no=20podemos=20saber=20qui=C3=A9?= =?UTF-8?q?n=20subi=C3=B3=20el=20archivo=20todav=C3=ADa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/lib/active_storage/service/jekyll_service.rb | 2 +- app/services/lfs_object_service.rb | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/lib/active_storage/service/jekyll_service.rb b/app/lib/active_storage/service/jekyll_service.rb index 6763ee0d..f399f440 100644 --- a/app/lib/active_storage/service/jekyll_service.rb +++ b/app/lib/active_storage/service/jekyll_service.rb @@ -24,7 +24,7 @@ module ActiveStorage instrument :upload, key: key, checksum: checksum do unless exist?(key) IO.copy_stream(io, make_path_for(key)) - LfsObjectService.new(site: site, usuarie: current_usuarie, blob: blob).process + LfsObjectService.new(site: site, blob: blob).process end ensure_integrity_of(key, checksum) if checksum end diff --git a/app/services/lfs_object_service.rb b/app/services/lfs_object_service.rb index 61775e12..bb62301d 100644 --- a/app/services/lfs_object_service.rb +++ b/app/services/lfs_object_service.rb @@ -2,14 +2,13 @@ # Representa un objeto git LFS class LfsObjectService - attr_reader :site, :blob, :usuarie + attr_reader :site, :blob # @param :site [Site] # @param :blob [ActiveStorage::Blob] - def initialize(site:, blob:, usuarie:) + def initialize(site:, blob:) @site = site @blob = blob - @usuarie = usuarie end def process @@ -23,7 +22,7 @@ class LfsObjectService Site::Writer.new(site: site, file: path, content: pointer).save # Commitear el pointer - site.repository.commit(file: path, usuarie: usuarie, message: File.basename(path)) + site.repository.commit(file: path, usuarie: author, message: File.basename(path)) # Eliminar el pointer FileUtils.rm(path) @@ -61,4 +60,8 @@ class LfsObjectService size #{size} POINTER end + + def author + @author ||= GitAuthor.new email: "disk_service@#{Site.domain}", name: 'DiskService' + end end From 2fb5bc24d5d21fdc2d32146ef114518ed96140c8 Mon Sep 17 00:00:00 2001 From: f Date: Sat, 25 Mar 2023 15:34:47 -0300 Subject: [PATCH 078/106] fix: encontrar el blob para este servicio --- app/lib/active_storage/service/jekyll_service.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/app/lib/active_storage/service/jekyll_service.rb b/app/lib/active_storage/service/jekyll_service.rb index f399f440..e6c5fda6 100644 --- a/app/lib/active_storage/service/jekyll_service.rb +++ b/app/lib/active_storage/service/jekyll_service.rb @@ -24,7 +24,7 @@ module ActiveStorage instrument :upload, key: key, checksum: checksum do unless exist?(key) IO.copy_stream(io, make_path_for(key)) - LfsObjectService.new(site: site, blob: blob).process + LfsObjectService.new(site: site, blob: blob_for(key)).process end ensure_integrity_of(key, checksum) if checksum end @@ -77,7 +77,7 @@ module ActiveStorage # @param :key [String] # @return [String] def filename_for(key) - ActiveStorage::Blob.where(key: key).limit(1).pluck(:filename).first.tap do |filename| + blob_for(key).filename.to_s.tap do |filename| raise ArgumentError, "Filename for key #{key} is blank" if filename.blank? end end @@ -92,7 +92,11 @@ module ActiveStorage # @return [Site] def site - @site ||= Site.find_by_name(File.basename(root)) + @site ||= Site.find_by_name(name) + end + + def blob_for(key) + ActiveStorage::Blob.find_by(key: key, service_name: name) end end end From 6b759c92ce0ad52caae465926af55edccc85f402 Mon Sep 17 00:00:00 2001 From: f Date: Mon, 27 Mar 2023 11:45:23 -0300 Subject: [PATCH 079/106] fix: instalar las gemas cuando sea necesario #12755 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit si se modificó el gemfile queremos volver a instalarlas también --- app/models/site.rb | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/app/models/site.rb b/app/models/site.rb index 4b2a8eb9..6110f104 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -553,10 +553,33 @@ class Site < ApplicationRecord Dir.chdir path, &block end + # Instala las gemas cuando es necesario: + # + # * El sitio existe + # * No están instaladas + # * El archivo Gemfile se modificó + # * El archivo Gemfile.lock se modificó def install_gems return unless persisted? - return if Rails.root.join('_storage', 'gems', name).directory? - deploys.find_by_type('DeployLocal').send(:bundle) + if !gem_dir? || gemfile_updated? || gemfile_lock_updated? + deploys.find_by_type('DeployLocal').send(:bundle) + touch + end + end + + # Detecta si el repositorio de gemas existe + def gem_dir? + Rails.root.join('_storage', 'gems', name).directory? + end + + # Detecta si el Gemfile fue modificado + def gemfile_updated? + updated_at > File.mtime(File.join(path, 'Gemfile')) + end + + # Detecta si el Gemfile.lock fue modificado + def gemfile_lock_updated? + updated_at > File.mtime(File.join(path, 'Gemfile.lock')) end end From 117b8502769b1b554878a219b32f15d4a4dfb13b Mon Sep 17 00:00:00 2001 From: f Date: Thu, 30 Mar 2023 10:27:30 -0300 Subject: [PATCH 080/106] fix: hacer pull antes de push --- .woodpecker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.woodpecker.yml b/.woodpecker.yml index ab4887ac..887d397f 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -47,6 +47,7 @@ pipeline: - "dotenv RAILS_ENV=production bundle exec rails assets:precompile" - "dotenv RAILS_ENV=production bundle exec rails assets:clean" - "git add public && git commit -m \"ci: assets [skip ci]\"" + - "git pull upstream ${CI_COMMIT_BRANCH}" - "git push upstream ${CI_COMMIT_BRANCH}" secrets: - "SSH_KEY" From edd88d04b93aee72429c826ccdf3437a4b2aa0f2 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 30 Mar 2023 11:29:23 -0300 Subject: [PATCH 081/106] =?UTF-8?q?feat:=20pre=20comprimir=20con=20brotli?= =?UTF-8?q?=20tambi=C3=A9n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .woodpecker.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 887d397f..19bd429b 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -28,7 +28,7 @@ pipeline: assets: image: "registry.nulo.in/sutty/panel:${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" commands: - - "apk add python2 dotenv openssh-client" + - "apk add python2 dotenv openssh-client brotli" - "install -d -m 700 ~/.ssh/" - "echo \"$${KNOWN_HOSTS}\" | base64 -d >> ~/.ssh/known_hosts" - "chmod 600 ~/.ssh/known_hosts" @@ -46,6 +46,7 @@ pipeline: - "dotenv RAILS_ENV=production bundle exec rails webpacker:clobber" - "dotenv RAILS_ENV=production bundle exec rails assets:precompile" - "dotenv RAILS_ENV=production bundle exec rails assets:clean" + - "find public -type f -print0 | xargs -r0 brotli -k9" - "git add public && git commit -m \"ci: assets [skip ci]\"" - "git pull upstream ${CI_COMMIT_BRANCH}" - "git push upstream ${CI_COMMIT_BRANCH}" From 661655abb5d03c2d2e21072de8230a05e324dc28 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 30 Mar 2023 13:51:09 -0300 Subject: [PATCH 082/106] =?UTF-8?q?fix:=20hacer=20el=20deploy=20cuando=20e?= =?UTF-8?q?l=20sitio=20ya=20est=C3=A1=20guardado=20#12276?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/site_service.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 75577226..70824422 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -30,11 +30,10 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do site.reset.nil? && add_licencias && add_code_of_conduct && - add_privacy_policy + add_privacy_policy && + deploy end - deploy - site end From 0744e124e350b45a1981080de5981784811dcee7 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 10:56:09 -0300 Subject: [PATCH 083/106] fixup! fix: instalar las gemas cuando sea necesario #12755 --- app/models/site.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/site.rb b/app/models/site.rb index 6110f104..804de42c 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -575,11 +575,11 @@ class Site < ApplicationRecord # Detecta si el Gemfile fue modificado def gemfile_updated? - updated_at > File.mtime(File.join(path, 'Gemfile')) + updated_at < File.mtime(File.join(path, 'Gemfile')) end # Detecta si el Gemfile.lock fue modificado def gemfile_lock_updated? - updated_at > File.mtime(File.join(path, 'Gemfile.lock')) + updated_at < File.mtime(File.join(path, 'Gemfile.lock')) end end From 8c5535c5c7a1dc4af94b57ed0e948c0e191f0350 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 17:39:25 -0300 Subject: [PATCH 084/106] =?UTF-8?q?fix:=20ordenar=20layouts=20alfab=C3=A9t?= =?UTF-8?q?icamente=20#5085?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/posts/index.haml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/posts/index.haml b/app/views/posts/index.haml index a82616d8..8a2a678d 100644 --- a/app/views/posts/index.haml +++ b/app/views/posts/index.haml @@ -5,7 +5,7 @@ %h3= t('posts.new') %table.mb-3 - - @site.layouts.each do |layout| + - @site.layouts.sort_by(&:humanized_name).each do |layout| - next if layout.hidden? %tr %th= layout.humanized_name From 59e97ef6856fb8617df3edaab6dcf7e2df5554e5 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 18:16:11 -0300 Subject: [PATCH 085/106] =?UTF-8?q?fix:=20forzar=20la=20compilaci=C3=B3n?= =?UTF-8?q?=20de=20brotli?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .woodpecker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 19bd429b..1d760b52 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -46,7 +46,7 @@ pipeline: - "dotenv RAILS_ENV=production bundle exec rails webpacker:clobber" - "dotenv RAILS_ENV=production bundle exec rails assets:precompile" - "dotenv RAILS_ENV=production bundle exec rails assets:clean" - - "find public -type f -print0 | xargs -r0 brotli -k9" + - "find public -type f -print0 | xargs -r0 brotli -k9f" - "git add public && git commit -m \"ci: assets [skip ci]\"" - "git pull upstream ${CI_COMMIT_BRANCH}" - "git push upstream ${CI_COMMIT_BRANCH}" From 0d0c8c8b073598d9a74114d8ec65923c90ab7e32 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 19:31:22 -0300 Subject: [PATCH 086/106] =?UTF-8?q?fix:=20mostrar=20los=20dise=C3=B1os=20e?= =?UTF-8?q?n=20dos=20columnas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/sites/_form.haml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/views/sites/_form.haml b/app/views/sites/_form.haml index 757b8b48..2d8ea4fb 100644 --- a/app/views/sites/_form.haml +++ b/app/views/sites/_form.haml @@ -53,10 +53,10 @@ = render 'bootstrap/alert' do = t('activerecord.errors.models.site.attributes.design_id.layout_incompatible.help', layouts: site.incompatible_layouts.to_sentence) - .row.designs + .row.row-cols-1.row-cols-md-2.designs -# Demasiado complejo para un f.collection_radio_buttons - Design.all.find_each do |design| - .design.col-md-4.d-flex.flex-column + .design.col.d-flex.flex-column .custom-control.custom-radio = f.radio_button :design_id, design.id, checked: design.id == site.design_id, From c2fafac7f0556c12015fb0bf8c102cc22c15723f Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 19:32:36 -0300 Subject: [PATCH 087/106] feat: informar el estado del sitio #10492 --- app/models/site.rb | 1 + app/models/site/build_stats.rb | 45 ++++++++++++++++++++++++++++++++++ app/views/posts/index.haml | 4 ++- app/views/sites/_status.haml | 19 ++++++++++++++ config/locales/en.yml | 4 +++ config/locales/es.yml | 4 +++ 6 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 app/models/site/build_stats.rb create mode 100644 app/views/sites/_status.haml diff --git a/app/models/site.rb b/app/models/site.rb index 4b2a8eb9..6aa96612 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -7,6 +7,7 @@ class Site < ApplicationRecord include Site::Forms include Site::FindAndReplace include Site::Api + include Site::BuildStats include Tienda # Cifrar la llave privada que cifra y decifra campos ocultos. Sutty diff --git a/app/models/site/build_stats.rb b/app/models/site/build_stats.rb new file mode 100644 index 00000000..8b23942d --- /dev/null +++ b/app/models/site/build_stats.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +class Site + module BuildStats + extend ActiveSupport::Concern + + included do + # Devuelve el tiempo promedio de publicación para este sitio + # + # @return [Integer] + def average_publication_time + build_stats.group(:action).average(:seconds).values.reduce(:+).round + end + + # Devuelve el tiempo promedio de compilación para sitios similares + # a este. + # + # @return [Integer] + def average_publication_time_for_similar_sites + similar_deploys = Deploy.where(type: deploys.pluck(:type)).pluck(:id) + + BuildStat.where(deploy_id: similar_deploys).group(:action).average(:seconds).values.reduce(:+).round + end + + # Define si podemos calcular el tiempo promedio de publicación + # para este sitio + # + # @return [Boolean] + def average_publication_time_calculable? + build_stats.jekyll.where(status: true).count > 0 + end + + def similar_sites? + !design.no_theme? + end + + # Detecta si el sitio todavía no ha sido publicado + # + # @return [Boolean] + def not_published_yet? + build_stats.jekyll.where(status: true).count.zero? + end + end + end +end diff --git a/app/views/posts/index.haml b/app/views/posts/index.haml index dbeddaad..f7b884af 100644 --- a/app/views/posts/index.haml +++ b/app/views/posts/index.haml @@ -1,7 +1,9 @@ %main.row %aside.menu.col-md-3 - %h1= link_to @site.title, @site.url + %h1= @site.title %p.lead= @site.description + - cache_if @usuarie, [@site, I18n.locale] do + = render 'sites/status', site: @site %h3= t('posts.new') %table.mb-3 diff --git a/app/views/sites/_status.haml b/app/views/sites/_status.haml new file mode 100644 index 00000000..fb38896a --- /dev/null +++ b/app/views/sites/_status.haml @@ -0,0 +1,19 @@ +- link = nil +- if site.not_published_yet? + - message = t('.not_published_yet') +- if site.building? + - if site.average_publication_time_calculable? + - average_building_time = site.average_building_time + - elsif !site.similar_sites? + - average_building_time = 60 + - else + - average_building_time = site.average_publication_time_for_similar_sites + + - average_publication_time_human = distance_of_time_in_words average_building_time + - message = t('.building', average_time: average_publication_time_human, seconds: average_building_time) +- else + - message = t('.available') + - link = true + += render 'bootstrap/alert' do + = link_to_if link, message.html_safe, site.url diff --git a/config/locales/en.yml b/config/locales/en.yml index 567ab6bb..ee16f506 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -330,6 +330,10 @@ en: designer_url: 'Support the designer' static_file_migration: 'File migration' find_and_replace: 'Search and replace' + status: + building: "Your site is building, please wait ..." + not_published_yet: "Your site is being published for the first time, please wait up to 1 minute..." + available: "Your site is available! Click here to visit it." index: title: 'My Sites' pull: 'Upgrade' diff --git a/config/locales/es.yml b/config/locales/es.yml index 0a829e4a..e3d3f2ef 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -335,6 +335,10 @@ es: designer_url: 'Apoyá a le(s) diseñadore(s)' static_file_migration: 'Migración de archivos' find_and_replace: 'Búsqueda y reemplazo' + status: + building: "Tu sitio se está publicando, por favor espera ..." + not_published_yet: "Tu sitio se está publicando por primera vez, por favor espera hasta un minuto..." + available: "¡Tu sitio está disponible! Cliquea aquí para visitarlo." index: title: 'Mis sitios' pull: 'Actualizar' From 0442aa1e0672167a9502a5c5b7d14440bd7fdf88 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 19:37:47 -0300 Subject: [PATCH 088/106] fixup! feat: informar el estado del sitio #10492 --- app/views/sites/_status.haml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/sites/_status.haml b/app/views/sites/_status.haml index fb38896a..52afa3ca 100644 --- a/app/views/sites/_status.haml +++ b/app/views/sites/_status.haml @@ -3,7 +3,7 @@ - message = t('.not_published_yet') - if site.building? - if site.average_publication_time_calculable? - - average_building_time = site.average_building_time + - average_building_time = site.average_publication_time - elsif !site.similar_sites? - average_building_time = 60 - else From 8f19f837cdb11740cfe58d8be7fee4af30a70962 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 20:20:37 -0300 Subject: [PATCH 089/106] =?UTF-8?q?fix:=20hacer=20que=20devise=20respete?= =?UTF-8?q?=20el=20idioma=20de=20la=20sesi=C3=B3n=20#10478?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/lib/devise/failure_app_decorator.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 app/lib/devise/failure_app_decorator.rb diff --git a/app/lib/devise/failure_app_decorator.rb b/app/lib/devise/failure_app_decorator.rb new file mode 100644 index 00000000..f17cb482 --- /dev/null +++ b/app/lib/devise/failure_app_decorator.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +module Devise + module FailureAppDecorator + extend ActiveSupport::Concern + + included do + include AbstractController::Callbacks + + around_action :set_locale + + private + + def set_locale(&action) + I18n.with_locale(session[:locale] || I18n.locale, &action) + end + end + end +end + +Devise::FailureApp.include Devise::FailureAppDecorator From f62d7fcc800fd5e6c5eeea9306ee60df49ae9943 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 20:51:20 -0300 Subject: [PATCH 090/106] =?UTF-8?q?fix:=20esperar=20a=20que=20la=20primera?= =?UTF-8?q?=20publicaci=C3=B3n=20termine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/site/build_stats.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/site/build_stats.rb b/app/models/site/build_stats.rb index 8b23942d..6eebcc84 100644 --- a/app/models/site/build_stats.rb +++ b/app/models/site/build_stats.rb @@ -27,7 +27,7 @@ class Site # # @return [Boolean] def average_publication_time_calculable? - build_stats.jekyll.where(status: true).count > 0 + build_stats.jekyll.where(status: true).count > 1 end def similar_sites? From 5ae3fe0b354a9649c8b079c2f5966b23cd7b7eef Mon Sep 17 00:00:00 2001 From: f Date: Fri, 31 Mar 2023 20:52:35 -0300 Subject: [PATCH 091/106] =?UTF-8?q?fix:=20dar=20una=20acci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/locales/en.yml | 2 +- config/locales/es.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/config/locales/en.yml b/config/locales/en.yml index ee16f506..f3e319ee 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -331,7 +331,7 @@ en: static_file_migration: 'File migration' find_and_replace: 'Search and replace' status: - building: "Your site is building, please wait ..." + building: "Your site is building, please wait to refresh this page..." not_published_yet: "Your site is being published for the first time, please wait up to 1 minute..." available: "Your site is available! Click here to visit it." index: diff --git a/config/locales/es.yml b/config/locales/es.yml index e3d3f2ef..98181fb3 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -336,7 +336,7 @@ es: static_file_migration: 'Migración de archivos' find_and_replace: 'Búsqueda y reemplazo' status: - building: "Tu sitio se está publicando, por favor espera ..." + building: "Tu sitio se está publicando, por favor espera para recargar esta página..." not_published_yet: "Tu sitio se está publicando por primera vez, por favor espera hasta un minuto..." available: "¡Tu sitio está disponible! Cliquea aquí para visitarlo." index: From ec47335f04ccc4b0a7424fcbe92ad65d7ce6c129 Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 12:44:09 -0300 Subject: [PATCH 092/106] fix: es necesario el arbol actual para ignorar cambios en paralelo cuando estamos guardando un post con archivos subidos y posts relacionados, al no usar el arbol actual se pisaban los archivos modificados y el repositorio quedaba en un estado inconsistente. --- app/models/site/repository.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/models/site/repository.rb b/app/models/site/repository.rb index f63288d4..62e4c45e 100644 --- a/app/models/site/repository.rb +++ b/app/models/site/repository.rb @@ -117,6 +117,9 @@ class Site def commit(file:, usuarie:, message:, remove: false) file = [file] unless file.respond_to? :each + # Cargar el árbol actual + rugged.index.read_tree rugged.head.target.tree + file.each do |f| remove ? rm(f) : add(f) end From ad76fed1b19dac253f67b333be25b7cdd7ee01fa Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 13:31:32 -0300 Subject: [PATCH 093/106] fix: alert en modo oscuro --- app/assets/stylesheets/application.scss | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 2f52829b..258698d3 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -52,6 +52,12 @@ $sizes: ( --background: #{$black}; --color: #{$cyan}; } + + .alert-primary { + @include alert-variant(theme-color-level($cyan, $alert-bg-level), + theme-color-level($cyan, $alert-border-level), + theme-color-level($cyan, $alert-color-level)); + } } // TODO: Encontrar la forma de generar esto desde los locales de Rails From bd21f3d9b4806b54b63b3ece2efa5a0d4acbbf5e Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 13:47:12 -0300 Subject: [PATCH 094/106] fixup! fix: alert en modo oscuro --- app/assets/stylesheets/application.scss | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 258698d3..99b5a296 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -54,9 +54,9 @@ $sizes: ( } .alert-primary { - @include alert-variant(theme-color-level($cyan, $alert-bg-level), - theme-color-level($cyan, $alert-border-level), - theme-color-level($cyan, $alert-color-level)); + @include alert-variant(theme-color-level("cyan", $alert-bg-level), + theme-color-level("cyan", $alert-border-level), + theme-color-level("cyan", $alert-color-level)); } } From 191dbbd82344a8e7545c4c65e9d84838c435e27e Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 13:47:59 -0300 Subject: [PATCH 095/106] fix: indicar que hay un link --- app/views/sites/_status.haml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/sites/_status.haml b/app/views/sites/_status.haml index 52afa3ca..a731aa7d 100644 --- a/app/views/sites/_status.haml +++ b/app/views/sites/_status.haml @@ -16,4 +16,4 @@ - link = true = render 'bootstrap/alert' do - = link_to_if link, message.html_safe, site.url + = link_to_if link, message.html_safe, site.url, class: 'alert-link' From 3dacef76f1cafb9ecb64cb527737ba34452e9536 Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 13:55:21 -0300 Subject: [PATCH 096/106] fix: esto no funciona --- app/assets/stylesheets/application.scss | 6 ------ 1 file changed, 6 deletions(-) diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 99b5a296..2f52829b 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -52,12 +52,6 @@ $sizes: ( --background: #{$black}; --color: #{$cyan}; } - - .alert-primary { - @include alert-variant(theme-color-level("cyan", $alert-bg-level), - theme-color-level("cyan", $alert-border-level), - theme-color-level("cyan", $alert-color-level)); - } } // TODO: Encontrar la forma de generar esto desde los locales de Rails From b7a27a87dd2879622f89d4102f4a4346aa7c17ac Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 16:58:22 -0300 Subject: [PATCH 097/106] feat: cuando se modifica la licencia, considerarla personalizada --- app/models/licencia.rb | 4 ++++ app/services/post_service.rb | 12 ++++++++++++ app/views/sites/_form.haml | 1 + db/seeds/licencias.yml | 6 ++++++ 4 files changed, 23 insertions(+) diff --git a/app/models/licencia.rb b/app/models/licencia.rb index f0a542ef..351a8ae5 100644 --- a/app/models/licencia.rb +++ b/app/models/licencia.rb @@ -17,4 +17,8 @@ class Licencia < ApplicationRecord validates :description, presence: true validates :short_description, presence: true validates :deed, presence: true + + def custom? + url == 'custom' + end end diff --git a/app/services/post_service.rb b/app/services/post_service.rb index 81ebe4a1..f1b9f7c3 100644 --- a/app/services/post_service.rb +++ b/app/services/post_service.rb @@ -18,6 +18,8 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do commit(action: :created, file: update_related_posts) if post.update(post_params) + update_site_license! + # Devolver el post aunque no se haya salvado para poder rescatar los # errores post @@ -44,6 +46,8 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do # relacionados. commit(action: :updated, file: update_related_posts) if post.update(post_params) + update_site_license! + # Devolver el post aunque no se haya salvado para poder rescatar los # errores post @@ -137,4 +141,12 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do p.path.absolute if p.save(validate: false) end.compact << post.path.absolute end + + # Si les usuaries modifican o crean una licencia, considerarla + # personalizada en el panel. + def update_site_license! + if site.usuarie?(usuarie) && post.layout.name == :license + site.update licencia: Licencia.find_by_url('custom') + end + end end diff --git a/app/views/sites/_form.haml b/app/views/sites/_form.haml index 9a044c7f..10f158c8 100644 --- a/app/views/sites/_form.haml +++ b/app/views/sites/_form.haml @@ -79,6 +79,7 @@ %h2= t('.licencia.title') %p.lead= t('.help.licencia') - Licencia.all.find_each do |licencia| + - next if licencia.custom? && site.licencia != licencia .row.license .col .media.mt-1 diff --git a/db/seeds/licencias.yml b/db/seeds/licencias.yml index c5e2886a..402e5d8b 100644 --- a/db/seeds/licencias.yml +++ b/db/seeds/licencias.yml @@ -1,4 +1,10 @@ --- +- name_en: "Custom license" + name_es: "Licencia personalizada" + url_en: "custom" + url_es: "custom" + description_en: "The license terms are provided by you." + description_es: "Los términos de la licencia fueron provistos por vos." - name_en: 'Peer Production License' name_es: 'Licencia de Producción de Pares' short_description_en: "This work is licensed under a Peer Production License" From 94d30ac12aebac141992747613f888b573f5f43f Mon Sep 17 00:00:00 2001 From: f Date: Mon, 3 Apr 2023 17:50:04 -0300 Subject: [PATCH 098/106] fixup! feat: cuando se modifica la licencia, considerarla personalizada --- app/models/licencia.rb | 2 +- app/services/post_service.rb | 4 ++-- app/services/site_service.rb | 2 ++ app/views/sites/_form.haml | 7 ++++--- db/seeds/licencias.yml | 9 +++++++-- 5 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/models/licencia.rb b/app/models/licencia.rb index 351a8ae5..65009f46 100644 --- a/app/models/licencia.rb +++ b/app/models/licencia.rb @@ -19,6 +19,6 @@ class Licencia < ApplicationRecord validates :deed, presence: true def custom? - url == 'custom' + icons == 'custom' end end diff --git a/app/services/post_service.rb b/app/services/post_service.rb index f1b9f7c3..7b31867d 100644 --- a/app/services/post_service.rb +++ b/app/services/post_service.rb @@ -145,8 +145,8 @@ PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do # Si les usuaries modifican o crean una licencia, considerarla # personalizada en el panel. def update_site_license! - if site.usuarie?(usuarie) && post.layout.name == :license - site.update licencia: Licencia.find_by_url('custom') + if site.usuarie?(usuarie) && post.layout.name == :license && !site.licencia.custom? + site.update licencia: Licencia.find_by_icons('custom') end end end diff --git a/app/services/site_service.rb b/app/services/site_service.rb index 70824422..5e1d5055 100644 --- a/app/services/site_service.rb +++ b/app/services/site_service.rb @@ -110,6 +110,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do # @return [Boolean] def add_licencias return true unless site.layout? :license + return true if site.licencia.custom? with_all_locales do |locale| add_licencia lang: locale @@ -140,6 +141,7 @@ SiteService = Struct.new(:site, :usuarie, :params, keyword_init: true) do # @return [Boolean] def change_licencias return true unless site.layout? :license + return true if site.licencia.custom? with_all_locales do |locale| post = site.posts(lang: locale).find_by(layout: 'license') diff --git a/app/views/sites/_form.haml b/app/views/sites/_form.haml index 10f158c8..137a40b0 100644 --- a/app/views/sites/_form.haml +++ b/app/views/sites/_form.haml @@ -83,7 +83,8 @@ .row.license .col .media.mt-1 - = image_tag licencia.icons, alt: licencia.name, class: 'mr-3 mt-4' + - unless licencia.custom? + = image_tag licencia.icons, alt: licencia.name, class: 'mr-3 mt-4' .media-body .custom-control.custom-radio = f.radio_button :licencia_id, licencia.id, @@ -94,8 +95,8 @@ = sanitize_markdown licencia.description, tags: %w[p a strong em ul ol li h1 h2 h3 h4 h5 h6] - = link_to t('.licencia.url'), licencia.url, - target: '_blank', class: 'btn' + - unless licencia.custom? + = link_to t('.licencia.url'), licencia.url, target: '_blank', class: 'btn', rel: 'noopener' %hr/ diff --git a/db/seeds/licencias.yml b/db/seeds/licencias.yml index 402e5d8b..f6b76296 100644 --- a/db/seeds/licencias.yml +++ b/db/seeds/licencias.yml @@ -1,10 +1,15 @@ --- - name_en: "Custom license" name_es: "Licencia personalizada" - url_en: "custom" - url_es: "custom" + url_en: "" + url_es: "" + icons: "custom" + short_description_en: "" + short_description_es: "" description_en: "The license terms are provided by you." description_es: "Los términos de la licencia fueron provistos por vos." + deed_en: "" + deed_es: "" - name_en: 'Peer Production License' name_es: 'Licencia de Producción de Pares' short_description_en: "This work is licensed under a Peer Production License" From ea71aafe58c233234bcdf1c00df7fac5df2b1cea Mon Sep 17 00:00:00 2001 From: f Date: Tue, 4 Apr 2023 11:33:51 -0300 Subject: [PATCH 099/106] fix: enviar los correos de devise en el idioma de le usuarie #12952 --- app/models/usuarie.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/models/usuarie.rb b/app/models/usuarie.rb index c87d82f9..7b83ee75 100644 --- a/app/models/usuarie.rb +++ b/app/models/usuarie.rb @@ -41,6 +41,12 @@ class Usuarie < ApplicationRecord lock_access! if attempts_exceeded? && !access_locked? end + def send_devise_notification(notification, *args) + I18n.with_locale(lang) do + devise_mailer.send(notification, self, *args).deliver_later + end + end + private def lang_from_locale! From 38d6f6d842ebcb6715aa02427a8875e9c9fd2b3b Mon Sep 17 00:00:00 2001 From: f Date: Tue, 4 Apr 2023 13:21:38 -0300 Subject: [PATCH 100/106] =?UTF-8?q?fix:=20mantener=20la=20notificaci=C3=B3?= =?UTF-8?q?n=20hasta=20que=20se=20confirme=20el=20correo=20#12950?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/application_controller.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index e80c279d..0628421f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -9,6 +9,7 @@ class ApplicationController < ActionController::Base before_action :prepare_exception_notifier before_action :configure_permitted_parameters, if: :devise_controller? + before_action :notify_unconfirmed_email, unless: :devise_controller? around_action :set_locale rescue_from Pundit::NilPolicyError, with: :page_not_found @@ -27,6 +28,13 @@ class ApplicationController < ActionController::Base private + def notify_unconfirmed_email + return unless current_usuarie + return if current_usuarie.confirmed? + + flash[:notice] ||= I18n.t('devise.registrations.signed_up') + end + def uuid?(string) /[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}/ =~ string end From 8d31170086d3fa51c946c244fff4814f72b9075f Mon Sep 17 00:00:00 2001 From: f Date: Tue, 4 Apr 2023 13:34:19 -0300 Subject: [PATCH 101/106] fix: usar el idioma de le usuarie --- app/controllers/application_controller.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 0628421f..b4be5a97 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -32,7 +32,9 @@ class ApplicationController < ActionController::Base return unless current_usuarie return if current_usuarie.confirmed? - flash[:notice] ||= I18n.t('devise.registrations.signed_up') + I18n.with_locale(current_usuarie.lang) do + flash[:notice] ||= I18n.t('devise.registrations.signed_up') + end end def uuid?(string) @@ -92,6 +94,7 @@ class ApplicationController < ActionController::Base protected def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: Usuarie::CONSENT_FIELDS) devise_parameter_sanitizer.permit(:account_update, keys: %i[lang]) end From 29be4b26b034ee7e2a78413e9c8dbd6278266fc8 Mon Sep 17 00:00:00 2001 From: f Date: Wed, 5 Apr 2023 19:30:44 -0300 Subject: [PATCH 102/106] fix: no producir un error al no haber locales --- app/models/metadata_locales.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/metadata_locales.rb b/app/models/metadata_locales.rb index 3790b944..37b50286 100644 --- a/app/models/metadata_locales.rb +++ b/app/models/metadata_locales.rb @@ -44,6 +44,6 @@ class MetadataLocales < MetadataHasAndBelongsToMany def posts other_locales.map do |locale| site.posts(lang: locale).where(layout: post.layout.value) - end.reduce(&:concat) || PostRelation.new + end.reduce(&:concat) || PostRelation.new(site: site, lang: 'any') end end From 6bc013c8593bdb9d184fadcd6f091ab1e2d4d8eb Mon Sep 17 00:00:00 2001 From: f Date: Wed, 5 Apr 2023 19:30:59 -0300 Subject: [PATCH 103/106] fix: no mostrar el campo si no hay locales --- app/views/posts/attribute_ro/_locales.haml | 19 +++++++------- app/views/posts/attributes/_locales.haml | 29 +++++++++++----------- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/app/views/posts/attribute_ro/_locales.haml b/app/views/posts/attribute_ro/_locales.haml index 3ac22933..16ecb532 100644 --- a/app/views/posts/attribute_ro/_locales.haml +++ b/app/views/posts/attribute_ro/_locales.haml @@ -1,9 +1,10 @@ -%tr{ id: attribute } - %th= post_label_t(attribute, post: post) - %td - %ul - - metadata.value.each do |uuid| - - p = site.docs.find(uuid, uuid: true) - %li{ dir: t("locales.#{p.lang.value}.dir"), lang: p.lang.value } - = link_to p.title.value, - site_post_path(site, p.id, locale: p.lang.value) +- if site.locales.count > 1 + %tr{ id: attribute } + %th= post_label_t(attribute, post: post) + %td + %ul + - metadata.value.each do |uuid| + - p = site.docs.find(uuid, uuid: true) + %li{ dir: t("locales.#{p.lang.value}.dir"), lang: p.lang.value } + = link_to p.title.value, + site_post_path(site, p.id, locale: p.lang.value) diff --git a/app/views/posts/attributes/_locales.haml b/app/views/posts/attributes/_locales.haml index 23f66700..4978f6b4 100644 --- a/app/views/posts/attributes/_locales.haml +++ b/app/views/posts/attributes/_locales.haml @@ -1,18 +1,19 @@ -%fieldset - %legend= post_label_t(attribute, post: post) +- if site.locales.count > 1 + %fieldset + %legend= post_label_t(attribute, post: post) - = render 'posts/attribute_feedback', - post: post, attribute: attribute, metadata: metadata + = render 'posts/attribute_feedback', + post: post, attribute: attribute, metadata: metadata - - site.locales.each do |locale| - - next if post.lang.value == locale - - locale_t = t("locales.#{locale}.name", default: locale.to_s.humanize) - - value = metadata.value.find do |v| - - metadata.values[locale].values.include? v + - site.locales.each do |locale| + - next if post.lang.value == locale + - locale_t = t("locales.#{locale}.name", default: locale.to_s.humanize) + - value = metadata.value.find do |v| + - metadata.values[locale].values.include? v - .form-group - = label_tag "#{base}_#{attribute}_#{locale}", locale_t + .form-group + = label_tag "#{base}_#{attribute}_#{locale}", locale_t - = select_tag("#{plain_field_name_for(base, attribute)}[]", - options_for_select(metadata.values[locale], value), - **field_options(attribute, metadata), include_blank: t('.empty')) + = select_tag("#{plain_field_name_for(base, attribute)}[]", + options_for_select(metadata.values[locale], value), + **field_options(attribute, metadata), include_blank: t('.empty')) From dd3ef04fc4b759d818ac9ef16db88e59761889ab Mon Sep 17 00:00:00 2001 From: f Date: Thu, 6 Apr 2023 11:19:33 -0300 Subject: [PATCH 104/106] =?UTF-8?q?feat:=20generar=20im=C3=A1genes=20p?= =?UTF-8?q?=C3=BAblicas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .woodpecker.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.woodpecker.yml b/.woodpecker.yml index 1d760b52..2e775624 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -1,10 +1,10 @@ pipeline: publish: - image: "plugins/docker" + image: "docker.io/woodpeckerci/plugin-docker-buildx" settings: - registry: "registry.nulo.in" + registry: "gitea.nulo.in" username: "sutty" - repo: "registry.nulo.in/sutty/panel" + repo: "gitea.nulo.in/sutty/panel" tags: - "${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" - "latest" @@ -12,10 +12,10 @@ pipeline: - "RUBY_VERSION=${RUBY_VERSION}" - "RUBY_PATCH=${RUBY_PATCH}" - "ALPINE_VERSION=${ALPINE_VERSION}" - - "BASE_IMAGE=registry.nulo.in/sutty/rails" + - "BASE_IMAGE=gitea.nulo.in/sutty/rails" purge: false secrets: - - "docker_password" + - "DOCKER_PASSWORD" when: branch: - "rails" @@ -26,7 +26,7 @@ pipeline: - "Dockerfile" - ".dockerignore" assets: - image: "registry.nulo.in/sutty/panel:${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" + image: "gitea.nulo.in/sutty/panel:${ALPINE_VERSION}-${RUBY_VERSION}.${RUBY_PATCH}" commands: - "apk add python2 dotenv openssh-client brotli" - "install -d -m 700 ~/.ssh/" @@ -66,6 +66,6 @@ pipeline: - "yarn.lock" matrix: include: - - ALPINE_VERSION: "3.14.8" + - ALPINE_VERSION: "3.14.10" RUBY_VERSION: "2.7" - RUBY_PATCH: "6" + RUBY_PATCH: "8" From 34d26a0174b0644d96e430b3bf894c734d366dce Mon Sep 17 00:00:00 2001 From: f Date: Thu, 6 Apr 2023 11:27:28 -0300 Subject: [PATCH 105/106] fix: instalar pnpm 7 porque 8 es incompatible con node 14 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index a6420a35..3da9ffab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,7 @@ RUN apk add --no-cache libxslt libxml2 postgresql-libs libssh2 \ RUN gem install --no-document --no-user-install foreman RUN wget https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz -O - | tar --strip-components 1 -xvzf - pandoc-${PANDOC_VERSION}/bin/pandoc && mv /bin/pandoc /usr/bin/pandoc -RUN apk add npm && npm install -g pnpm && apk del npm +RUN apk add npm && npm install -g pnpm@~7 && apk del npm COPY ./monit.conf /etc/monit.d/sutty.conf From 6cab61891c9c1fd0fb7c3a260febc816d40178ea Mon Sep 17 00:00:00 2001 From: f Date: Thu, 6 Apr 2023 20:30:47 -0300 Subject: [PATCH 106/106] fix: la tarea estaba mal nombrada --- Procfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Procfile b/Procfile index 950168dd..25a1639d 100644 --- a/Procfile +++ b/Procfile @@ -5,6 +5,6 @@ blazer_1h: bundle exec rake blazer:run_checks SCHEDULE="1 hour" blazer_1d: bundle exec rake blazer:run_checks SCHEDULE="1 day" blazer: bundle exec rake blazer:send_failing_checks prometheus: bundle exec prometheus_exporter -b 0.0.0.0 --prefix "sutty_" -distributed_press_renew_tokens: bundle exec rake distributed_press:tokens:renew +distributed_press_tokens_renew: bundle exec rake distributed_press:tokens:renew cleanup: bundle exec rake cleanup:everything stats: bundle exec rake stats:process_all