(no commit message)
[utils] / crawler / kiss / src / org / wamblee / crawler / kiss / KissCrawler.java
1 /*
2  * Copyright 2005 the original author or authors.
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 org.wamblee.crawler.kiss;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileNotFoundException;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.PrintStream;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Date;
30 import java.util.List;
31 import java.util.Properties;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import javax.mail.Message;
36 import javax.mail.MessagingException;
37 import javax.mail.Session;
38 import javax.mail.Transport;
39 import javax.mail.internet.InternetAddress;
40 import javax.mail.internet.MimeMessage;
41 import javax.xml.transform.TransformerException;
42
43 import org.apache.commons.httpclient.HttpClient;
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46 import org.apache.commons.mail.EmailException;
47 import org.apache.commons.mail.HtmlEmail;
48 import org.apache.xml.serialize.OutputFormat;
49 import org.apache.xml.serialize.XMLSerializer;
50 import org.w3c.dom.Document;
51 import org.wamblee.crawler.Action;
52 import org.wamblee.crawler.Configuration;
53 import org.wamblee.crawler.Crawler;
54 import org.wamblee.crawler.Page;
55 import org.wamblee.crawler.PageException;
56 import org.wamblee.crawler.impl.ConfigurationParser;
57 import org.wamblee.crawler.impl.CrawlerImpl;
58 import org.wamblee.io.FileResource;
59 import org.wamblee.xml.XSLT;
60
61 /**
62  * The KiSS crawler for automatic recording of interesting TV shows.
63  * 
64  */
65 public class KissCrawler {
66
67     private static final Log LOG = LogFactory.getLog(KissCrawler.class);
68
69     /**
70      * Log file name for the crawler.
71      */
72     private static final String LOG_FILE = "kiss.log";
73
74     /**
75      * Start URL of the electronic programme guide.
76      */
77     private static final String START_URL = "http://epg.kml.kiss-technology.com/login_core.php";
78
79     /**
80      * Crawler configuration file.
81      */
82     private static final String CRAWLER_CONFIG = "config.xml";
83
84     /**
85      * Configuration file describing interesting programs.
86      */
87     private static final String PROGRAM_CONFIG = "programs.xml";
88
89     /**
90      * Regular expression for matching time interval strings in the retrieved
91      * pages.
92      */
93     private static final String TIME_REGEX = "([0-9]{2}):([0-9]{2})[^0-9]*([0-9]{2}):([0-9]{2}).*";
94
95     /**
96      * Compiled pattern for the time regular expression.
97      */
98     private Pattern _pattern;
99
100     /**
101      * Runs the KiSS crawler.
102      * 
103      * @param aArgs
104      *            Arguments, currently all ignored because they are hardcoded.
105      * @throws Exception
106      *             In case of problems.
107      */
108     public static void main(String[] aArgs) throws Exception {
109         new KissCrawler(START_URL, CRAWLER_CONFIG, PROGRAM_CONFIG);
110     }
111
112     /**
113      * Constructs the crawler. This retrieves the TV guide by crawling the KiSS
114      * EPG guide, filters the guide for interesting programs, tries to record
115      * them, and sends a summary mail to the user.
116      * 
117      * @param aStartUrl
118      *            Start URL of the electronic programme guide.
119      * @param aCrawlerConfig
120      *            Configuration file for the crawler.
121      * @param aProgramConfig
122      *            Configuration file describing interesting shows.
123      * @throws IOException
124      *             In case of problems reading files.
125      * @throws MessagingException
126      *             In case of problems sending a mail notification.
127      */
128     public KissCrawler(String aStartUrl, String aCrawlerConfig,
129             String aProgramConfig) throws IOException, MessagingException {
130
131         _pattern = Pattern.compile(TIME_REGEX);
132
133         FileOutputStream fos = new FileOutputStream(new File(LOG_FILE));
134         PrintStream os = new PrintStream(fos);
135
136         try {
137             HttpClient client = new HttpClient();
138             // client.getHostConfiguration().setProxy("127.0.0.1", 3128);
139
140             Crawler crawler = createCrawler(aCrawlerConfig, os, client);
141             InputStream programConfigFile = new FileInputStream(new File(
142                     aProgramConfig));
143             List<ProgramFilter> programFilters = new ProgramConfigurationParser()
144                     .parse(programConfigFile);
145
146             Page page = getStartPage(aStartUrl, crawler);
147             TVGuide guide = createGuide(page);
148             PrintVisitor printer = new PrintVisitor(System.out);
149             guide.accept(printer);
150             processResults(programFilters, guide);
151         } finally {
152             os.flush();
153             os.close();
154             System.out.println("Output written on '" + LOG_FILE + "'");
155         }
156     }
157
158     /**
159      * Records interesting shows.
160      * 
161      * @param aProgramCondition
162      *            Condition determining which shows are interesting.
163      * @param aGuide
164      *            Television guide.
165      * @throws MessagingException
166      *             In case of problems sending a summary mail.
167      */
168     private void processResults(List<ProgramFilter> aProgramCondition,
169             TVGuide aGuide) throws MessagingException {
170         ProgramActionExecutor executor = new ProgramActionExecutor();
171         for (ProgramFilter filter : aProgramCondition) {
172             List<Program> programs = filter.apply(aGuide);
173             ProgramAction action = filter.getAction();
174             for (Program program : programs) {
175                 action.execute(program, executor);
176             }
177         }
178         executor.commit();
179         sendMail(executor);
180     }
181
182     /**
183      * Creates the crawler.
184      * 
185      * @param aCrawlerConfig
186      *            Crawler configuration file.
187      * @param aOs
188      *            Logging output stream for the crawler.
189      * @param aClient
190      *            HTTP Client to use.
191      * @return Crawler.
192      * @throws FileNotFoundException
193      *             In case configuration files cannot be found.
194      */
195     private Crawler createCrawler(String aCrawlerConfig, PrintStream aOs,
196             HttpClient aClient) throws FileNotFoundException {
197         ConfigurationParser parser = new ConfigurationParser(aOs);
198         InputStream crawlerConfigFile = new FileInputStream(new File(
199                 aCrawlerConfig));
200         Configuration config = parser.parse(crawlerConfigFile);
201         Crawler crawler = new CrawlerImpl(aClient, config);
202         return crawler;
203     }
204
205     /**
206      * Gets the start page of the electronic programme guide. This involves
207      * login and navigation to a suitable start page after logging in.
208      * 
209      * @param aStartUrl
210      *            URL of the electronic programme guide.
211      * @param aCrawler
212      *            Crawler to use.
213      * @return Starting page.
214      */
215     private Page getStartPage(String aStartUrl, Crawler aCrawler) {
216         try {
217             Page page = aCrawler.getPage(aStartUrl);
218             return page.getAction("channels-favorites").execute();
219         } catch (PageException e) {
220             throw new RuntimeException(
221                     "Could not login to electronic program guide", e);
222         }
223     }
224
225     /**
226      * Creates the TV guide by web crawling.
227      * 
228      * @param aPage
229      *            Starting page.
230      * @return TV guide.
231      */
232     private TVGuide createGuide(Page aPage) {
233         LOG.info("Obtaining full TV guide");
234         Action[] actions = aPage.getActions();
235         List<Channel> channels = new ArrayList<Channel>();
236         for (Action action : actions) {
237             try {
238                 LOG.info("Getting channel info for '" + action.getName() + "'");
239                 Channel channel = createChannel(action.getName(), action
240                         .execute().getAction("right-now").execute());
241                 channels.add(channel);
242                 if (SystemProperties.isDebugMode()) {
243                     break; // Only one channel is crawled.
244                 }
245             } catch (PageException e) {
246                 LOG.error("Could not create channel information for '"
247                         + action.getName() + "'", e);
248             }
249         }
250         return new TVGuide(channels);
251     }
252
253     /**
254      * Create channel information for a specific channel.
255      * 
256      * @param aChannel
257      *            Channel name.
258      * @param aPage
259      *            Starting page for the channel.
260      * @return Channel.
261      */
262     private Channel createChannel(String aChannel, Page aPage) {
263         LOG.info("Obtaining program for " + aChannel);
264         Action[] programActions = aPage.getActions();
265         List<Program> programs = new ArrayList<Program>();
266         for (Action action : programActions) {
267             String time = action.getContent().element("time").getText().trim();
268             Matcher matcher = _pattern.matcher(time);
269             if (matcher.matches()) {
270                 Time begin = new Time(Integer.parseInt(matcher.group(1)),
271                         Integer.parseInt(matcher.group(2)));
272                 Time end = new Time(Integer.parseInt(matcher.group(3)), Integer
273                         .parseInt(matcher.group(4)));
274                 TimeInterval interval = new TimeInterval(begin, end);
275                 String description = "";
276                 String keywords = "";
277                 if (!SystemProperties.isNoProgramDetailsRequired()) {
278                     try {
279                         Page programInfo = action.execute();
280                         description = programInfo.getContent().element(
281                                 "description").getText().trim();
282                         keywords = programInfo.getContent().element("keywords")
283                                 .getText().trim();
284                     } catch (PageException e) {
285                         LOG.warn(
286                                 "Program details could not be determined for '"
287                                         + action.getName() + "'", e);
288                     }
289                 }
290                 Program program = new Program(aChannel, action.getName(),
291                         description, keywords, interval, action);
292
293                 LOG.info("Got program " + program);
294                 programs.add(program);
295             }
296         }
297         return new Channel(aChannel, programs);
298     }
299
300     /**
301      * Sends a summary mail to the user.
302      * 
303      * @param aText
304      *            Text of the mail.
305      * @throws MessagingException
306      *             In case of problems sending mail.
307      */
308     private void sendMail(ProgramActionExecutor aExecutor) throws MessagingException {
309         String textReport = aExecutor.getReport();
310         System.out.println("Text report: \n" + textReport);
311         System.out.println("XML report:\n" + aExecutor.getXmlReport().asXML());
312         
313         
314         Properties props = new Properties();
315         props.put("mail.transport.protocol", "smtp");
316         props.put("mail.smtp.host", "falcon");
317         props.put("mail.smtp.port", "25");
318
319         Session mailSession = Session.getInstance(props);
320         InternetAddress from = new InternetAddress("erik@brakkee.org");
321     
322         HtmlEmail mail = new HtmlEmail();
323         mail.setMailSession(mailSession);
324         try {
325             mail.setFrom("erik@brakkee.org");
326             mail.setTo(Arrays.asList(new InternetAddress[] { from }));
327             mail.setSentDate(new Date());
328             mail.setSubject("KiSS Crawler Update");
329             String html = aExecutor.getXmlReport().asXML(); 
330             Document document = new XSLT().transform(html.getBytes(), new FileResource(new File("reportToHtml.xsl")));
331             ByteArrayOutputStream xhtml = new ByteArrayOutputStream();
332             XMLSerializer serializer = new XMLSerializer(xhtml, new OutputFormat());
333             serializer.serialize(document);
334             mail.setHtmlMsg(xhtml.toString());
335             mail.setTextMsg(textReport);
336             mail.send();
337         } catch (EmailException e) {
338             throw new RuntimeException(e);
339         } catch (TransformerException e) { 
340             throw new RuntimeException(e);
341         } catch (IOException e) { 
342             throw new RuntimeException(e);
343         }
344     }
345
346 }