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.
 
 
 
 

384 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.time.Month;
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 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,"E-Mail-Adresse des Listenmitglieds nicht angegeben!");
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("Laden des Nutzers für die Adresse {} fehlgeschlagen",userEmail));
user.addPermission(perm);
} catch (NumberFormatException nfe){
return Map.of(ERROR,"Keine gültigen Berechtigungen übergeben!");
} catch (SQLException e) {
LOG.debug("Laden des Nutzers für die Adresse {} fehlgeschlagen",userEmail,e);
return Map.of(ERROR,t("Laden des Nutzers für die Adresse {} fehlgeschlagen",userEmail));
}
return Map.of(SUCCESS,"Nutzer-Berechtigungen aktualisiert");
}
private Map<String,Object> archive(MailingList list, String month, User requestingUser){
if (list != null){
try {
var allEmails = requestingUser != 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();
if (month == null || month.isBlank()) {
return Map.of(LIST,list.email(),"summary",Post.summarize(list,limitedSenders));
} else {
return Map.of(LIST,list.email(),"posts",Post.find(list,month,limitedSenders).stream().map(Post::safeMap).toList());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
LOG.debug("list: {}",list.email());
return Map.of();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String error = handleGet(req, resp);
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,"Es ist dir nicht gestattet, diese Liste zu löschen!");
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("Liste {} deaktiviert, Abonnement gesperrt, Liste de-publiziert. Mitglieder wurden entfernt.",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 dropPermission(String userEmail, String permissions) {
if (userEmail == null || userEmail.isBlank()) return Map.of(ERROR,"Nutzer-Emailadresse fehlt!");
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("Laden des Nutzers für die Adresse {} fehlgeschlagen",userEmail));
user.dropPermission(perm);
} catch (NumberFormatException nfe){
return Map.of(ERROR,"Keine gültigen Berechtigungen übergeben!");
} catch (SQLException e) {
LOG.debug("Laden des Nutzers für die Adresse {} fehlgeschlagen",userEmail,e);
return Map.of(ERROR,t("Laden des Nutzers für die Adresse {} fehlgeschlagen",userEmail));
}
return Map.of(SUCCESS,"Nutzer-Berechtigungen aktualisiert");
}
private Map enableList(MailingList list, User user, boolean enable) {
if (list == null) return Map.of(ERROR,"Keine Listen-Email übertragen!");
if (!list.mayBeAlteredBy(user)) Map.of(ERROR,t("Du bist nicht berechtigt, '{}' zu bearbeiten!",list.email()));
try {
list.enable(enable);
return Map.of(SUCCESS,t("Mailing-Liste '{}' wurde {}!",list.email(),enable ? "aktiviert" : "inaktiviert"));
} catch (SQLException e) {
LOG.error("Aktivieren/Inaktivieren der Mailing-Liste fehlgeschlagen: ",e);
return Map.of(ERROR,t("Aktualisieren der Liste '{}' fehlgeschlagen",list.email()));
}
}
public String handleGet(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());
switch (path) {
case LIST_ARCHIVE:
var list = Util.getMailingList(req);
try {
var allowed = list.hasState(STATE_PUBLIC_ARCHIVE) || list.moderators().map(ListMember::user).anyMatch(mod -> user.equals(mod));
if (!allowed) return t("Sie sind nicht berechtigt, das Archiv dieser Liste einzusehen!");
json.put("archive",archive(list,req.getParameter(MONTH),user));
} catch (SQLException sqle){
return sqle.getMessage();
}
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("Laden der Nutzerliste fehlgeschlagen:",e);
json.put(ERROR,"Laden der Nutzerliste fehlgeschlagen");
}
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("Kein Handler für den Pfad '{}'!",path));
break;
}
} else {
switch (path) {
case LIST_ARCHIVE:
var list = Util.getMailingList(req);
var allowed = list.hasState(STATE_PUBLIC_ARCHIVE);
if (!allowed) return t("Diese Liste hat kein öffentliches Archiv!");
json.put("archive",archive(list,req.getParameter(MONTH),null));
break;
case LIST_SUBSCRIBABLE:
json.put("lists", MailingList.subscribable().stream().map(MailingList::minimalMap).toList());
break;
default:
json.put(ERROR,"Nicht eingeloggt!");
}
}
try {
resp.setContentType("application/json");
resp.getWriter().println(json.toJSONString());
return null;
} catch (IOException e) {
return t("Konnte Anfrage nicht verarbeiten: {}",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 USER_ADD_PERMISSION:
if (user.hashPermission(User.PERMISSION_ADMIN)){
json.putAll(addPermission(userEmail,permissions));
} else json.put(ERROR,"Sie haben nicht die Berechtigung, um Berechtigungen zu ändern!");
break;
case USER_DROP_PERMISSION:
if (user.hashPermission(User.PERMISSION_ADMIN)){
json.putAll(dropPermission(userEmail,permissions));
} else json.put(ERROR,"Sie haben nicht die Berechtigung, um Berechtigungen zu ändern!");
break;
default:
json.put(ERROR,t("Kein Handler für den Pfad '{}'!",path));
break;
}
} else {
json.put(ERROR,"Nicht eingeloggt!");
}
try {
resp.setContentType("application/json");
resp.getWriter().println(json.toJSONString());
return null;
} catch (IOException e) {
return t("Konnte Anfrage nicht verarbeiten: {}",e.getMessage());
}
}
private Map<String, String> hideList(MailingList list, User user, boolean hide) {
if (list == null) return Map.of(ERROR,"Keine Listen-Email übertragen!");
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-Liste '{}' wurde {}!",list.email(),hide ? "versteckt" : "veröffentlicht"));
} catch (SQLException e) {
LOG.error("Veröffentlichen/Verstekcen der Mailing-Liste fehlgeschlagen: ",e);
return Map.of(ERROR,t("Aktualisieren der Liste '{}' fehlgeschlagen",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,"Keine Listen-Email übertragen!");
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.hasState(MailingList.STATE_PUBLIC_ARCHIVE)) 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,"Keine Listen-Email übertragen!");
if (!list.membersMayBeListedBy(user)) Map.of(ERROR,t("Es ist dir nicht gestattet, die Mitglieder von '{}' aufzulisten",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("Laden der Mitglieder-Liste fehlgeschlagen: ",e);
return Map.of(ERROR,t("Laden der Mitglieder-Liste von '{}' fehlgeschlagen!",list.email()));
}
}
private Map testList(MailingList list, User user) {
if (list == null) return Map.of(ERROR,"Keine Listen-Email übertragen!");
if (!list.mayBeTestedBy(user)) Map.of(ERROR,t("Es ist dir nicht gestattet, '{}' zu testen",list.email()));
try {
list.test(user);
return Map.of(SUCCESS,t("Test-Email an {} versendet",user.email()));
} catch (Exception e) {
LOG.warn("Senden der Test-Email fehlgeschlagen",e);
return Map.of(ERROR,t("Senden der Test-Email an {} fehlgeschlagen",user.email()));
}
}
}