1
0

sync_room_to_group.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env perl
  2. use strict;
  3. use warnings;
  4. use JSON::XS;
  5. use LWP::UserAgent;
  6. use URI::Escape;
  7. if (@ARGV < 4) {
  8. die "usage: $0 <homeserver url> <access_token> <room_id|room_alias> <group_id>\n";
  9. }
  10. my ($hs, $access_token, $room_id, $group_id) = @ARGV;
  11. my $ua = LWP::UserAgent->new();
  12. $ua->timeout(10);
  13. if ($room_id =~ /^#/) {
  14. $room_id = uri_escape($room_id);
  15. $room_id = decode_json($ua->get("${hs}/_matrix/client/r0/directory/room/${room_id}?access_token=${access_token}")->decoded_content)->{room_id};
  16. }
  17. my $room_users = [ keys %{decode_json($ua->get("${hs}/_matrix/client/r0/rooms/${room_id}/joined_members?access_token=${access_token}")->decoded_content)->{joined}} ];
  18. my $group_users = [
  19. (map { $_->{user_id} } @{decode_json($ua->get("${hs}/_matrix/client/unstable/groups/${group_id}/users?access_token=${access_token}" )->decoded_content)->{chunk}}),
  20. (map { $_->{user_id} } @{decode_json($ua->get("${hs}/_matrix/client/unstable/groups/${group_id}/invited_users?access_token=${access_token}" )->decoded_content)->{chunk}}),
  21. ];
  22. die "refusing to sync from empty room" unless (@$room_users);
  23. die "refusing to sync to empty group" unless (@$group_users);
  24. my $diff = {};
  25. foreach my $user (@$room_users) { $diff->{$user}++ }
  26. foreach my $user (@$group_users) { $diff->{$user}-- }
  27. foreach my $user (keys %$diff) {
  28. if ($diff->{$user} == 1) {
  29. warn "inviting $user";
  30. print STDERR $ua->put("${hs}/_matrix/client/unstable/groups/${group_id}/admin/users/invite/${user}?access_token=${access_token}", Content=>'{}')->status_line."\n";
  31. }
  32. elsif ($diff->{$user} == -1) {
  33. warn "removing $user";
  34. print STDERR $ua->put("${hs}/_matrix/client/unstable/groups/${group_id}/admin/users/remove/${user}?access_token=${access_token}", Content=>'{}')->status_line."\n";
  35. }
  36. }