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.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;
56 * The KiSS crawler for automatic recording of interesting TV shows.
59 public class KissCrawler {
61 private static final Log LOG = LogFactory.getLog(KissCrawler.class);
64 * Start URL of the electronic programme guide.
66 private static final String START_URL = "http://epg.kml.kiss-technology.com/login.php";
69 * Default socket timeout to use.
71 private static final int SOCKET_TIMEOUT = 10000;
74 * Regular expression for matching time interval strings in the retrieved
77 private static final String TIME_REGEX = "[^0-9]*([0-9]{2}):([0-9]{2})[^0-9]*([0-9]{2}):([0-9]{2}).*";
80 * Compiled pattern for the time regular expression.
82 private Pattern _pattern;
85 * Runs the KiSS crawler.
88 * Arguments: First argument is the crawler configuration file,
89 * and second is the program configuration file.
91 * In case of problems.
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();
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());
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.
108 * @param aCrawlerConfig
109 * Configuration file for the crawler.
110 * @param aProgramConfig
111 * Configuration file describing interesting shows.
113 * Object used to send notifications of the results.
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.
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,
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.
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.
144 * Object used to send notifications of the results.
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.
154 public KissCrawler(String aStartUrl, int aSocketTimeout,
155 String aCrawlerConfig, String aProgramConfig, Notifier aNotifier,
156 Report aReport) throws IOException, NotificationException,
159 _pattern = Pattern.compile(TIME_REGEX);
162 HttpClient client = new HttpClient();
163 // client.getHostConfiguration().setProxy("127.0.0.1", 3128);
164 client.getParams().setParameter("http.socket.timeout",
167 XslTransformer transformer = new XslTransformer(
168 new ClasspathUriResolver());
170 Crawler crawler = createCrawler(aCrawlerConfig, client, transformer);
171 InputStream programConfigFile = new FileInputStream(new File(
173 ProgramConfigurationParser parser = new ProgramConfigurationParser();
174 parser.parse(programConfigFile);
175 List<ProgramFilter> programFilters = parser.getFilters();
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);
188 aNotifier.send(aReport.asXml());
190 System.out.println("Crawler finished");
195 * Records interesting shows.
197 * @param aProgramCondition
198 * Condition determining which shows are interesting.
201 * @throws MessagingException
202 * In case of problems sending a summary mail.
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);
219 * Creates the crawler.
221 * @param aCrawlerConfig
222 * Crawler configuration file.
224 * Logging output stream for the crawler.
226 * HTTP Client to use.
228 * @throws FileNotFoundException
229 * In case configuration files cannot be found.
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(
236 Configuration config = parser.parse(crawlerConfigFile);
237 Crawler crawler = new CrawlerImpl(aClient, config);
242 * Gets the start page of the electronic programme guide. This involves
243 * login and navigation to a suitable start page after logging in.
246 * URL of the electronic programme guide.
251 * @return Starting page.
253 private Page getStartPage(String aStartUrl, Crawler aCrawler, Report aReport)
254 throws PageException {
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);
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);
271 * Creates the TV guide by web crawling.
278 * @throws PageException
279 * In case of problem getting the tv guide.
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");
289 List<Channel> channels = new ArrayList<Channel>();
290 for (Action action : actions) {
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 '"
297 + "' does not contain required information");
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.
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);
312 return new TVGuide(channels);
316 * Create channel information for a specific channel.
321 * Starting page for the channel.
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 = "";
340 if (!SystemProperties.isNoProgramDetailsRequired()) {
341 Element descriptionElem = action.getContent().element(
343 if (descriptionElem == null) {
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);
357 description = descriptionElem.getTextTrim();
360 Program program = new Program(aChannel, action.getName(),
361 description, keywords, interval, action);
363 LOG.info("Got program " + program);
364 programs.add(program);
367 return new Channel(aChannel, programs);