]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/EmailAddress.java
319e415b93e86a97d89da13ddcf5b18e8df12ec8
[gigi.git] / src / club / wpia / gigi / dbObjects / EmailAddress.java
1 package club.wpia.gigi.dbObjects;
2
3 import java.io.IOException;
4 import java.util.Date;
5 import java.util.LinkedList;
6 import java.util.Locale;
7
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
17 public class EmailAddress implements IdCachable, Verifyable {
18
19     public static final int REPING_MINIMUM_DELAY = 5 * 60 * 1000;
20
21     private String address;
22
23     private int id;
24
25     private User owner;
26
27     private EmailAddress(int id) {
28         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid`, `email` FROM `emails` WHERE `id`=? AND `deleted` IS NULL")) {
29             ps.setInt(1, id);
30
31             GigiResultSet rs = ps.executeQuery();
32             if ( !rs.next()) {
33                 throw new IllegalArgumentException("Invalid email id " + id);
34             }
35             this.id = id;
36             owner = User.getById(rs.getInt(1));
37             address = rs.getString(2);
38         }
39     }
40
41     public EmailAddress(User owner, String address, Locale mailLocale) throws GigiApiException {
42         address = address.toLowerCase();
43         if ( !EmailProvider.isValidMailAddress(address)) {
44             throw new IllegalArgumentException("Invalid email.");
45         }
46         this.address = address;
47         this.owner = owner;
48         insert(Language.getInstance(mailLocale));
49     }
50
51     private void insert(Language l) throws GigiApiException {
52         try {
53             synchronized (EmailAddress.class) {
54                 if (id != 0) {
55                     throw new IllegalStateException("already inserted.");
56                 }
57                 try (GigiPreparedStatement psCheck = new GigiPreparedStatement("SELECT 1 FROM `emails` WHERE email=? AND deleted is NULL")) {
58                     psCheck.setString(1, address);
59                     GigiResultSet res = psCheck.executeQuery();
60                     if (res.next()) {
61                         throw new GigiApiException("The email address is already known to the system.");
62                     }
63                 }
64                 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `emails` SET memid=?, email=?")) {
65                     ps.setInt(1, owner.getId());
66                     ps.setString(2, address);
67                     ps.execute();
68                     id = ps.lastInsertId();
69                 }
70                 myCache.put(this);
71             }
72             ping(l);
73         } catch (IOException e) {
74             e.printStackTrace();
75         }
76     }
77
78     private void ping(Language l) throws IOException {
79         String hash = RandomToken.generateToken(16);
80         try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`='', `uid`=?, `type`='active', `status`='open'::`pingState`, `challenge`=?")) {
81             statmt.setString(1, address);
82             statmt.setInt(2, owner.getId());
83             statmt.setString(3, hash);
84             statmt.execute();
85         }
86
87         MailProbe.sendMailProbe(l, "email", id, hash, address);
88     }
89
90     public int getId() {
91         return id;
92     }
93
94     public String getAddress() {
95         return address;
96     }
97
98     public synchronized boolean isVerifyable(String hash) throws GigiApiException {
99         try (GigiPreparedStatement stmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
100             stmt.setString(1, address);
101             stmt.setInt(2, owner.getId());
102             stmt.setString(3, hash);
103             return stmt.executeQuery().next();
104         }
105     }
106
107     public synchronized void verify(String hash) throws GigiApiException {
108         try (GigiPreparedStatement stmt = new GigiPreparedStatement("UPDATE `emailPinglog` SET `status`='success'::`pingState` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
109             stmt.setString(1, address);
110             stmt.setInt(2, owner.getId());
111             stmt.setString(3, hash);
112             if ( !stmt.executeMaybeUpdate()) {
113                 throw new IllegalArgumentException("Given token could not be found to complete the verification process (Domain Ping).");
114             }
115         }
116         // Verify user with that primary email
117         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'")) {
118             ps2.setInt(1, owner.getId());
119             ps2.setString(2, address);
120             ps2.execute();
121         }
122     }
123
124     public boolean isVerified() {
125         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `status`='success'")) {
126             statmt.setString(1, address);
127             statmt.setInt(2, owner.getId());
128             GigiResultSet e = statmt.executeQuery();
129             return e.next();
130         }
131     }
132
133     public Date getLastPing(boolean onlySuccess) {
134         Date lastExecution;
135         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT MAX(`when`) FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active'" + (onlySuccess ? " AND `status`='success'" : ""))) {
136             statmt.setString(1, address);
137             statmt.setInt(2, owner.getId());
138             GigiResultSet e = statmt.executeQuery();
139             if ( !e.next()) {
140                 return null;
141             }
142             lastExecution = e.getTimestamp(1);
143         }
144         return lastExecution;
145     }
146
147     public synchronized void requestReping(Language l) throws IOException, GigiApiException {
148         Date lastExecution = getLastPing(false);
149
150         if (lastExecution != null && lastExecution.getTime() + REPING_MINIMUM_DELAY >= System.currentTimeMillis()) {
151             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)));
152         }
153         ping(l);
154         return;
155     }
156
157     private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
158
159     public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
160         EmailAddress em = myCache.get(id);
161         if (em == null) {
162             myCache.put(em = new EmailAddress(id));
163         }
164         return em;
165     }
166
167     public User getOwner() {
168         return owner;
169     }
170
171     public static EmailAddress[] findByAllEmail(String mail) {
172         LinkedList<EmailAddress> results = new LinkedList<EmailAddress>();
173         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")) {
174             ps.setString(1, mail);
175             GigiResultSet rs = ps.executeQuery();
176             while (rs.next()) {
177                 results.add(EmailAddress.getById(rs.getInt(1)));
178             }
179             return results.toArray(new EmailAddress[results.size()]);
180         }
181     }
182 }