c637f34cdfe266f910c5d676c062746826276c95
[utils] / crawler / kiss / src / main / java / org / wamblee / crawler / kiss / main / 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.main;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileNotFoundException;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import javax.mail.MessagingException;
30
31 import org.apache.commons.httpclient.HttpClient;
32 import org.apache.commons.httpclient.NameValuePair;
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.dom4j.Element;
36 import org.wamblee.crawler.Action;
37 import org.wamblee.crawler.Configuration;
38 import org.wamblee.crawler.Crawler;
39 import org.wamblee.crawler.Page;
40 import org.wamblee.crawler.PageException;
41 import org.wamblee.crawler.impl.ConfigurationParser;
42 import org.wamblee.crawler.impl.CrawlerImpl;
43 import org.wamblee.crawler.kiss.guide.Channel;
44 import org.wamblee.crawler.kiss.guide.PrintVisitor;
45 import org.wamblee.crawler.kiss.guide.Program;
46 import org.wamblee.crawler.kiss.guide.TVGuide;
47 import org.wamblee.crawler.kiss.guide.Time;
48 import org.wamblee.crawler.kiss.guide.TimeInterval;
49 import org.wamblee.crawler.kiss.notification.NotificationException;
50 import org.wamblee.crawler.kiss.notification.Notifier;
51 import org.wamblee.general.BeanFactory;
52 import org.wamblee.xml.ClasspathUriResolver;
53 import org.wamblee.xml.XslTransformer;
54
55 /**
56  * The KiSS crawler for automatic recording of interesting TV shows.
57  * 
58  */
59 public class KissCrawler {
60
61     private static final Log LOG = LogFactory.getLog(KissCrawler.class);
62
63     /**
64      * Start URL of the electronic programme guide.
65      */
66     private static final String START_URL = "http://epg.kml.kiss-technology.com/login.php";
67
68     /**
69      * Default socket timeout to use.
70      */
71     private static final int SOCKET_TIMEOUT = 10000;
72
73     /**
74      * Regular expression for matching time interval strings in the retrieved
75      * pages.
76      */
77     private static final String TIME_REGEX = "[^0-9]*([0-9]{2}):([0-9]{2})[^0-9]*([0-9]{2}):([0-9]{2}).*";
78
79     /**
80      * Compiled pattern for the time regular expression.
81      */
82     private Pattern _pattern;
83
84     /**
85      * Runs the KiSS crawler.
86      * 
87      * @param aArgs
88      *            Arguments: First argument is the crawler configuration file,
89      *            and second is the program configuration file. 
90      * @throws Exception
91      *             In case of problems.
92      */
93     public static void main(String[] aArgs) throws Exception {
94         String crawlerConfig = new File(aArgs[0]).getCanonicalPath();
95         String programConfig = new File(aArgs[1]).getCanonicalPath();
96
97         BeanFactory factory = new StandaloneCrawlerBeanFactory();
98         Notifier notifier = factory.find(Notifier.class);
99         new KissCrawler(START_URL, SOCKET_TIMEOUT, crawlerConfig,
100                 programConfig, notifier, new Report());
101     }
102
103     /**
104      * Constructs the crawler. This retrieves the TV guide by crawling the KiSS
105      * EPG guide, filters the guide for interesting programs, tries to record
106      * them, and sends a summary mail to the user.
107      * 
108      * @param aCrawlerConfig
109      *            Configuration file for the crawler.
110      * @param aProgramConfig
111      *            Configuration file describing interesting shows.
112      * @param aNotifier
113      *            Object used to send notifications of the results.
114      * @param aReport
115      *            Report to use.
116      * @throws IOException
117      *             In case of problems reading files.
118      * @throws NotificationException
119      *             In case notification fails.
120      * @throws PageException
121      *             In case of problems retrieving the TV guide.
122      */
123     public KissCrawler(String aCrawlerConfig, String aProgramConfig,
124             Notifier aNotifier, Report aReport) throws IOException,
125             NotificationException, PageException {
126         this(START_URL, SOCKET_TIMEOUT, aCrawlerConfig, aProgramConfig,
127                 aNotifier, aReport);
128     }
129
130     /**
131      * Constructs the crawler. This retrieves the TV guide by crawling the KiSS
132      * EPG guide, filters the guide for interesting programs, tries to record
133      * them, and sends a summary mail to the user.
134      * 
135      * @param aStartUrl
136      *            Start URL of the electronic programme guide.
137      * @param aSocketTimeout
138      *            Socket timeout to use.
139      * @param aCrawlerConfig
140      *            Configuration file for the crawler.
141      * @param aProgramConfig
142      *            Configuration file describing interesting shows.
143      * @param aNotifier
144      *            Object used to send notifications of the results.
145      * @param aReport
146      *            Report to use.
147      * @throws IOException
148      *             In case of problems reading files.
149      * @throws NotificationException
150      *             In case notification fails.
151      * @throws PageException
152      *             In case of problems retrieving the TV guide.
153      */
154     public KissCrawler(String aStartUrl, int aSocketTimeout,
155             String aCrawlerConfig, String aProgramConfig, Notifier aNotifier,
156             Report aReport) throws IOException, NotificationException,
157             PageException {
158
159         _pattern = Pattern.compile(TIME_REGEX);
160
161         try {
162             HttpClient client = new HttpClient();
163             // client.getHostConfiguration().setProxy("127.0.0.1", 3128);
164             client.getParams().setParameter("http.socket.timeout",
165                     SOCKET_TIMEOUT);
166
167             XslTransformer transformer = new XslTransformer(
168                     new ClasspathUriResolver());
169
170             Crawler crawler = createCrawler(aCrawlerConfig, client, transformer);
171             InputStream programConfigFile = new FileInputStream(new File(
172                     aProgramConfig));
173             ProgramConfigurationParser parser = new ProgramConfigurationParser();
174             parser.parse(programConfigFile);
175             List<ProgramFilter> programFilters = parser.getFilters();
176
177             try {
178                 Page page = getStartPage(aStartUrl, crawler, aReport);
179                 TVGuide guide = createGuide(page, aReport);
180                 PrintVisitor printer = new PrintVisitor(System.out);
181                 guide.accept(printer);
182                 processResults(programFilters, guide, aNotifier, aReport);
183             } catch (PageException e) {
184                 aReport.addMessage("Problem getting TV guide", e);
185                 LOG.info("Problem getting TV guide", e);
186                 throw e;
187             }
188             aNotifier.send(aReport.asXml());
189         } finally {
190             System.out.println("Crawler finished");
191         }
192     }
193
194     /**
195      * Records interesting shows.
196      * 
197      * @param aProgramCondition
198      *            Condition determining which shows are interesting.
199      * @param aGuide
200      *            Television guide.
201      * @throws MessagingException
202      *             In case of problems sending a summary mail.
203      */
204     private void processResults(List<ProgramFilter> aProgramCondition,
205             TVGuide aGuide, Notifier aNotifier, Report aReport) {
206         ProgramActionExecutor executor = new ProgramActionExecutor(aReport);
207         for (ProgramFilter filter : aProgramCondition) {
208             List<Program> programs = filter.apply(aGuide);
209             ProgramAction action = filter.getAction();
210             for (Program program : programs) {
211                 action.execute(program, executor);
212             }
213         }
214         executor.commit();
215
216     }
217
218     /**
219      * Creates the crawler.
220      * 
221      * @param aCrawlerConfig
222      *            Crawler configuration file.
223      * @param aOs
224      *            Logging output stream for the crawler.
225      * @param aClient
226      *            HTTP Client to use.
227      * @return Crawler.
228      * @throws FileNotFoundException
229      *             In case configuration files cannot be found.
230      */
231     private Crawler createCrawler(String aCrawlerConfig, HttpClient aClient,
232             XslTransformer aTransformer) throws FileNotFoundException {
233         ConfigurationParser parser = new ConfigurationParser(aTransformer);
234         InputStream crawlerConfigFile = new FileInputStream(new File(
235                 aCrawlerConfig));
236         Configuration config = parser.parse(crawlerConfigFile);
237         Crawler crawler = new CrawlerImpl(aClient, config);
238         return crawler;
239     }
240
241     /**
242      * Gets the start page of the electronic programme guide. This involves
243      * login and navigation to a suitable start page after logging in.
244      * 
245      * @param aStartUrl
246      *            URL of the electronic programme guide.
247      * @param aCrawler
248      *            Crawler to use.
249      * @param aReport
250      *            Report to use.
251      * @return Starting page.
252      */
253     private Page getStartPage(String aStartUrl, Crawler aCrawler, Report aReport)
254             throws PageException {
255         try {
256             Page page = aCrawler.getPage(aStartUrl, new NameValuePair[0]);
257             page = page.getAction("login").execute();
258             Action favorites = page.getAction("channels-favorites");
259             if (favorites == null) {
260                 String msg = "Channels favorites action not found on start page";
261                 throw new PageException(msg);
262             }
263             return favorites.execute();
264         } catch (PageException e) {
265             String msg = "Could not complete login to electronic programme guide.";
266             throw new PageException(msg, e);
267         }
268     }
269
270     /**
271      * Creates the TV guide by web crawling.
272      * 
273      * @param aPage
274      *            Starting page.
275      * @param aReport
276      *            Report to use.
277      * @return TV guide.
278      * @throws PageException
279      *             In case of problem getting the tv guide.
280      */
281     private TVGuide createGuide(Page aPage, Report aReport)
282             throws PageException {
283         LOG.info("Obtaining full TV guide");
284         Action[] actions = aPage.getActions();
285         if (actions.length == 0) {
286             LOG.error("No channels found");
287             throw new PageException("No channels found");
288         }
289         List<Channel> channels = new ArrayList<Channel>();
290         for (Action action : actions) {
291             try {
292                 LOG.info("Getting channel info for '" + action.getName() + "'");
293                 Action tomorrow = action.execute().getAction("tomorrow");
294                 if (tomorrow == null) {
295                     throw new PageException("Channel summary page for '"
296                             + action.getName()
297                             + "' does not contain required information");
298                 }
299                 Channel channel = createChannel(action.getName(), tomorrow
300                         .execute(), aReport);
301                 channels.add(channel);
302                 if (SystemProperties.isDebugMode()) {
303                     break; // Only one channel is crawled.
304                 }
305             } catch (PageException e) {
306                 aReport.addMessage("Could not create channel information for '"
307                         + action.getName() + "'");
308                 LOG.error("Could not create channel information for '"
309                         + action.getName() + "'", e);
310             }
311         }
312         return new TVGuide(channels);
313     }
314
315     /**
316      * Create channel information for a specific channel.
317      * 
318      * @param aChannel
319      *            Channel name.
320      * @param aPage
321      *            Starting page for the channel.
322      * @return Channel.
323      */
324     private Channel createChannel(String aChannel, Page aPage, Report aReport) {
325         LOG.info("Obtaining program for " + aChannel);
326         Action[] programActions = aPage.getActions();
327         List<Program> programs = new ArrayList<Program>();
328         for (Action action : programActions) {
329             String time = action.getContent().element("time").getText().trim();
330             Matcher matcher = _pattern.matcher(time);
331             if (matcher.matches()) {
332                 Time begin = new Time(Integer.parseInt(matcher.group(1)),
333                         Integer.parseInt(matcher.group(2)));
334                 Time end = new Time(Integer.parseInt(matcher.group(3)), Integer
335                         .parseInt(matcher.group(4)));
336                 TimeInterval interval = new TimeInterval(begin, end);
337                 String description = "";
338                 String keywords = "";
339
340                 if (!SystemProperties.isNoProgramDetailsRequired()) {
341                     Element descriptionElem = action.getContent().element(
342                             "description");
343                     if (descriptionElem == null) {
344                         try {
345                             Page programInfo = action.execute();
346                             description = programInfo.getContent().element(
347                                     "description").getText().trim();
348                             keywords = programInfo.getContent().element(
349                                     "keywords").getText().trim();
350                         } catch (PageException e) {
351                             String msg = "Program details could not be determined for '"
352                                     + action.getName() + "'";
353                             aReport.addMessage(msg, e);
354                             LOG.warn(msg, e);
355                         }
356                     } else {
357                         description = descriptionElem.getTextTrim();
358                     }
359                 }
360                 Program program = new Program(aChannel, action.getName(),
361                         description, keywords, interval, action);
362
363                 LOG.info("Got program " + program);
364                 programs.add(program);
365             }
366         }
367         return new Channel(aChannel, programs);
368     }
369 }