]> nos-oignons.net Git - gestion-adh.git/blobdiff - lib/nos_oignons/mailman.rb
Ajout d'un peu de logs
[gestion-adh.git] / lib / nos_oignons / mailman.rb
index 352b9689bbf258071b386866280d3afb945d05e9..007fd337183bb581c6508b467b4629d03581df39 100644 (file)
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-require 'shellwords'
+require 'json'
+require 'rest-client'
 
 module NosOignons
   module Mailman
+    class MailmanMember < Struct.new(:member_id, :email, keyword_init: true)
+      def unsubscribe!
+        Mailman::request(:delete, "/3.0/members/#{URI::encode_www_form_component(member_id)}")
+      end
+    end
+
     class << self
       def list_members(list)
-        `sudo -u list list_members #{Shellwords.escape(list)}`.strip.split
+        s = request(:get, "/3.0/lists/#{URI::encode_www_form_component(list)}/roster/member")
+        r = JSON.parse(s)
+        r["entries"].collect { |entry|
+            MailmanMember.new(member_id: entry["member_id"], email: entry["email"])
+          }
       end
 
-      def add_member(list, email)
-        add_members(list, [email])
+      def susbcribe_email(list, email)
+        list_id = list.gsub(/@/, '.')
+        request(:post, "/3.0/members", payload: {
+              list_id: list_id,
+              subscriber: email,
+              pre_verified: true,
+              pre_confirmed: true,
+              pre_approved: true,
+            }.to_json,
+            headers: { content_type: :json },
+          )
       end
 
-      def add_members(list, emails)
-        IO.popen(['sudo', '-u', 'list', 'add_members', '-r', '-', list], 'w') do |io|
-          emails.each do |email|
-            io.puts email
-          end
-        end
+      def request(method, path, **args)
+        RestClient::Request.execute(
+          **args,
+          method: method,
+          url: "#{rest_url}#{path}"
+        )
       end
 
-      def remove_member(list, email)
-        remove_members(list, [email])
-      end
+      private
+
+      def rest_url
+        @rest_url if defined?(@rest_url)
 
-      def remove_members(list, emails)
-        IO.popen(['sudo', '-u', 'list', 'remove_members', '-f', '-', list], 'w') do |io|
-          emails.each do |email|
-            io.puts email
+        @rest_url = ENV["NOS_OIGNONS_MAILMAN_REST_API_URL"]
+        if @rest_url.nil?
+          cred_path = File.join("#{ENV["CREDENTIALS_DIRECTORY"]}", "mailman-rest-url")
+          begin
+            @rest_url = File.open(cred_path).read
+          rescue Errno::ENOENT
+            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")
           end
         end
+        @rest_url
       end
     end
   end