Java-basierte Mailinglisten-Anwendung, die auf IMAP+SMTP aufsetzt, und damit (fast) jede Mailbox in eine Mailingliste verwandeln kann.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

394 lines
18 KiB

package de.srsoftware.widerhall.web;
import de.srsoftware.widerhall.Util;
import de.srsoftware.widerhall.data.ListMember;
import de.srsoftware.widerhall.data.MailingList;
import de.srsoftware.widerhall.data.Post;
import de.srsoftware.widerhall.data.User;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static de.srsoftware.widerhall.Constants.*;
import static de.srsoftware.widerhall.Util.t;
import static de.srsoftware.widerhall.data.MailingList.*;
public class Rest extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(Rest.class);
private static final String LIST_ADD_MOD = "list/add_mod";
private static final String LIST_ARCHIVE = "list/archive";
private static final String LIST_DISABLE = "list/disable";
private static final String LIST_DROP = "list/drop";
private static final String LIST_DROP_MEMBER = "list/drop_member";
private static final String LIST_DROP_MOD = "list/drop_mod";
private static final String LIST_DETAIL = "list/detail";
private static final String LIST_ENABLE = "list/enable";
private static final String LIST_HIDE = "list/hide";
private static final String LIST_MEMBERS = "list/members";
private static final String LIST_MODERATED = "list/moderated";
private static final String LIST_SHOW = "list/show";
private static final String LIST_TEST = "list/test";
private static final String LIST_SUBSCRIBABLE = "list/subscribable";
private static final String MAIL_DROP = "mail/drop";
private static final String USER_ADD_PERMISSION = "user/addpermission";
private static final String USER_DROP_PERMISSION = "user/droppermission";
private static final String USER_LIST = "user/list";
private static final String MEMBERS = "members";
private static final String SUCCESS = "success";
private Map addPermission(String userEmail, String permissions) {
if (userEmail == null || userEmail.isBlank()) return Map.of(ERROR,"missing user email address!");
try {
int perm = Integer.parseInt(permissions);
var user = User.loadAll(List.of(userEmail)).stream().findAny().orElse(null);
if (user == null) return Map.of(ERROR,t("Failed to load user for address {}",userEmail));
user.addPermission(perm);
} catch (NumberFormatException nfe){
return Map.of(ERROR,"no valid permissions provided!");
} catch (SQLException e) {
LOG.debug("Failed to load user for address {}",userEmail,e);
return Map.of(ERROR,t("Failed to load user for address {}",userEmail));
}
return Map.of(SUCCESS,"Updated user permissions");
}
private Map<String,Object> archive(HttpServletRequest req, User user) throws SQLException {
var list = Util.getMailingList(req);
if (list == null) throw new IllegalArgumentException(t("You are trying to access a non-existing list!"));
var allowed = list.hasPublicArchive() || list.mayBeAlteredBy(user);
if (!allowed) throw new IllegalAccessError(t("You are not allowed to access the archive of this list!"));
var allEmails = user != null || list.hasState(STATE_OPEN_FOR_SUBSCRIBERS) || list.hasState(STATE_OPEN_FOR_GUESTS);
var limitedSenders = allEmails ? null : list.moderators().map(ListMember::user).map(User::email).toList();
boolean userIsMod = list.mayBeAlteredBy(user);
String month = req.getParameter(MONTH);
if (month == null || month.isBlank()) return Map.of(LIST,list.email(),MODERATOR,userIsMod,"summary",Post.summarize(list,limitedSenders));
return Map.of(LIST,list.email(),MODERATOR,userIsMod,"posts",Post.find(list,month,limitedSenders).stream().map(Post::safeMap).toList());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String error;
try {
error = handleGet(req, resp);
} catch (SQLException e) {
error = e.getMessage();
}
if (error != null) resp.sendError(400,error);
}
public Map dropList(MailingList list, User user){
boolean allowed = user.hashPermission(User.PERMISSION_ADMIN);
try {
if (!allowed) {
var member = ListMember.load(list, user);
if (member != null) allowed = member.isOwner();
}
} catch (SQLException e) {
LOG.warn("Was not able to load listmember for {}/{}",list.email(),user.email(),e);
}
if (!allowed) return Map.of(ERROR,"You are not allowed to remove this list!");
try {
list.hide(true).enable(false).openForGuests(false).openForSubscribers(false);
list.members().forEach(listMember -> {
try {
listMember.unsubscribe();
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
} catch (Exception e) {
LOG.debug("Disabling and hiding of {} failed",list.email(),e);
}
return Map.of(SUCCESS,t("List {} disabled, closed for subscribers and hidden. Members have been removed.",list.email()));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String error = handlePost(req, resp);
if (error != null) resp.sendError(400,error);
}
private Map dropMail(String messageId,User user){
try {
var message = Post.load(messageId);
if (message == null) return Map.of(ERROR,t("Cannot remove: unknown message id"));
var allowed = message.list().mayBeAlteredBy(user);
if (allowed){
message.remove();
return Map.of(SUCCESS,t("Message deleted"));
}
return Map.of(ERROR,t("You are not allowed to remove messages from this list!"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private Map dropPermission(String userEmail, String permissions) {
if (userEmail == null || userEmail.isBlank()) return Map.of(ERROR,"missing user email address!");
try {
int perm = Integer.parseInt(permissions);
var user = User.loadAll(List.of(userEmail)).stream().findAny().orElse(null);
if (user == null) return Map.of(ERROR,t("Failed to load user for address {}",userEmail));
user.dropPermission(perm);
} catch (NumberFormatException nfe){
return Map.of(ERROR,"no valid permissions provided!");
} catch (SQLException e) {
LOG.debug("Failed to load user for address {}",userEmail,e);
return Map.of(ERROR,t("Failed to load user for address {}",userEmail));
}
return Map.of(SUCCESS,t("Updated user permissions"));
}
private Map enableList(MailingList list, User user, boolean enable) {
if (list == null) return Map.of(ERROR,"no list email provided!");
if (!list.mayBeAlteredBy(user)) Map.of(ERROR,t("You are not allowed to edit '{}'",list.email()));
try {
list.enable(enable);
return Map.of(SUCCESS,t("Mailing list '{}' was {}!",list.email(),enable ? "enabled" : "disabled"));
} catch (SQLException e) {
LOG.error("Failed to enable/disable mailing list: ",e);
return Map.of(ERROR,t("Failed to update list '{}'",list.email()));
}
}
public String handleGet(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
var user = Util.getUser(req);
var path = Util.getPath(req);
JSONObject json = new JSONObject();
if (user != null){
json.put(USER,user.safeMap());
switch (path) {
case LIST_ARCHIVE:
json.put("archive",archive(req,user));
break;
case USER_LIST:
try {
json.put("users", (user.hashPermission(User.PERMISSION_ADMIN) ? User.loadAll() : List.of(user)).stream().map(User::safeMap).toList());
} catch (SQLException e) {
LOG.debug("Failed to load user list:",e);
json.put(ERROR,"failed to load user list");
}
break;
case LIST_MODERATED:
json.put("lists", MailingList.moderatedBy(user).stream().sorted((l1,l2)->l1.name().compareTo(l2.name())).map(MailingList::safeMap).toList());
break;
case LIST_SUBSCRIBABLE:
json.put("lists", MailingList.subscribable(user).stream().map(MailingList::minimalMap).toList());
break;
default:
json.put(ERROR,t("No handler for path '{}'!",path));
break;
}
} else {
switch (path) {
case LIST_ARCHIVE:
json.put("archive",archive(req,null));
break;
case LIST_SUBSCRIBABLE:
json.put("lists", MailingList.subscribable().stream().map(MailingList::minimalMap).toList());
break;
default:
json.put(ERROR,"Not logged in!");
}
}
try {
resp.setContentType("application/json");
resp.getWriter().println(json.toJSONString());
return null;
} catch (IOException e) {
return t("Failed to handle request: {}",e.getMessage());
}
}
public String handlePost(HttpServletRequest req, HttpServletResponse resp){
var user = Util.getUser(req);
var path = Util.getPath(req);
JSONObject json = new JSONObject();
if (user != null){
json.put(USER,user.safeMap());
var list = Util.getMailingList(req);
var userEmail = req.getParameter(EMAIL);
var permissions = req.getParameter(PERMISSIONS);
switch (path) {
case LIST_ADD_MOD:
json.putAll(listAddMod(list,userEmail,user));
break;
case LIST_DETAIL:
json.putAll(listDetail(list,user));
break;
case LIST_DISABLE:
json.putAll(enableList(list,user,false));
break;
case LIST_DROP:
json.putAll(dropList(list,user));
break;
case LIST_DROP_MEMBER:
json.putAll(listDropMember(list,userEmail,user));
break;
case LIST_DROP_MOD:
json.putAll(listDropMod(list,userEmail,user));
break;
case LIST_ENABLE:
json.putAll(enableList(list,user,true));
break;
case LIST_HIDE:
json.putAll(hideList(list,user,true));
break;
case LIST_MEMBERS:
json.putAll(listMembers(list,user));
break;
case LIST_SHOW:
json.putAll(hideList(list,user,false));
break;
case LIST_TEST:
json.putAll(testList(list,user));
break;
case MAIL_DROP:
var messageId = req.getParameter(MESSAGE_ID);
json.putAll(dropMail(messageId,user));
break;
case USER_ADD_PERMISSION:
if (user.hashPermission(User.PERMISSION_ADMIN)){
json.putAll(addPermission(userEmail,permissions));
} else json.put(ERROR,"You are not allowed to alter user permissions!");
break;
case USER_DROP_PERMISSION:
if (user.hashPermission(User.PERMISSION_ADMIN)){
json.putAll(dropPermission(userEmail,permissions));
} else json.put(ERROR,"You are not allowed to alter user permissions!");
break;
default:
json.put(ERROR,t("No handler for path '{}'!",path));
break;
}
} else {
json.put(ERROR,"Not logged in!");
}
try {
resp.setContentType("application/json");
resp.getWriter().println(json.toJSONString());
return null;
} catch (IOException e) {
return t("Failed to handle request: {}",e.getMessage());
}
}
private Map<String, String> hideList(MailingList list, User user, boolean hide) {
if (list == null) return Map.of(ERROR,"no list email provided!");
if (!list.mayBeAlteredBy(user)) Map.of(ERROR,t("You are not allowed to edit '{}'",list.email()));
try {
list.hide(hide);
return Map.of(SUCCESS,t("Mailing list '{}' was {}!",list.email(),hide ? "hidden" : "made public"));
} catch (SQLException e) {
LOG.error("Failed to (un)hide mailing list: ",e);
return Map.of(ERROR,t("Failed to update list '{}'",list.email()));
}
}
private Map listAddMod(MailingList list, String userEmail, User user) {
ListMember moderator = null;
try {
moderator = ListMember.load(list,user);
} catch (SQLException e) {
LOG.warn("Failed to load list member for {}/{}",user.email(),list.email(),e);
return Map.of(ERROR,t("Failed to load list member for {}/{}",user.email(),list.email()));
}
if (moderator == null) return Map.of(ERROR,t("{} is not a member of {}",user.email(),list.email()));
var error = moderator.addNewModerator(userEmail);
return error == null ? Map.of(SUCCESS,t("{} is now a moderator of {}",userEmail,list.email())) : Map.of(ERROR,error);
}
private Map listDetail(MailingList list, User user) {
if (list == null) return Map.of(ERROR,"no list email provided!");
var map = new HashMap<>();
if (list.hasState(MailingList.STATE_FORWARD_FROM)) map.put(KEY_FORWARD_FROM,true);
if (list.hasState(MailingList.STATE_FORWARD_ATTACHED)) map.put(KEY_FORWARD_ATTACHED,true);
if (list.hasState(MailingList.STATE_HIDE_RECEIVERS)) map.put(KEY_HIDE_RECEIVERS,true);
if (list.hasState(MailingList.STATE_REPLY_TO_LIST)) map.put(KEY_REPLY_TO_LIST,true);
if (list.isOpenForGuests()) map.put(KEY_OPEN_FOR_GUESTS,true);
if (list.isOpenForSubscribers()) map.put(KEY_OPEN_FOR_SUBSCRIBERS,true);
if (list.hasPublicArchive()) map.put(KEY_ARCHIVE,true);
if (list.hasState(STATE_MODS_CAN_EDIT_MODS)) map.put(KEY_MODS_CAN_EDIT_MODS,true);
if (list.holdTime() != null) map.put(KEY_DELETE_MESSAGES,list.holdTime());
return map;
}
private Map listDropMember(MailingList list, String userEmail, User user) {
ListMember moderator = null;
try {
moderator = ListMember.load(list,user);
} catch (SQLException e) {
LOG.warn("Failed to load list member for {}/{}",user.email(),list.email(),e);
return Map.of(ERROR,t("Failed to load list member for {}/{}",user.email(),list.email()));
}
if (moderator == null) return Map.of(ERROR,t("{} is not a member of {}",user.email(),list.email()));
var error = moderator.dropMember(userEmail);
return error == null ? Map.of(SUCCESS,t("{} is now a moderator of {}",userEmail,list.email())) : Map.of(ERROR,error);
}
private Map listDropMod(MailingList list, String userEmail, User user) {
ListMember moderator = null;
try {
moderator = ListMember.load(list,user);
} catch (SQLException e) {
LOG.warn("Failed to load list member for {}/{}",user.email(),list.email(),e);
return Map.of(ERROR,t("Failed to load list member for {}/{}",user.email(),list.email()));
}
if (moderator == null) return Map.of(ERROR,t("{} is not a member of {}",user.email(),list.email()));
var error = moderator.dropModerator(userEmail);
return error == null ? Map.of(SUCCESS,t("{} is now a moderator of {}",userEmail,list.email())) : Map.of(ERROR,error);
}
private Map<String, Object> listMembers(MailingList list, User user) {
if (list == null) return Map.of(ERROR,"no list email provided!");
if (!list.membersMayBeListedBy(user)) Map.of(ERROR,t("You are not allowed to list members of '{}'",list.email()));
try {
var members = list.members()
.sorted((m1,m2)->m1.user().name().compareTo(m2.user().name()))
.map(ListMember::safeMap)
.toList();
return Map.of(MEMBERS,members,LIST,list.minimalMap());
} catch (SQLException e) {
LOG.error("Failed to load member list: ",e);
return Map.of(ERROR,t("Failed to load member list '{}'",list.email()));
}
}
private Map testList(MailingList list, User user) {
if (list == null) return Map.of(ERROR,"no list email provided!");
if (!list.mayBeTestedBy(user)) Map.of(ERROR,t("You are not allowed to test '{}'",list.email()));
try {
list.test(user);
return Map.of(SUCCESS,t("Sent test email to {}",user.email()));
} catch (Exception e) {
LOG.warn("Failed to send test email",e);
return Map.of(ERROR,t("Failed to send test email to {}",user.email()));
}
}
}