Browse Source

Merge branch 'main' into lang_de

lang_de
Stephan Richter 2 years ago
parent
commit
d706eac6a7
  1. 85
      doc/data structure.dia
  2. 2
      pom.xml
  3. 2
      src/main/java/de/srsoftware/widerhall/Constants.java
  4. 28
      src/main/java/de/srsoftware/widerhall/Util.java
  5. 78
      src/main/java/de/srsoftware/widerhall/data/ListMember.java
  6. 216
      src/main/java/de/srsoftware/widerhall/data/MailingList.java
  7. 11
      src/main/java/de/srsoftware/widerhall/data/User.java
  8. 33
      src/main/java/de/srsoftware/widerhall/mail/Forwarder.java
  9. 123
      src/main/java/de/srsoftware/widerhall/mail/ImapClient.java
  10. 31
      src/main/java/de/srsoftware/widerhall/mail/SmtpClient.java
  11. 133
      src/main/java/de/srsoftware/widerhall/web/Rest.java
  12. 68
      src/main/java/de/srsoftware/widerhall/web/Web.java
  13. 6
      static/templates/add_list.st
  14. 3
      static/templates/frontpage.st
  15. 2
      static/templates/index.st
  16. 19
      static/templates/inspect.st
  17. 23
      static/templates/js.st
  18. 5
      static/templates/listadminlist.st
  19. 2
      static/templates/register.st
  20. 2
      static/templates/subscribe.st
  21. 2
      static/templates/unsubscribe.st

85
doc/data structure.dia

@ -868,13 +868,13 @@ @@ -868,13 +868,13 @@
</dia:object>
<dia:object type="Flowchart - Box" version="0" id="O18">
<dia:attribute name="obj_pos">
<dia:point val="12,19"/>
<dia:point val="12,21"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="11.95,18.95;17.05,21.05"/>
<dia:rectangle val="11.95,20.95;17.05,23.05"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="12,19"/>
<dia:point val="12,21"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5"/>
@ -900,7 +900,7 @@ @@ -900,7 +900,7 @@
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="pos">
<dia:point val="14.5,20.1941"/>
<dia:point val="14.5,22.1941"/>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#000000ff"/>
@ -913,13 +913,13 @@ @@ -913,13 +913,13 @@
</dia:object>
<dia:object type="Flowchart - Box" version="0" id="O19">
<dia:attribute name="obj_pos">
<dia:point val="12,21"/>
<dia:point val="12,23"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="11.95,20.95;17.05,23.05"/>
<dia:rectangle val="11.95,22.95;17.05,25.05"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="12,21"/>
<dia:point val="12,23"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5"/>
@ -945,7 +945,7 @@ @@ -945,7 +945,7 @@
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="pos">
<dia:point val="14.5,22.1941"/>
<dia:point val="14.5,24.1941"/>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#000000ff"/>
@ -958,13 +958,13 @@ @@ -958,13 +958,13 @@
</dia:object>
<dia:object type="Flowchart - Box" version="0" id="O20">
<dia:attribute name="obj_pos">
<dia:point val="12,23"/>
<dia:point val="12,25"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="11.95,22.95;17.05,25.05"/>
<dia:rectangle val="11.95,24.95;17.05,27.05"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="12,23"/>
<dia:point val="12,25"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5"/>
@ -990,7 +990,7 @@ @@ -990,7 +990,7 @@
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="pos">
<dia:point val="14.5,24.1941"/>
<dia:point val="14.5,26.1941"/>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#000000ff"/>
@ -1003,13 +1003,13 @@ @@ -1003,13 +1003,13 @@
</dia:object>
<dia:object type="Flowchart - Box" version="0" id="O21">
<dia:attribute name="obj_pos">
<dia:point val="12,25"/>
<dia:point val="12,27"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="11.95,24.95;17.05,27.05"/>
<dia:rectangle val="11.95,26.95;17.05,29.05"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="12,25"/>
<dia:point val="12,27"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5"/>
@ -1035,7 +1035,7 @@ @@ -1035,7 +1035,7 @@
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="pos">
<dia:point val="14.5,26.1941"/>
<dia:point val="14.5,28.1941"/>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#000000ff"/>
@ -1562,13 +1562,13 @@ @@ -1562,13 +1562,13 @@
</dia:object>
<dia:object type="Flowchart - Box" version="0" id="O34">
<dia:attribute name="obj_pos">
<dia:point val="12,27"/>
<dia:point val="12,29"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="11.95,26.95;17.05,29.05"/>
<dia:rectangle val="11.95,28.95;17.05,31.05"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="12,27"/>
<dia:point val="12,29"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5"/>
@ -1594,7 +1594,7 @@ @@ -1594,7 +1594,7 @@
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="pos">
<dia:point val="14.5,28.1941"/>
<dia:point val="14.5,30.1941"/>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#000000ff"/>
@ -1650,5 +1650,50 @@ @@ -1650,5 +1650,50 @@
</dia:composite>
</dia:attribute>
</dia:object>
<dia:object type="Flowchart - Box" version="0" id="O36">
<dia:attribute name="obj_pos">
<dia:point val="12,19"/>
</dia:attribute>
<dia:attribute name="obj_bb">
<dia:rectangle val="11.95,18.95;17.05,21.05"/>
</dia:attribute>
<dia:attribute name="elem_corner">
<dia:point val="12,19"/>
</dia:attribute>
<dia:attribute name="elem_width">
<dia:real val="5"/>
</dia:attribute>
<dia:attribute name="elem_height">
<dia:real val="2"/>
</dia:attribute>
<dia:attribute name="show_background">
<dia:boolean val="true"/>
</dia:attribute>
<dia:attribute name="padding">
<dia:real val="0.5"/>
</dia:attribute>
<dia:attribute name="text">
<dia:composite type="text">
<dia:attribute name="string">
<dia:string>#inbox#</dia:string>
</dia:attribute>
<dia:attribute name="font">
<dia:font family="sans" style="0" name="Helvetica"/>
</dia:attribute>
<dia:attribute name="height">
<dia:real val="0.80000000000000004"/>
</dia:attribute>
<dia:attribute name="pos">
<dia:point val="14.5,20.1941"/>
</dia:attribute>
<dia:attribute name="color">
<dia:color val="#000000ff"/>
</dia:attribute>
<dia:attribute name="alignment">
<dia:enum val="1"/>
</dia:attribute>
</dia:composite>
</dia:attribute>
</dia:object>
</dia:layer>
</dia:diagram>

2
pom.xml

@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
<groupId>org.example</groupId>
<artifactId>Widerhall</artifactId>
<version>0.0.13</version>
<version>0.0.19</version>
<build>
<plugins>
<plugin>

2
src/main/java/de/srsoftware/widerhall/Constants.java

