]> nos-oignons.net Git - gestion-adh.git/blob - lib/nos_oignons/mailman.rb
Switch to Mailman 3 REST API for “ag” subscriptions
[gestion-adh.git] / lib / nos_oignons / mailman.rb
1 #-*- coding: utf-8 -*-
2 #
3 # Système de gestion des adhésions de Nos oignons
4 # Copyright © 2013-2014 Nos oignons <contact@nos-oignons.net>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as
8 # published by the Free Software Foundation, either version 3 of the
9 # License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU Affero General Public License for more details.
15 #
16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 require 'json'
20 require 'rest-client'
21
22 module NosOignons
23   module Mailman
24     class MailmanMember < Struct.new(:member_id, :email, keyword_init: true)
25       def unsubscribe!
26         Mailman::request(:delete, "/3.0/members/#{URI::encode_www_form_component(member_id)}")
27       end
28     end
29
30     class << self
31       def list_members(list)
32         s = request(:get, "/3.0/lists/#{URI::encode_www_form_component(list)}/roster/member")
33         r = JSON.parse(s)
34         r["entries"].collect { |entry|
35             MailmanMember.new(member_id: entry["member_id"], email: entry["email"])
36           }
37       end
38
39       def susbcribe_email(list, email)
40         list_id = list.gsub(/@/, '.')
41         request(:post, "/3.0/members", payload: {
42               list_id: list_id,
43               subscriber: email,
44               pre_verified: true,
45               pre_confirmed: true,
46               pre_approved: true,
47             }.to_json,
48             headers: { content_type: :json },
49           )
50       end
51
52       def request(method, path, **args)
53         RestClient::Request.execute(
54           **args,
55           method: method,
56           url: "#{rest_url}#{path}"
57         )
58       end
59
60       private
61
62       def rest_url
63         @rest_url if defined?(@rest_url)
64
65         @rest_url = ENV["NOS_OIGNONS_MAILMAN_REST_API_URL"]
66         if @rest_url.nil?
67           cred_path = File.join("#{ENV["CREDENTIALS_DIRECTORY"]}", "mailman-rest-url")
68           begin
69             @rest_url = File.open(cred_path).read
70           rescue Errno::ENOENT
71             raise ArgumentError.new("Environment variable `NOS_OIGNONS_MAILMAN_REST_API_URL` not defined, and unable to read the file `$CREDENTIALS_DIRECTORY/mailman-rest-url` either")
72           end
73         end
74         @rest_url
75       end
76     end
77   end
78 end