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