@ -5,10 +5,10 @@ public class Constants { @@ -5,10 +5,10 @@ public class Constants {
public static final String BASE_URL = "base_url";
public static final String CONFIG = "configuration";
public static final String DB = "database";
public static final String DEFAULT_INBOX = "INBOX";
public static final String DOMAIN = "domain";
public static final String EMAIL = "email";
public static final String ERROR = "error";
public static final String HOST = "host";
public static final String IMAPS = "imaps";
public static final String INBOX = "inbox";
public static final String INDEX = "index";

28
src/main/java/de/srsoftware/widerhall/Util.java

@ -1,7 +1,12 @@ @@ -1,7 +1,12 @@
package de.srsoftware.widerhall;
import de.srsoftware.tools.translations.Translation;
import de.srsoftware.widerhall.data.MailingList;
import de.srsoftware.widerhall.data.User;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@ -9,6 +14,8 @@ import java.security.NoSuchAlgorithmException; @@ -9,6 +14,8 @@ import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.stream.Collectors;
import static de.srsoftware.widerhall.Constants.*;
public class Util {
private static final MessageDigest SHA256 = getSha256();
@ -90,4 +97,25 @@ public class Util { @@ -90,4 +97,25 @@ public class Util {
}
return value;
}
public static User getUser(HttpServletRequest req) {
var o = req.getSession().getAttribute(USER);
return o instanceof User ? (User) o : null;
}
public static String getPath(HttpServletRequest req) {
var path = req.getPathInfo();
return path == null ? INDEX : path.substring(1);
}
public static MailingList getMailingList(HttpServletRequest req) {
var listEmail = req.getParameter(LIST);
if (listEmail == null || listEmail.isBlank()) return null;
return MailingList.load(listEmail);
}
public static boolean getCheckbox(HttpServletRequest req, String key) {
return "on".equals(req.getParameter(key));
}
}

78
src/main/java/de/srsoftware/widerhall/data/ListMember.java

@ -11,6 +11,7 @@ import java.sql.SQLException; @@ -11,6 +11,7 @@ import java.sql.SQLException;
import java.util.*;
import static de.srsoftware.widerhall.Constants.*;
import static de.srsoftware.widerhall.Constants.STATE;
/**
* @author Stephan Richter
@ -26,19 +27,21 @@ public class ListMember { @@ -26,19 +27,21 @@ public class ListMember {
private static final String USER_EMAIL = "user_email";
private static final String STATE = "state";
private final String listEmail,token,userEmail;
private MailingList list;
private User user;
private final String token;
private final int state;
/**
* create a new list member object
* @param listEmail
* @param userEmail
* @param list
* @param user
* @param state
* @param token
*/
public ListMember(String listEmail, String userEmail, int state, String token){
this.listEmail = listEmail;
this.userEmail = userEmail;
public ListMember(MailingList list, User user, int state, String token){
this.list = list;
this.user = user;
this.state = state;
this.token = token;
}
@ -59,19 +62,18 @@ public class ListMember { @@ -59,19 +62,18 @@ public class ListMember {
if (rs.next()){
var lm = ListMember.from(rs);
rs.close();
User user = User.loadAll(List.of(lm.userEmail)).stream().findAny().orElse(null);
if (user != null){
if (lm.user != null){
int newState = lm.state ^ STATE_AWAITING_CONFIRMATION | STATE_SUBSCRIBER;
Database.open()
.update(TABLE_NAME)
.set(TOKEN,null)
.set(STATE, newState) //drop confirmation state, set subscriber state
.where(LIST_EMAIL,lm.listEmail)
.where(USER_EMAIL,lm.userEmail)
.where(LIST_EMAIL,lm.list.email())
.where(USER_EMAIL,lm.user.email())
.compile()
.run();
}
return user;
return lm.user;
}
return null;
}
@ -91,7 +93,7 @@ public class ListMember { @@ -91,7 +93,7 @@ public class ListMember {
if ((state & STATE_AWAITING_CONFIRMATION) > 0){
token = Util.sha256(String.join("/",list.email(),user.email(),user.salt()));
}
return new ListMember(list.email(),user.email(),state,token).save();
return new ListMember(list,user,state,token).save();
}
/**
@ -118,8 +120,8 @@ public class ListMember { @@ -118,8 +120,8 @@ public class ListMember {
*/
public static ListMember from(ResultSet rs) throws SQLException {
return new ListMember(
rs.getString(LIST_EMAIL),
rs.getString(USER_EMAIL),
MailingList.load(rs.getString(LIST_EMAIL)),
User.load(rs.getString(USER_EMAIL)),
rs.getInt(STATE),
rs.getString(TOKEN));
}
@ -175,28 +177,24 @@ public class ListMember { @@ -175,28 +177,24 @@ public class ListMember {
return null;
}
/**
* return a map of User State for a given MailingList
* @param listEmail
* @return
* @throws SQLException
*/
public static Map<User,Integer> of(String listEmail) throws SQLException {
// Step 1: create mal USER_EMAIL → STATE for MailingList
var rs = Database.open()
.select(TABLE_NAME)
.where(LIST_EMAIL,listEmail)
.compile()
.exec();
var temp = new HashMap<String,Integer>();
while (rs.next()) temp.put(rs.getString(USER_EMAIL),rs.getInt(STATE));
rs.close();
// Step 2: map user emails to users
var result = new HashMap<User,Integer>();
User.loadAll(temp.keySet())
.stream()
.forEach(user -> result.put(user,temp.get(user.email())));
return result;
public static Set<ListMember> of(MailingList list) throws SQLException {
var rs = Database.open().select(TABLE_NAME).where(LIST_EMAIL,list.email()).compile().exec();
var set = new HashSet<ListMember>();
try {
while (rs.next()) set.add(ListMember.from(rs));
} finally {
rs.close();
}
return set;
}
public Map<String,Object> safeMap(){
return Map.of(
EMAIL,user.email(),
NAME,user.name(),
STATE,ListMember.stateText(state)
);
}
/**
@ -207,8 +205,8 @@ public class ListMember { @@ -207,8 +205,8 @@ public class ListMember {
private ListMember save() throws SQLException {
var req = Database.open()
.insertInto(TABLE_NAME)
.set(LIST_EMAIL,listEmail)
.set(USER_EMAIL,userEmail)
.set(LIST_EMAIL,list.email())
.set(USER_EMAIL,user.email())
.set(STATE,state);
if (token != null) req.set(TOKEN,token);
req.compile().run();
@ -255,4 +253,8 @@ public class ListMember { @@ -255,4 +253,8 @@ public class ListMember {
req.where(LIST_EMAIL,list.email()).where(USER_EMAIL,user.email()).compile().run();
}
}
public User user(){
return user;
}
}

216
src/main/java/de/srsoftware/widerhall/data/MailingList.java

@ -1,15 +1,21 @@ @@ -1,15 +1,21 @@
package de.srsoftware.widerhall.data;
import de.srsoftware.widerhall.Configuration;
import de.srsoftware.widerhall.mail.ImapClient;
import de.srsoftware.widerhall.mail.MessageHandler;
import de.srsoftware.widerhall.mail.SmtpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Stream;
import static de.srsoftware.widerhall.Constants.*;
import static de.srsoftware.widerhall.Util.t;
@ -18,7 +24,7 @@ import static de.srsoftware.widerhall.data.User.PERMISSION_ADMIN; @@ -18,7 +24,7 @@ import static de.srsoftware.widerhall.data.User.PERMISSION_ADMIN;
/**
* this class encapsulates a MailingList db object
*/
public class MailingList {
public class MailingList implements MessageHandler {
private static final Logger LOG = LoggerFactory.getLogger(MailingList.class);
private static final String IMAP_HOST = "imap_host";
private static final String IMAP_PORT = "imap_port";
@ -32,14 +38,17 @@ public class MailingList { @@ -32,14 +38,17 @@ public class MailingList {
private static final int STATE_PENDING = 0;
private static final int STATE_ENABLED = 1;
private static final int STATE_PUBLIC = 2;
public static final int STATE_FORWARD_FROM = 4;
public static final int STATE_FORWARD_ATTACHED = 8;
private static final int VISIBLE = 1;
private static final int HIDDEN = 0;
private final String name;
private final String email;
private final String imapPass, imapHost, imapUser;
private final int imapPort;
private int state;
private final SmtpClient smtp;
private final ImapClient imap;
private static final HashMap<String,MailingList> lists = new HashMap<>();
private static final HashMap<String,MailingList> cache = new HashMap<>();
/**
* create a new ML object
@ -55,15 +64,12 @@ public class MailingList { @@ -55,15 +64,12 @@ public class MailingList {
* @param smtpPass
* @param state
*/
public MailingList(String email, String name, String imapHost, int imapPort, String imapUser, String imapPass, String smtpHost, int smtpPort, String smtpUser, String smtpPass, int state) {
public MailingList(String email, String name, String imapHost, int imapPort, String imapUser, String imapPass, String inbox, String smtpHost, int smtpPort, String smtpUser, String smtpPass, int state) {
this.email = email;
this.name = name;
this.imapHost = imapHost;
this.imapPort = imapPort;
this.imapUser = imapUser;
this.imapPass = imapPass;
this.state = state;
this.smtp = new SmtpClient(smtpHost,smtpPort,smtpUser,smtpPass);
this.imap = new ImapClient(imapHost,imapPort,imapUser,imapPass,inbox);
}
/**
@ -81,8 +87,8 @@ public class MailingList { @@ -81,8 +87,8 @@ public class MailingList {
* @return
* @throws SQLException
*/
public static MailingList create(String email, String name, String imapHost, int imapPort, String imapUser, String imapPass, String smtpHost, int smtpPort, String smtpUser, String smtpPass) throws SQLException {
return new MailingList(email, name, imapHost, imapPort, imapUser, imapPass, smtpHost, smtpPort, smtpUser, smtpPass, STATE_PENDING).save();
public static MailingList create(String email, String name, String imapHost, int imapPort, String imapUser, String imapPass, String inbox, String smtpHost, int smtpPort, String smtpUser, String smtpPass) throws SQLException {
return new MailingList(email, name, imapHost, imapPort, imapUser, imapPass, inbox, smtpHost, smtpPort, smtpUser, smtpPass, STATE_PENDING).save();
}
/**
@ -99,6 +105,7 @@ public class MailingList { @@ -99,6 +105,7 @@ public class MailingList {
.append(IMAP_PORT).append(" ").append(INT).append(", ")
.append(IMAP_USER).append(" ").append(VARCHAR).append(", ")
.append(IMAP_PASS).append(" ").append(VARCHAR).append(", ")
.append(INBOX).append(" ").append(VARCHAR).append(", ")
.append(SMTP_HOST).append(" ").append(VARCHAR).append(", ")
.append(SMTP_PORT).append(" ").append(INT).append(", ")
.append(SMTP_USER).append(" ").append(VARCHAR).append(", ")
@ -108,49 +115,51 @@ public class MailingList { @@ -108,49 +115,51 @@ public class MailingList {
Database.open().query(sql).compile().run();
}
/**
* load the set of mailing lists a given user is allowed to edit
* @param user
* @return
*/
public static Set<MailingList> editableBy(User user) {
var list = new HashSet<MailingList>();
for (String key : ListMember.listsOwnedBy(user)) list.add(load(key));
return list;
}
public String email() {
return email;
}
public void enable(boolean enable) throws SQLException {
state = enable ? state | STATE_ENABLED : state ^ (state & STATE_ENABLED);
Database.open().update(TABLE_NAME).set(STATE,state).where(EMAIL, email()).compile().run();
}
setFlag(STATE_ENABLED,enable);
public void hide(boolean hide) throws SQLException {
state = hide ? state ^ (state & STATE_PUBLIC) : state | STATE_PUBLIC;
Database.open().update(TABLE_NAME).set(STATE,state).where(EMAIL, email()).compile().run();
if (enable) {
imap.start().addListener(this);
} else {
imap.stop();
}
}
/**
* test, whether the current ML is subscribable by a given user
* @param user
* @return
*/
public boolean isOpenFor(User user) {
if ((state & STATE_PUBLIC) > 0) return true; // all users may subscribe public mailing lists
if (user == null) return false;
private void forward(Message message) throws MessagingException {
try {
var member = ListMember.load(this,user);
return member.hasState(ListMember.STATE_OWNER|ListMember.STATE_SUBSCRIBER); // owners may subscribe their own mailing lists
var emails = members().stream().map(ListMember::user).map(User::email).toList();
String sender = (state & STATE_FORWARD_FROM) > 0 ? message.getFrom()[0].toString() : email();
smtp.bccForward(sender,message,emails);
} catch (SQLException e) {
LOG.warn("Konnte ListeMember nicht laden: ",e);
return false;
LOG.error("Laden der Listen-Mitglieder von {} fehlgeschlagen. Nachricht kann nicht weitergeleitet werden!",email(),e);
}
}
/**
* load the set of mailing lists a given user is allowed to edit
* @param user
* @return
*/
public static Set<MailingList> editableBy(User user) {
var list = new HashSet<MailingList>();
for (String key : ListMember.listsOwnedBy(user)) list.add(load(key));
return list;
public void forwardAttached(boolean forward) throws SQLException {
setFlag(STATE_FORWARD_ATTACHED,forward);
}
public void forwardFrom(boolean forward) throws SQLException {
setFlag(STATE_FORWARD_FROM,forward);
}
/**
* Create a mailing list object from a ResultSet.
* This is a cached method: if the ML has been loaded before, the already-loaded object will be returned.
@ -161,13 +170,14 @@ public class MailingList { @@ -161,13 +170,14 @@ public class MailingList {
*/
private static MailingList from(ResultSet rs) throws SQLException {
String email = rs.getString(EMAIL);
var ml = lists.get(email);
if (ml == null) lists.put(email,ml = new MailingList(rs.getString(EMAIL),
var ml = cache.get(email);
if (ml == null) cache.put(email,ml = new MailingList(rs.getString(EMAIL),
rs.getString(NAME),
rs.getString(IMAP_HOST),
rs.getInt(IMAP_PORT),
rs.getString(IMAP_USER),
rs.getString(IMAP_PASS),
rs.getString(INBOX),
rs.getString(SMTP_HOST),
rs.getInt(SMTP_PORT),
rs.getString(SMTP_USER),
@ -176,6 +186,31 @@ public class MailingList { @@ -176,6 +186,31 @@ public class MailingList {
return ml;
}
public boolean hasState(int test){
return (state & test) > 0;
}
public void hide(boolean hide) throws SQLException {
setFlag(STATE_PUBLIC,!hide);
}
/**
* test, whether the current ML is subscribable by a given user
* @param user
* @return
*/
public boolean isOpenFor(User user) {
if ((state & STATE_PUBLIC) > 0) return true; // all users may subscribe public mailing lists
if (user == null) return false;
try {
var member = ListMember.load(this,user);
return member.hasState(ListMember.STATE_OWNER|ListMember.STATE_SUBSCRIBER); // owners may subscribe their own mailing lists
} catch (SQLException e) {
LOG.warn("Konnte Listen-Mitglied nicht laden: ",e);
return false;
}
}
/**
* Load a ML object by it's identifying email address.
* This is a cached method: if the ML has been loaded before, the already-loaded object will be returned.
@ -184,7 +219,7 @@ public class MailingList { @@ -184,7 +219,7 @@ public class MailingList {
*/
public static MailingList load(String listEmail) {
if (listEmail == null) return null;
var ml = lists.get(listEmail);
var ml = cache.get(listEmail);
if (ml == null) try {
var rs = Database.open()
.select(TABLE_NAME)
@ -192,11 +227,46 @@ public class MailingList { @@ -192,11 +227,46 @@ public class MailingList {
.compile().exec();
if (rs.next()) ml = MailingList.from(rs);
} catch (SQLException e) {
LOG.debug("Konnte MailingList nicht laden: ",e);
LOG.debug("Konnte Mailing-Liste nicht laden: ",e);
}
return ml;
}
public boolean mayBeAlteredBy(User user) {
if (user.hashPermission(PERMISSION_ADMIN)) return true;
try {
if (ListMember.load(this,user).hasState(ListMember.STATE_OWNER)) return true;
} catch (SQLException e) {
LOG.debug("Fehler beim Laden des Listenmitglieds für ({}, {})",user.email(),email());
}
return false;
}
public boolean mayBeTestedBy(User user) {
if (user.hashPermission(PERMISSION_ADMIN)) return true;
try {
if (ListMember.load(this,user).hasState(ListMember.STATE_OWNER)) return true;
} catch (SQLException e) {
LOG.debug("Fehler beim Laden des Listenmitglieds für ({}, {})",user.email(),email());
}
return false;
}
public Set<ListMember> members() throws SQLException {
return ListMember.of(this);
}
public boolean membersMayBeListedBy(User user) {
if (user.hashPermission(PERMISSION_ADMIN)) return true;
try {
if (ListMember.load(this,user).hasState(ListMember.STATE_OWNER)) return true;
} catch (SQLException e) {
LOG.debug("Fehler beim Laden des Listenmitglieds für ({}, {})",user.email(),email());
}
return false;
}
/**
* creates a map from the current ML object containing only email and name of the ML
* @return
@ -206,7 +276,7 @@ public class MailingList { @@ -206,7 +276,7 @@ public class MailingList {
String[] parts = email.split("@", 2);
map.put(EMAIL,Map.of(PREFIX,parts[0],DOMAIN,parts[1]));
map.put(NAME, name);
map.put(STATE, stateString(state));
map.put(STATE, stateMap());
return map;
}
@ -214,6 +284,13 @@ public class MailingList { @@ -214,6 +284,13 @@ public class MailingList {
return name;
}
@Override
public void onMessageReceived(Message message) throws MessagingException {
LOG.debug("Nachricht empfangen: {}",message.getFrom());
storeMessage(message);
forward(message);
}
/**
* provide the set of mailing lists that are publicy open to subscriptions
* @return
@ -241,12 +318,14 @@ public class MailingList { @@ -241,12 +318,14 @@ public class MailingList {
*/
public Map<String, Object> safeMap() {
var map = minimalMap();
if (imapHost != null) map.put(IMAP_HOST, imapHost);
if (imapPort != 0) map.put(IMAP_PORT, imapPort);
if (imapUser != null) map.put(IMAP_USER, imapUser);
if (imap.host() != null) map.put(IMAP_HOST, imap.host());
if (imap.port() != 0) map.put(IMAP_PORT, imap.port());
if (imap.username() != null) map.put(IMAP_USER, imap.username());
if (imap.folderName() != null) map.put(INBOX,imap.folderName());
if (smtp.host() != null) map.put(SMTP_HOST, smtp.host());
if (smtp.port() != 0) map.put(SMTP_PORT, smtp.port());
if (smtp.username() != null) map.put(SMTP_USER, smtp.username());
map.put(STATE,stateMap());
return map;
}
@ -261,10 +340,11 @@ public class MailingList { @@ -261,10 +340,11 @@ public class MailingList {
.insertInto(TABLE_NAME)
.set(EMAIL, email)
.set(NAME, name)
.set(IMAP_HOST, imapHost)
.set(IMAP_PORT, imapPort)
.set(IMAP_USER, imapUser)
.set(IMAP_PASS, imapPass)
.set(IMAP_HOST, imap.host())
.set(IMAP_PORT, imap.port())
.set(IMAP_USER, imap.username())
.set(IMAP_PASS, imap.password())
.set(INBOX,imap.folderName())
.set(SMTP_HOST, smtp.host())
.set(SMTP_PORT, smtp.port())
.set(SMTP_USER, smtp.username())
@ -290,16 +370,17 @@ public class MailingList { @@ -290,16 +370,17 @@ public class MailingList {
smtp.login().send(email(),name(),user.email(),subject,text);
}
/**
* convert state to readable string
* @param state
* @return
*/
private static String stateString(int state) {
var states = new ArrayList<String>();
states.add((state & STATE_ENABLED) == STATE_ENABLED ? "enabled" : "disabled");
states.add((state & STATE_PUBLIC) == STATE_PUBLIC ? "public" : "hidden");
return String.join(", ", states);
private void setFlag(int flag, boolean on) throws SQLException {
state = on ? state | flag : state ^ (state & flag);
Database.open().update(TABLE_NAME).set(STATE,state).where(EMAIL, email()).compile().run();
}
public Map<String,Integer> stateMap(){
var map = new HashMap<String,Integer>();
if (hasState(STATE_ENABLED)) map.put("enabled",VISIBLE);
if (hasState(STATE_PUBLIC)) map.put("public",VISIBLE);
if (hasState(STATE_FORWARD_FROM)) map.put("original_from",HIDDEN);
return map;
}
/**
@ -335,7 +416,7 @@ public class MailingList { @@ -335,7 +416,7 @@ public class MailingList {
rs.close();
return result;
} catch (SQLException e) {
LOG.warn("Lesen der für {} abbonnierbaren Mailinglisten fehlgeschlagen.",user,e);
LOG.warn("Lesen der abbonnierbaren Mailinglisten von {} fehlgeschlagen.",user,e);
return Set.of();
}
}
@ -360,6 +441,10 @@ public class MailingList { @@ -360,6 +441,10 @@ public class MailingList {
}
}
private void storeMessage(Message message){
// TODO: implement
}
/**
* send a test email to the provided user
@ -372,4 +457,13 @@ public class MailingList { @@ -372,4 +457,13 @@ public class MailingList {
var text = "Wenn Sie diese Nachricht empfangen haben, sind die SMTP-Einstellungen Ihrer Mailing-Liste korrekt.";
smtp.login().send(email(),name(),user.email(),subject,text);
}
public static Stream<InternetAddress> toAddress(String email) {
try {
return Arrays.asList(InternetAddress.parse(email)).stream();
} catch (AddressException e) {
LOG.debug("Parsen von {} fehlgeschlagen",email,e);
return new ArrayList<InternetAddress>().stream();
}
}
}

11
src/main/java/de/srsoftware/widerhall/data/User.java

@ -138,6 +138,17 @@ public class User { @@ -138,6 +138,17 @@ public class User {
return (permissions & permission) > 0;
}
public static User load(String email) throws SQLException {
var rs = Database.open().select(TABLE_NAME).where(EMAIL,email).compile().exec();
try {
if (rs.next()) {
return User.from(rs);
}
return null;
} finally {
rs.close();
}
}
/**
* Load the list of all users. Internally calls loadAll(null)

33
src/main/java/de/srsoftware/widerhall/mail/Forwarder.java

@ -1,33 +0,0 @@ @@ -1,33 +0,0 @@
package de.srsoftware.widerhall.mail;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.Message;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
public class Forwarder implements MessageHandler {
private static final Logger LOG = LoggerFactory.getLogger(Forwarder.class);
private final SmtpClient smtp;
private final String receiver,sender;
public Forwarder(String host, int port, String username, String password, String sender, String receiver) {
this.sender = sender;
this.receiver = receiver;
SmtpClient smtp = new SmtpClient(host,port,username,password);
this.smtp = smtp;
}
@Override
public void onMessageReceived(Message message) throws MessagingException {
LOG.debug("forwarding {}",message.getSubject());
try {
smtp.send(sender,"Stephan Richter",receiver,"Info: "+message.getSubject(),"Neue Mail eingegangen!");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

123
src/main/java/de/srsoftware/widerhall/mail/ImapClient.java

@ -2,7 +2,6 @@ package de.srsoftware.widerhall.mail; @@ -2,7 +2,6 @@ package de.srsoftware.widerhall.mail;
import com.sun.mail.imap.IMAPFolder;
import de.srsoftware.widerhall.Constants;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -13,56 +12,63 @@ import java.util.Properties; @@ -13,56 +12,63 @@ import java.util.Properties;
public class ImapClient {
private static final Logger LOG = LoggerFactory.getLogger(ImapClient.class);
private final JSONObject config;
private boolean stopped = false;
private final int port;
private final String host, username, password, folderName;
private IMAPFolder inbox;
private HashSet<MessageHandler> listeners = new HashSet<>();
private ListeningThread listeningThread;
private Heartbeat heartbeat;
private class ListeningThread extends Thread {
private static final Logger LOG = LoggerFactory.getLogger(ListeningThread.class);
private HashSet<MessageHandler> listeners = new HashSet<>();
private boolean stopped = false;
public ListeningThread addListener(MessageHandler messageHandler) {
listeners.add(messageHandler);
return this;
}
public ListeningThread dropListeners() {
listeners.clear();
return this;
}
@Override
public void run() {
while (!stopped) {
try {
sleep(5000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
try {
openInbox();
} catch (MessagingException e){
LOG.warn("Connection problem:",e);
try {
sleep(1000);
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
LOG.warn("Verbindung-Problem:",e);
}
}
}
private void openInbox() throws MessagingException {
String host = (String) config.get(Constants.HOST);
String username = (String) config.get(Constants.USER);
String password = (String) config.get(Constants.PASSWORD);
String folderName = (String) config.get(Constants.INBOX);
LOG.debug("Connecting and logging in…");
LOG.debug("Verbinden und Einloggen…");
Properties props = imapProps();
Session session = Session.getInstance(props);
Store store = session.getStore(Constants.IMAPS);
store.connect(host,username,password);
LOG.debug("Connected, opening {}:",folderName);
LOG.debug("Verbunden. Öffne {}:",folderName);
inbox = (IMAPFolder)store.getFolder(folderName);
inbox.open(IMAPFolder.READ_WRITE);
while (!stopped){
handleMessages();
LOG.debug("Idling.");
LOG.debug("Warte.");
inbox.idle(true);
}
}
private void handleMessages() throws MessagingException {
LOG.debug("reading email:");
LOG.debug("Lese E-Mail:");
if (!inbox.isOpen()){
inbox.open(IMAPFolder.READ_WRITE);
}
@ -74,7 +80,7 @@ public class ImapClient { @@ -74,7 +80,7 @@ public class ImapClient {
}
private void handle(Message message) throws MessagingException {
LOG.debug("Handling {}",message.getSubject());
LOG.debug("Verarbeite {}",message.getSubject());
for (MessageHandler listener : listeners) listener.onMessageReceived(message);
}
@ -83,18 +89,25 @@ public class ImapClient { @@ -83,18 +89,25 @@ public class ImapClient {
props.put(Constants.PROTOCOL,Constants.IMAPS);
return props;
}
public ListeningThread doStop() {
stopped = true;
return this;
}
}
private class Heartbeat extends Thread{
private static final Logger LOG = LoggerFactory.getLogger(Heartbeat.class);
private boolean stopped = false;
@Override
public void run() {
while (!stopped){
try {
sleep(300034);
if (inbox != null) continue;
LOG.debug("sending NOOP");
LOG.debug("Sende NOOP");
inbox.doCommand(protocol -> {
protocol.simpleCommand("NOOP",null);
return null;
@ -104,21 +117,69 @@ public class ImapClient { @@ -104,21 +117,69 @@ public class ImapClient {
}
}
}
public Heartbeat doStop() {
stopped = true;
return this;
}
}
public ImapClient(String host, int port, String username, String password, String folderName) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.folderName = folderName;
}
public ImapClient addListener(MessageHandler messageHandler) {
if (listeningThread == null) listeningThread = new ListeningThread();
listeningThread.addListener(messageHandler);
return this;
}
public ImapClient(JSONObject config){
this.config = config;
public String host(){
return host;
}
public void start() {
LOG.debug("Creating ListeningThread…");
new ListeningThread().start();
LOG.debug("Creating Heartbeat…");
new Heartbeat().start();
public String username(){
return username;
}
public String password(){
return password;
}
public ImapClient addListener(MessageHandler messageHandler) {
listeners.add(messageHandler);
public int port(){
return port;
}
public String folderName(){
return folderName;
}
public ImapClient start() {
stop();
LOG.debug("Erzeuge ListeningThread…");
(listeningThread = new ListeningThread()).start();
LOG.debug("Erzeuge Heartbeat…");
(heartbeat = new Heartbeat()).start();
return this;
}
public ImapClient stop(){
if (listeningThread != null) {
LOG.debug("Stoppe alten ListeningThread…");
listeningThread.dropListeners().doStop();
listeningThread = null;
}
if (heartbeat != null){
heartbeat.doStop();
heartbeat = null;
}
return this;
}
}

31
src/main/java/de/srsoftware/widerhall/mail/SmtpClient.java

@ -4,10 +4,10 @@ import org.slf4j.Logger; @@ -4,10 +4,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
public class SmtpClient {
@ -19,6 +19,7 @@ public class SmtpClient { @@ -19,6 +19,7 @@ public class SmtpClient {
private static final String UTF8 = "UTF-8";
private final String host,password,username;
private final int port;
private boolean forwardUsingListAddress = true;
private Session session;
@ -29,6 +30,25 @@ public class SmtpClient { @@ -29,6 +30,25 @@ public class SmtpClient {
this.port = port;
}
public void bccForward(String from, Message message, List<String> emails) throws MessagingException {
if (session == null) login();
MimeMessage forward = new MimeMessage(session);
forward.setFrom(from);
forward.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(String.join(", ",emails)));
forward.setSubject(message.getSubject());
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message.getDataHandler());
multipart.addBodyPart(messageBodyPart);
forward.setContent(multipart);
send(forward);
}
public SmtpClient login(){
if (session == null) {
Properties props = new Properties();
@ -38,7 +58,7 @@ public class SmtpClient { @@ -38,7 +58,7 @@ public class SmtpClient {
props.put(SSL, true);
session = Session.getInstance(props);
LOG.debug("Created new session: {}", session);
LOG.debug("Neue Session erzeugt: {}", session);
}
return this;
}
@ -55,10 +75,14 @@ public class SmtpClient { @@ -55,10 +75,14 @@ public class SmtpClient {
message.setText(content,UTF8);
message.setSentDate(new Date());
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(receivers,false));
send(message);
}
public void send(Message message) throws MessagingException {
LOG.debug("Versende Mail…");
Transport.send(message,username,password);
LOG.debug("…versendet");
}
public String host() {
@ -76,4 +100,5 @@ public class SmtpClient { @@ -76,4 +100,5 @@ public class SmtpClient {
public String password() {
return password;
}
}

133
src/main/java/de/srsoftware/widerhall/web/Rest.java

@ -1,5 +1,6 @@ @@ -1,5 +1,6 @@
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.User;
@ -16,6 +17,7 @@ import java.io.IOException; @@ -16,6 +17,7 @@ import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ -27,6 +29,7 @@ public class Rest extends HttpServlet { @@ -27,6 +29,7 @@ public class Rest extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(Rest.class);
private static final String LIST_DISABLE = "list/disable";
private static final String LIST_EDITABLE = "list/editable";
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";
@ -40,7 +43,7 @@ public class Rest extends HttpServlet { @@ -40,7 +43,7 @@ public class Rest extends HttpServlet {
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!");
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);
@ -83,12 +86,25 @@ public class Rest extends HttpServlet { @@ -83,12 +86,25 @@ public class Rest extends HttpServlet {
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){
Object o = req.getSession().getAttribute(USER);
var user = Util.getUser(req);
var path = Util.getPath(req);
JSONObject json = new JSONObject();
var path = req.getPathInfo();
path = path == null ? INDEX : path.substring(1);
if (o instanceof User user){
if (user != null){
json.put(USER,user.safeMap());
switch (path) {
case USER_LIST:
@ -104,6 +120,7 @@ public class Rest extends HttpServlet { @@ -104,6 +120,7 @@ public class Rest extends HttpServlet {
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;
@ -127,35 +144,38 @@ public class Rest extends HttpServlet { @@ -127,35 +144,38 @@ public class Rest extends HttpServlet {
}
public String handlePost(HttpServletRequest req, HttpServletResponse resp){
Object o = req.getSession().getAttribute(USER);
JSONObject json = new JSONObject();
var path = req.getPathInfo();
path = path == null ? INDEX : path.substring(1);
if (o instanceof User user){
var user = Util.getUser(req);
var path = Util.getPath(req);
JSONObject json = new JSONObject();
if (user != null){
json.put(USER,user.safeMap());
var listEmail = req.getParameter(LIST);
var list = Util.getMailingList(req);
var userEmail = req.getParameter(EMAIL);
var permissions = req.getParameter(PERMISSIONS);
switch (path) {
case LIST_DETAIL:
json.putAll(listDetail(list,user));
break;
case LIST_DISABLE:
json.putAll(enableList(listEmail,user,false));
json.putAll(enableList(list,user,false));
break;
case LIST_ENABLE:
json.putAll(enableList(listEmail,user,true));
json.putAll(enableList(list,user,true));
break;
case LIST_HIDE:
json.putAll(hideList(listEmail,user,true));
json.putAll(hideList(list,user,true));
break;
case LIST_MEMBERS:
json.putAll(listMembers(listEmail,user));
json.putAll(listMembers(list,user));
break;
case LIST_SHOW:
json.putAll(hideList(listEmail,user,false));
json.putAll(hideList(list,user,false));
break;
case LIST_TEST:
json.putAll(testList(listEmail,user));
json.putAll(testList(list,user));
break;
case USER_ADD_PERMISSION:
if (user.hashPermission(User.PERMISSION_ADMIN)){
@ -183,62 +203,47 @@ public class Rest extends HttpServlet { @@ -183,62 +203,47 @@ public class Rest extends HttpServlet {
}
}
private Map<String, Object> listMembers(String listEmail, User user) {
if (listEmail == null || listEmail.isBlank()) return Map.of(ERROR,"no list email provided!");
if (user.hashPermission(User.PERMISSION_ADMIN) || ListMember.listsOwnedBy(user).contains(listEmail)) {
try {
var members = ListMember.of(listEmail)
.entrySet()
.stream()
.map(entry -> Map.of(
EMAIL,entry.getKey().email(),
NAME,entry.getKey().name(),
STATE,ListMember.stateText(entry.getValue())
))
.toList();
return Map.of(MEMBERS,members);
} catch (SQLException e) {
LOG.error("Laden der Mitglieder-Liste fehlgeschlagen: ",e);
return Map.of("error",t("Laden der Mitglieder-Liste von '{}' fehlgeschlagen",listEmail));
}
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 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()));
}
return Map.of("error",t("Sie haben nicht die Berechtigng, um die Mitglieder von '{}' aufzulisten.",listEmail));
}
private Map enableList(String listEmail, User user, boolean enable) {
if (listEmail == null || listEmail.isBlank()) return Map.of(ERROR,"no list email provided!");
if (user.hashPermission(User.PERMISSION_ADMIN) || ListMember.listsOwnedBy(user).contains(listEmail)){
try {
MailingList.load(listEmail).enable(enable);
return Map.of(SUCCESS,t("Mailing-List '{}' wurde {}!",listEmail,enable ? "aktiviert" : "inaktiviert"));
} catch (SQLException e) {
LOG.error("Aktivieren/Inaktivieren der Mailing-Liste fehlgeschlagen: ",e);
return Map.of(ERROR,t("Aktualisieren der Liste '{}' fehlgeschlagen!",listEmail));
}
}
return Map.of(ERROR,t("Sie haben nicht die Berechtigng, '{}' zu bearbeiten",listEmail));
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("forward_from",true);
if (list.hasState(MailingList.STATE_FORWARD_ATTACHED)) map.put("forward_attached",true);
return map;
}
private Map<String, String> hideList(String listEmail, User user, boolean hide) {
if (listEmail == null || listEmail.isBlank()) return Map.of(ERROR,"Keine Listen-Email übergeben!");
if (user.hashPermission(User.PERMISSION_ADMIN) || ListMember.listsOwnedBy(user).contains(listEmail)){
try {
MailingList.load(listEmail).hide(hide);
return Map.of(SUCCESS,t("Mailing-List '{}' wurde {}!",listEmail,hide ? "versteckt" : "veröffentlicht"));
} catch (SQLException e) {
LOG.error("Verstecken/Veröffentlichen der Mailinglist fehlgeschlagen: ",e);
return Map.of("error",t("Aktualisieren der Liste '{}' fehlgeschlagen",listEmail));
}
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("You are not allowed to list members of '{}'",list.email()));
try {
var members = list.members()
.stream()
.map(ListMember::safeMap)
.toList();
return Map.of(MEMBERS,members);
} catch (SQLException e) {
LOG.error("Failed to load member list: ",e);
return Map.of("error",t("Failed to load member list '{}'",list.email()));
}
return Map.of(ERROR,t("Sie haben nicht die Berechtigng, '{}' zu bearbeiten",listEmail));
}
private Map testList(String listEmail, User user) {
if (listEmail == null || listEmail.isBlank()) return Map.of(ERROR,"Keine Listen-Email übergeben!");
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("You are not allowed to test '{}'",list.email()));
try {
MailingList.load(listEmail).test(user);
return Map.of(SUCCESS,t("Test-Email an {} gesendet",user.email()));
list.test(user);
return Map.of(SUCCESS,t("Sent test email to {}",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()));

68
src/main/java/de/srsoftware/widerhall/web/Web.java

@ -1,25 +1,17 @@ @@ -1,25 +1,17 @@
package de.srsoftware.widerhall.web;
import de.srsoftware.widerhall.Configuration;
import de.srsoftware.widerhall.Constants;
import de.srsoftware.widerhall.Util;
import de.srsoftware.widerhall.data.ListMember;
import de.srsoftware.widerhall.data.MailingList;
import de.srsoftware.widerhall.data.User;
import org.antlr.runtime.MismatchedTokenException;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STRawGroupDir;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.sql.SQLException;
import java.util.HashMap;
@ -34,6 +26,7 @@ public class Web extends TemplateServlet { @@ -34,6 +26,7 @@ public class Web extends TemplateServlet {
private static final String CONFIRM = "confirm";
private static final Logger LOG = LoggerFactory.getLogger(Web.class);
private static final String ADMIN = "admin";
private static final String INSPECT = "inspect";
private static final String LOGIN = "login";
private static final String LOGOUT = "logout";
private static final String REGISTER = "register";
@ -75,6 +68,10 @@ public class Web extends TemplateServlet { @@ -75,6 +68,10 @@ public class Web extends TemplateServlet {
var imapUser = req.getParameter(IMAP_USER);
data.put(IMAP_USER, imapUser);
var imapPass = req.getParameter(IMAP_PASS);
var inbox = req.getParameter(INBOX);
if (inbox == null || inbox.isBlank()) inbox = DEFAULT_INBOX;
data.put(INBOX, inbox);
var smtpHost = req.getParameter(SMTP_HOST);
data.put(SMTP_HOST, smtpHost);
var smtpUser = req.getParameter(SMTP_USER);
@ -125,7 +122,7 @@ public class Web extends TemplateServlet { @@ -125,7 +122,7 @@ public class Web extends TemplateServlet {
}
try {
var list = MailingList.create(email, name, imapHost, imapPort, imapUser, imapPass, smtpHost, smtpPort, smtpUser, smtpPass);
var list = MailingList.create(email, name, imapHost, imapPort, imapUser, imapPass, inbox, smtpHost, smtpPort, smtpUser, smtpPass);
ListMember.create(list, user, ListMember.STATE_OWNER);
return redirectTo(INDEX, resp);
} catch (SQLException e) {
@ -250,11 +247,15 @@ public class Web extends TemplateServlet { @@ -250,11 +247,15 @@ public class Web extends TemplateServlet {
}
private String handlePost(HttpServletRequest req, HttpServletResponse resp) {
var path = req.getPathInfo();
path = path == null ? INDEX : path.substring(1);
final var user = Util.getUser(req);
final var path = Util.getPath(req);
final var list = Util.getMailingList(req);
switch (path){
case ADD_LIST:
return addList(req,resp);
case INSPECT:
return inspect(req,resp);
case LOGIN:
return handleLogin(req,resp);
case REGISTER:
@ -268,8 +269,39 @@ public class Web extends TemplateServlet { @@ -268,8 +269,39 @@ public class Web extends TemplateServlet {
return t("Kein Handler für den Pfad '{}'!",path);
}
private String inspect(HttpServletRequest req, HttpServletResponse resp) {
var user = Util.getUser(req);
if (user == null) return redirectTo(LOGIN,resp);
var data = new HashMap<String,Object>();
var error = false;
var list = Util.getMailingList(req);
if (list == null) {
error = true;
data.put(ERROR, t("Keine gültige MailingListe übermittelt!"));
} else data.put(LIST, list.email());
if (!error && !list.mayBeAlteredBy(user)) {
error = true;
data.put(ERROR,t("Es ist Ihnen nicht gestattet, diese Mailinglist zu verändern!"));
}
if (!error){
var dummy = req.getParameterMap();
try {
list.forwardFrom(Util.getCheckbox(req, "forward_from"));
list.forwardAttached(Util.getCheckbox(req, "forward_attached"));
data.put(NOTES,t("Mailing-Liste aktualisiert!"));
} catch (SQLException e){
LOG.warn("Aktualisierung der Mailing-Liste fehlgeschlagen:",e);
data.put(ERROR,t("Aktualisierung der Mailing-Liste fehlgeschlagen!"));
}
LOG.debug("params: {}",dummy);
}
return loadTemplate(INSPECT,data,resp);
}
private String redirectTo(String page, HttpServletResponse resp) {
@ -401,13 +433,13 @@ public class Web extends TemplateServlet { @@ -401,13 +433,13 @@ public class Web extends TemplateServlet {
if (user != null) data.put(USER,user.safeMap());
if (list == null){
data.put(ERROR,"No list provided by form data!");
data.put(ERROR,"Keine Mailin-Liste in den Formular-Daten übermittelt!!");
return loadTemplate(UNSUBSCRIBE,data,resp);
}
if (user == null) {
if (email == null || email.isBlank()) {
data.put(ERROR, "Email is required for list un-subscription!");
data.put(ERROR, "Für das Abbestellen ist eine E-Mail-Adresse erforderlich!");
return loadTemplate(UNSUBSCRIBE, data, resp);
}
if (pass != null && pass.isBlank()) pass = null;
@ -417,18 +449,18 @@ public class Web extends TemplateServlet { @@ -417,18 +449,18 @@ public class Web extends TemplateServlet {
req.getSession().setAttribute(USER,user);
data.put(USER,user.safeMap());
} catch (InvalidKeyException | SQLException e) {
data.put(ERROR,"Invalid email/password combination!");
data.put(ERROR,"Ungültige E-Mail-/Passwort-Kombination!");
return loadTemplate(UNSUBSCRIBE,data,resp);
}
}
// if we get here, we should have a valid user
try {
ListMember.unsubscribe(list,user);
data.put(NOTES,t("Sucessfully un-subscribed from '{}'.",list.email()));
data.put(NOTES,t("'{}' erfolgreich abbestellt.",list.email()));
return loadTemplate(INDEX,data,resp);
} catch (SQLException e) {
LOG.warn("Problem during unscubsription of {} from {}:",user.email(),list.email(),e);
data.put(ERROR,"Failed to unsubscribe!");
LOG.warn("Es ist ein Problem beim Entfernen von {} aus der Liste {} aufgetreten:",user.email(),list.email(),e);
data.put(ERROR,"Abbestellen der Mailin-Liste fehlgeschlagen!");
return loadTemplate(UNSUBSCRIBE,data,resp);
}

6
static/templates/add_list.st

@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
«navigation()»
«userinfo()»
<h1>Widerhall Listen-Erzeugung</h1>
@ -43,6 +43,10 @@ @@ -43,6 +43,10 @@
<input type="password" name="imap_pass" value="«data.imap_pass»" id="imap_pass" />
Passwort
</label>
<label>
<input type="text" name="inbox" value="«if(data.inbox)»«data.inbox»«else»INBOX«endif»" id="imap_inbox" />
Inbox name
</label>
</fieldset>
<fieldset>
<legend>SMTP-Protokoll</legend>

3
static/templates/frontpage.st

@ -3,7 +3,7 @@ @@ -3,7 +3,7 @@
<head>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
<h1>Widerhall Startseite</h1>
Falls du zu den Mailing-Listen willst, <a href="web/index">Gehe zur Seite /web</a>...
<fieldset>
@ -35,5 +35,6 @@ @@ -35,5 +35,6 @@
Das ist alles.
</p>
</fieldset>
«footer()»
</body>
</html>

2
static/templates/index.st

@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
«navigation()»
«userinfo()»
«messages()»

19
static/templates/inspect.st

@ -6,11 +6,28 @@ @@ -6,11 +6,28 @@
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
«navigation()»
«userinfo()»
«messages()»
<h1>Widerhall '«data.list»'-Details</h1>
«listmembers()»
<form method="POST">
<fieldset>
<legend>Options for «data.list»</legend>
<label>
<input type="checkbox" name="forward_from">
Forward using original sender
</label>
<label>
<input type="checkbox" name="forward_attached">
Append original message as attachment
</label>
<button type="submit">Save</button>
</fieldset>
</form>
<script type="text/javascript">
loadListDetail('«data.list»');
</script>
</body>
</html>

23
static/templates/js.st

@ -27,6 +27,10 @@ function hideList(listEmail){ @@ -27,6 +27,10 @@ function hideList(listEmail){
$.post('/api/list/hide',{list:listEmail},showListResult,'json');
}
function loadListDetail(listEmail){
$.post('/api/list/detail',{list:listEmail},showListDetail,'json');
}
function loadListOfEditableLists(){
$.getJSON('/api/list/editable', showListOfEditableLists);
}
@ -51,6 +55,12 @@ function showList(listEmail){ @@ -51,6 +55,12 @@ function showList(listEmail){
$.post('/api/list/show',{list:listEmail},showListResult,'json');
}
function showListDetail(data){
console.log(data);
if (data.forward_from) $('input[name="forward_from"]').prop('checked',true);
if (data.forward_attached) $('input[name="forward_attached"]').prop('checked',true);
}
function showListOfEditableLists(data){
for (let i in data.lists){
let list = data.lists[i];
@ -63,7 +73,11 @@ function showListOfEditableLists(data){ @@ -63,7 +73,11 @@ function showListOfEditableLists(data){
td = $('<td/>');
$('<a/>',{href:inspect}).text(addr).appendTo(td)
td.appendTo(row);
$('<td/>').text(list.state).appendTo(row);
let states = [];
for (let state in list.state){
if (list.state[state] > 0) states.push(state);
}
$('<td/>').text(states.toString()).appendTo(row);
let select = $('<select/>',{name:addr}).change(function () {
let action = $(this).children("option:selected").val();
@ -78,6 +92,7 @@ function showListOfEditableLists(data){ @@ -78,6 +92,7 @@ function showListOfEditableLists(data){
$('<td/>').text(list.imap_host).appendTo(row);
$('<td/>').text(list.imap_port).appendTo(row);
$('<td/>').text(list.imap_user).appendTo(row);
$('<td/>').text(list.inbox).appendTo(row);
$('<td/>').text(list.smtp_host).appendTo(row);
$('<td/>').text(list.smtp_port).appendTo(row);
$('<td/>').text(list.smtp_user).appendTo(row);
@ -98,7 +113,11 @@ function showListList(data){ @@ -98,7 +113,11 @@ function showListList(data){
$('<td/>',{class:'right'}).text(list.email.prefix).appendTo(row);
$('<td/>',{class:'right'}).text('@').appendTo(row);
$('<td/>').text(list.email.domain).appendTo(row);
$('<td/>').text(list.state).appendTo(row);
let states = [];
for (let state in list.state){
if (list.state[state] > 0) states.push(state);
}
$('<td/>').text(states.toString()).appendTo(row);
let td = $('<td/>',{class:'actions'});
$('<button/>',{onclick:"subscribeTo('"+list.email.domain+"', '"+list.email.prefix+"');"}).text('abonnieren').appendTo(td);
$('<button/>',{onclick:"unsubscribeFrom('"+list.email.domain+"', '"+list.email.prefix+"');"}).text('abbestellen').appendTo(td);

5
static/templates/listadminlist.st

@ -2,8 +2,8 @@ @@ -2,8 +2,8 @@
<legend>Liste der (bearbeitbaren) Mailing-Listen</legend>
<table id="listlist">
<tr>
<th colspan="4">Liste</th>
<th colspan="3">IMAP</th>
<th colspan="4">List</th>
<th colspan="4">IMAP</th>
<th colspan="3">SMTP</th>
</tr>
<tr>
@ -14,6 +14,7 @@ @@ -14,6 +14,7 @@
<th>Host</th>
<th>Port</th>
<th>Benutzername</th>
<th>Posteingang</th>
<th>Host</th>
<th>Port</th>
<th>Benutzername</th>

2
static/templates/register.st

@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
«navigation()»
«userinfo()»
<h1>Widerhall Nutzer-Registrierung</h1>

2
static/templates/subscribe.st

@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
«navigation()»
«userinfo()»
«messages()»

2
static/templates/unsubscribe.st

@ -6,7 +6,7 @@ @@ -6,7 +6,7 @@
<script src="js"></script>
<link rel="stylesheet" href="css" />
</head>
<body id="login">
<body>
«navigation()»
«userinfo()»
«messages()»

Loading…
Cancel
Save