Reformatted code, updated to new Analytics tags, fixed a problem with EmailAuthenticator
[zxing.git] / zxingorg / src / com / google / zxing / web / DecodeEmailTask.java
1 /*
2  * Copyright 2008 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.web;
18
19 import com.google.zxing.MultiFormatReader;
20 import com.google.zxing.Reader;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.Result;
23 import com.google.zxing.client.j2se.BufferedImageMonochromeBitmapSource;
24
25 import javax.imageio.ImageIO;
26 import javax.mail.Address;
27 import javax.mail.Authenticator;
28 import javax.mail.Flags;
29 import javax.mail.Folder;
30 import javax.mail.Message;
31 import javax.mail.MessagingException;
32 import javax.mail.Session;
33 import javax.mail.Store;
34 import javax.mail.Transport;
35 import javax.mail.internet.InternetAddress;
36 import javax.mail.internet.MimeBodyPart;
37 import javax.mail.internet.MimeMessage;
38 import javax.mail.internet.MimeMultipart;
39 import java.awt.image.BufferedImage;
40 import java.io.UnsupportedEncodingException;
41 import java.util.Properties;
42 import java.util.TimerTask;
43 import java.util.logging.Level;
44 import java.util.logging.Logger;
45
46 /**
47  * @author Sean Owen
48  */
49 final class DecodeEmailTask extends TimerTask {
50
51   private static final Logger log = Logger.getLogger(DecodeEmailTask.class.getName());
52
53   private static final String SMTP_HOST = "smtp.gmail.com";
54   private static final String POP_HOST = "pop.gmail.com";
55   private static final String SMTP_PORT = "465";
56   private static final String POP_PORT = "995";
57   private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
58   private static final Properties sessionProperties = new Properties();
59   static {
60     sessionProperties.setProperty("mail.transport.protocol", "smtp");
61     sessionProperties.setProperty("mail.smtp.host", SMTP_HOST);
62     sessionProperties.setProperty("mail.smtp.auth", "true");
63     sessionProperties.setProperty("mail.smtp.port", SMTP_PORT);
64     sessionProperties.setProperty("mail.smtp.socketFactory.port", SMTP_PORT);
65     sessionProperties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
66     sessionProperties.setProperty("mail.smtp.socketFactory.fallback", "false");
67     sessionProperties.setProperty("mail.smtp.quitwait", "false");
68     sessionProperties.setProperty("mail.pop3.host", POP_HOST);
69     sessionProperties.setProperty("mail.pop3.auth", "true");
70     sessionProperties.setProperty("mail.pop3.port", POP_PORT);
71     sessionProperties.setProperty("mail.pop3.socketFactory.port", POP_PORT);
72     sessionProperties.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
73     sessionProperties.setProperty("mail.pop3.socketFactory.fallback", "false");
74   }
75
76   private final Authenticator emailAuthenticator;
77   private final Address fromAddress;
78
79   DecodeEmailTask(String emailAddress, Authenticator emailAuthenticator) {
80     this.emailAuthenticator = emailAuthenticator;
81     try {
82       fromAddress = new InternetAddress(emailAddress, "ZXing By Email");
83     } catch (UnsupportedEncodingException uee) {
84       // Can't happen?
85       throw new RuntimeException(uee);
86     }
87   }
88
89   @Override
90   public void run() {
91     log.info("Checking email...");
92     try {
93       Session session = Session.getInstance(sessionProperties, emailAuthenticator);
94       Store store = null;
95       Folder inbox = null;
96       try {
97         store = session.getStore("pop3");
98         store.connect();
99         inbox = store.getFolder("INBOX");
100         inbox.open(Folder.READ_WRITE);
101         int count = inbox.getMessageCount();
102         if (count > 0) {
103           log.info("Found " + count + " messages");
104         }
105         for (int i = 1; i <= count; i++) {
106           log.info("Processing message " + i);
107           Message message = inbox.getMessage(i);
108           Object content = message.getContent();
109           if (content instanceof MimeMultipart) {
110             MimeMultipart mimeContent = (MimeMultipart) content;
111             int numParts = mimeContent.getCount();
112             for (int j = 0; j < numParts; j++) {
113               MimeBodyPart part = (MimeBodyPart) mimeContent.getBodyPart(j);
114               String contentType = part.getContentType();
115               if (!contentType.startsWith("image/")) {
116                 continue;
117               }
118               BufferedImage image = ImageIO.read(part.getInputStream());
119               if (image != null) {
120                 Reader reader = new MultiFormatReader();
121                 Result result = null;
122                 try {
123                   result = reader.decode(new BufferedImageMonochromeBitmapSource(image), DecodeServlet.HINTS);
124                 } catch (ReaderException re) {
125                   log.info("Decoding FAILED");
126                 }
127
128                 Message reply = new MimeMessage(session);
129                 Address sender = message.getFrom()[0];
130                 reply.setRecipient(Message.RecipientType.TO, sender);
131                 reply.setFrom(fromAddress);
132                 if (result == null) {
133                   reply.setSubject("Decode failed");
134                   reply.setContent("Sorry, we could not decode that image.", "text/plain");
135                 } else {
136                   String text = result.getText();
137                   reply.setSubject("Decode succeeded");
138                   reply.setContent(text, "text/plain");
139                 }
140                 log.info("Sending reply");
141                 Transport.send(reply);
142               }
143             }
144           }
145           message.setFlag(Flags.Flag.DELETED, true);
146         }
147       } finally {
148         try {
149           if (inbox != null) {
150             inbox.close(true);
151           }
152           if (store != null) {
153             store.close();
154           }
155         } catch (MessagingException me) {
156           // continue
157         }
158       }
159     } catch (Throwable t) {
160       log.log(Level.WARNING, "Unexpected error", t);
161     }
162   }
163
164   public static void main(String[] args) {
165     Authenticator emailAuthenticator = new EmailAuthenticator(args[0], args[1]);
166     new DecodeEmailTask(emailAuthenticator).run();
167   }
168
169 }