2 * Copyright 2005 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.wamblee.crawler.kiss.main;
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;
29 import javax.mail.MessagingException;
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;
54 * The KiSS crawler for automatic recording of interesting TV shows.
57 public class KissCrawler {
59 private static final Log LOG = LogFactory.getLog(KissCrawler.class);
62 * Start URL of the electronic programme guide.
64 private static final String START_URL = "http://epg.kml.kiss-technology.com/login_core.php";
67 * Default socket timeout to use.
69 private static final int SOCKET_TIMEOUT = 10000;
72 * Regular expression for matching time interval strings in the retrieved
75 private static final String TIME_REGEX = "([0-9]{2}):([0-9]{2})[^0-9]*([0-9]{2}):([0-9]{2}).*";
78 * Compiled pattern for the time regular expression.
80 private Pattern _pattern;
83 * Runs the KiSS crawler.
86 * Arguments, currently all ignored because they are hardcoded.
88 * In case of problems.
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();
94 BeanFactory factory = new StandaloneCrawlerBeanFactory();
95 Notifier notifier = factory.find(Notifier.class);
96 new KissCrawler(START_URL, SOCKET_TIMEOUT, crawlerConfig, programConfig, notifier, new Report());
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.
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.
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);
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.
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.
140 public KissCrawler(String aStartUrl, int aSocketTimeout, String aCrawlerConfig,
141 String aProgramConfig, Notifier aNotifier, Report aReport) throws IOException, NotificationException, PageException {
143 _pattern = Pattern.compile(TIME_REGEX);
146 HttpClient client = new HttpClient();
147 // client.getHostConfiguration().setProxy("127.0.0.1", 3128);
148 client.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT);
150 XslTransformer transformer = new XslTransformer(
151 new ClasspathUriResolver());
153 Crawler crawler = createCrawler(aCrawlerConfig, client, transformer);
154 InputStream programConfigFile = new FileInputStream(new File(
156 ProgramConfigurationParser parser = new ProgramConfigurationParser(
158 parser.parse(programConfigFile);
159 List<ProgramFilter> programFilters = parser.getFilters();
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,
168 } catch (PageException e) {
169 aReport.addMessage("Problem getting TV guide", e);
170 LOG.info("Problem getting TV guide", e);
173 aNotifier.send(aReport.asXml());
175 System.out.println("Crawler finished");
180 * Records interesting shows.
182 * @param aProgramCondition
183 * Condition determining which shows are interesting.
186 * @throws MessagingException
187 * In case of problems sending a summary mail.
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);
204 * Creates the crawler.
206 * @param aCrawlerConfig
207 * Crawler configuration file.
209 * Logging output stream for the crawler.
211 * HTTP Client to use.
213 * @throws FileNotFoundException
214 * In case configuration files cannot be found.
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(
221 Configuration config = parser.parse(crawlerConfigFile);
222 Crawler crawler = new CrawlerImpl(aClient, config);
227 * Gets the start page of the electronic programme guide. This involves
228 * login and navigation to a suitable start page after logging in.
231 * URL of the electronic programme guide.
236 * @return Starting page.
238 private Page getStartPage(String aStartUrl, Crawler aCrawler, Report aReport)
239 throws PageException {
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);
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);
255 * Creates the TV guide by web crawling.
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");
270 List<Channel> channels = new ArrayList<Channel>();
271 for (Action action : actions) {
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 '"
278 + "' does not contain required information");
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.
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);
293 return new TVGuide(channels);
297 * Create channel information for a specific channel.
302 * Starting page for the channel.
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()) {
322 Page programInfo = action.execute();
323 description = programInfo.getContent().element(
324 "description").getText().trim();
325 keywords = programInfo.getContent().element("keywords")
327 } catch (PageException e) {
328 String msg = "Program details could not be determined for '"
329 + action.getName() + "'";
330 aReport.addMessage(msg, e);
334 Program program = new Program(aChannel, action.getName(),
335 description, keywords, interval, action);
337 LOG.info("Got program " + program);
338 programs.add(program);
341 return new Channel(aChannel, programs);