1 package club.wpia.gigi.dbObjects;
3 import java.io.IOException;
5 import java.util.LinkedList;
6 import java.util.Locale;
8 import club.wpia.gigi.GigiApiException;
9 import club.wpia.gigi.database.GigiPreparedStatement;
10 import club.wpia.gigi.database.GigiResultSet;
11 import club.wpia.gigi.email.EmailProvider;
12 import club.wpia.gigi.email.MailProbe;
13 import club.wpia.gigi.localisation.Language;
14 import club.wpia.gigi.output.template.SprintfCommand;
15 import club.wpia.gigi.util.RandomToken;
16 import club.wpia.gigi.util.TimeConditions;
18 public class EmailAddress implements IdCachable, Verifyable {
20 public static final int REPING_MINIMUM_DELAY = 5 * 60 * 1000;
22 private String address;
28 private EmailAddress(int id) {
29 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid`, `email` FROM `emails` WHERE `id`=? AND `deleted` IS NULL")) {
32 GigiResultSet rs = ps.executeQuery();
34 throw new IllegalArgumentException("Invalid email id " + id);
37 owner = User.getById(rs.getInt(1));
38 address = rs.getString(2);
42 public EmailAddress(User owner, String address, Locale mailLocale) throws GigiApiException {
43 address = address.toLowerCase();
44 if ( !EmailProvider.isValidMailAddress(address)) {
45 throw new IllegalArgumentException("Invalid email.");
47 this.address = address;
49 insert(Language.getInstance(mailLocale));
52 private void insert(Language l) throws GigiApiException {
54 synchronized (EmailAddress.class) {
56 throw new IllegalStateException("already inserted.");
58 try (GigiPreparedStatement psCheck = new GigiPreparedStatement("SELECT 1 FROM `emails` WHERE email=? AND deleted is NULL")) {
59 psCheck.setString(1, address);
60 GigiResultSet res = psCheck.executeQuery();
62 throw new GigiApiException("The email address is already known to the system.");
65 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `emails` SET memid=?, email=?")) {
66 ps.setInt(1, owner.getId());
67 ps.setString(2, address);
69 id = ps.lastInsertId();
74 } catch (IOException e) {
79 private void ping(Language l) throws IOException {
80 String hash = RandomToken.generateToken(16);
81 try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`='', `uid`=?, `type`='active', `status`='open'::`pingState`, `challenge`=?")) {
82 statmt.setString(1, address);
83 statmt.setInt(2, owner.getId());
84 statmt.setString(3, hash);
88 MailProbe.sendMailProbe(l, "email", id, hash, address);
95 public String getAddress() {
99 public synchronized boolean isVerifyable(String hash) throws GigiApiException {
100 try (GigiPreparedStatement stmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
101 stmt.setString(1, address);
102 stmt.setInt(2, owner.getId());
103 stmt.setString(3, hash);
104 return stmt.executeQuery().next();
108 public synchronized void verify(String hash) throws GigiApiException {
109 try (GigiPreparedStatement stmt = new GigiPreparedStatement("UPDATE `emailPinglog` SET `status`='success'::`pingState` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
110 stmt.setString(1, address);
111 stmt.setInt(2, owner.getId());
112 stmt.setString(3, hash);
113 if ( !stmt.executeMaybeUpdate()) {
114 throw new IllegalArgumentException("Given token could not be found to complete the verification process (Domain Ping).");
117 // Verify user with that primary email
118 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'")) {
119 ps2.setInt(1, owner.getId());
120 ps2.setString(2, address);
125 public boolean isVerified() {
126 try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `status`='success' AND `when` > (now() - interval '1 months' * ?::INTEGER)")) {
127 statmt.setString(1, address);
128 statmt.setInt(2, owner.getId());
129 statmt.setInt(3, TimeConditions.getInstance().getEmailPingMonths());
130 GigiResultSet e = statmt.executeQuery();
135 public Date getLastPing(boolean onlySuccess) {
137 try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT MAX(`when`) FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active'" + (onlySuccess ? " AND `status`='success'" : ""))) {
138 statmt.setString(1, address);
139 statmt.setInt(2, owner.getId());
140 GigiResultSet e = statmt.executeQuery();
144 lastExecution = e.getTimestamp(1);
146 return lastExecution;
149 public synchronized void requestReping(Language l) throws IOException, GigiApiException {
150 Date lastExecution = getLastPing(false);
152 if (lastExecution != null && lastExecution.getTime() + REPING_MINIMUM_DELAY >= System.currentTimeMillis()) {
153 throw new GigiApiException(SprintfCommand.createSimple("Reping is only allowed after {0} minutes, yours end at {1}.", REPING_MINIMUM_DELAY / 60 / 1000, new Date(lastExecution.getTime() + REPING_MINIMUM_DELAY)));
159 private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
161 public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
162 EmailAddress em = myCache.get(id);
164 myCache.put(em = new EmailAddress(id));
169 public User getOwner() {
173 public static EmailAddress[] findByAllEmail(String mail) {
174 LinkedList<EmailAddress> results = new LinkedList<EmailAddress>();
175 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `emails`.`id` FROM `emails` INNER JOIN `users` ON `users`.`id` = `emails`.`memid` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `emails`.`email` LIKE ? AND `emails`.`deleted` IS NULL AND `certOwners`.`deleted` IS NULL ORDER BY `users`.`id`, `emails`.`email` LIMIT 100")) {
176 ps.setString(1, mail);
177 GigiResultSet rs = ps.executeQuery();
179 results.add(EmailAddress.getById(rs.getInt(1)));
181 return results.toArray(new EmailAddress[results.size()]);