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