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;
20 import java.io.FileInputStream;
21 import java.io.FileNotFoundException;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.PrintStream;
26 import java.util.ArrayList;
27 import java.util.Date;
28 import java.util.EnumMap;
29 import java.util.List;
30 import java.util.Properties;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import javax.mail.Message;
35 import javax.mail.MessagingException;
36 import javax.mail.Session;
37 import javax.mail.Transport;
38 import javax.mail.internet.InternetAddress;
39 import javax.mail.internet.MimeMessage;
41 import org.apache.commons.httpclient.HttpClient;
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44 import org.wamblee.conditions.Condition;
45 import org.wamblee.crawler.Action;
46 import org.wamblee.crawler.Configuration;
47 import org.wamblee.crawler.Crawler;
48 import org.wamblee.crawler.Page;
49 import org.wamblee.crawler.PageException;
50 import org.wamblee.crawler.impl.ConfigurationParser;
51 import org.wamblee.crawler.impl.CrawlerImpl;
52 import org.wamblee.crawler.kiss.Program.RecordingResult;
55 * The KiSS crawler for automatic recording of interesting TV shows.
58 public class KissCrawler {
60 private static final Log LOG = LogFactory.getLog(KissCrawler.class);
63 * Log file name for the crawler.
65 private static final String LOG_FILE = "kiss.log";
68 * Start URL of the electronic programme guide.
70 private static final String START_URL = "http://epg.kml.kiss-technology.com/login_core.php";
73 * Crawler configuration file.
75 private static final String CRAWLER_CONFIG = "config.xml";
78 * Configuration file describing interesting programs.
80 private static final String PROGRAM_CONFIG = "programs.xml";
83 * Regular expression for matching time interval strings in the retrieved
86 private static final String TIME_REGEX = "([0-9]{2}):([0-9]{2})[^0-9]*([0-9]{2}):([0-9]{2}).*";
89 * Compiled pattern for the time regular expression.
91 private Pattern _pattern;
94 * Runs the KiSS crawler.
97 * Arguments, currently all ignored because they are hardcoded.
99 * In case of problems.
101 public static void main(String[] aArgs) throws Exception {
102 new KissCrawler(START_URL, CRAWLER_CONFIG, PROGRAM_CONFIG);
106 * Constructs the crawler. This retrieves the TV guide by crawling the KiSS
107 * EPG guide, filters the guide for interesting programs, tries to record
108 * them, and sends a summary mail to the user.
111 * Start URL of the electronic programme guide.
112 * @param aCrawlerConfig
113 * Configuration file for the crawler.
114 * @param aProgramConfig
115 * Configuration file describing interesting shows.
116 * @throws IOException
117 * In case of problems reading files.
118 * @throws MessagingException
119 * In case of problems sending a mail notification.
121 public KissCrawler(String aStartUrl, String aCrawlerConfig,
122 String aProgramConfig) throws IOException, MessagingException {
124 _pattern = Pattern.compile(TIME_REGEX);
126 FileOutputStream fos = new FileOutputStream(new File(LOG_FILE));
127 PrintStream os = new PrintStream(fos);
130 HttpClient client = new HttpClient();
131 // client.getHostConfiguration().setProxy("127.0.0.1", 3128);
133 Crawler crawler = createCrawler(aCrawlerConfig, os, client);
135 Page page = getStartPage(aStartUrl, crawler);
136 TVGuide guide = createGuide(page);
137 PrintVisitor printer = new PrintVisitor(System.out);
138 guide.accept(printer);
140 InputStream programConfigFile = new FileInputStream(new File(
142 Condition<Program> programCondition = new ProgramConfigurationParser()
143 .parse(programConfigFile);
144 recordInterestingShows(programCondition, guide);
148 System.out.println("Output written on '" + LOG_FILE + "'");
153 * Records interesting shows.
155 * @param aProgramCondition
156 * Condition determining which shows are interesting.
159 * @throws MessagingException
160 * In case of problems sending a summary mail.
162 private void recordInterestingShows(Condition<Program> aProgramCondition,
163 TVGuide aGuide) throws MessagingException {
164 MatchVisitor matcher = new MatchVisitor(aProgramCondition);
165 aGuide.accept(matcher);
166 List<Program> programs = matcher.getMatches();
167 EnumMap<RecordingResult, List<Program>> messages = new EnumMap<RecordingResult, List<Program>>(
168 RecordingResult.class);
169 for (RecordingResult result : RecordingResult.values()) {
170 messages.put(result, new ArrayList<Program>());
172 for (Program program : programs) {
173 Program.RecordingResult result = program.record();
174 messages.get(result).add(program);
176 String msg = "Summary of KiSS crawler: \n\n\n";
178 for (RecordingResult result : RecordingResult.values()) {
179 if (messages.get(result).size() > 0) {
180 msg += result.getDescription() + "\n\n";
181 for (Program program : messages.get(result)) {
182 msg += program + "\n";
186 if (programs.size() == 0) {
187 msg += "No suitable programs found";
190 System.out.println(msg);
195 * Creates the crawler.
197 * @param aCrawlerConfig
198 * Crawler configuration file.
200 * Logging output stream for the crawler.
202 * HTTP Client to use.
204 * @throws FileNotFoundException
205 * In case configuration files cannot be found.
207 private Crawler createCrawler(String aCrawlerConfig, PrintStream aOs,
208 HttpClient aClient) throws FileNotFoundException {
209 ConfigurationParser parser = new ConfigurationParser(aOs);
210 InputStream crawlerConfigFile = new FileInputStream(new File(
212 Configuration config = parser.parse(crawlerConfigFile);
213 Crawler crawler = new CrawlerImpl(aClient, config);
218 * Gets the start page of the electronic programme guide. This involves
219 * login and navigation to a suitable start page after logging in.
222 * URL of the electronic programme guide.
225 * @return Starting page.
227 private Page getStartPage(String aStartUrl, Crawler aCrawler) {
229 Page page = aCrawler.getPage(aStartUrl);
230 return page.getAction("channels-favorites").execute();
231 } catch (PageException e) {
232 throw new RuntimeException(
233 "Could not login to electronic program guide", e);
238 * Creates the TV guide by web crawling.
244 private TVGuide createGuide(Page aPage) {
245 LOG.info("Obtaining full TV guide");
246 Action[] actions = aPage.getActions();
247 List<Channel> channels = new ArrayList<Channel>();
248 for (Action action : actions) {
250 LOG.info("Getting channel info for '" + action.getName() + "'");
251 Channel channel = createChannel(action.getName(), action
252 .execute().getAction("right-now").execute());
253 channels.add(channel);
254 if (SystemProperties.isDebugMode()) {
255 break; // Only one channel is crawled.
257 } catch (PageException e) {
258 LOG.error("Could not create channel information for '"
259 + action.getName() + "'", e);
262 return new TVGuide(channels);
266 * Create channel information for a specific channel.
271 * Starting page for the channel.
274 private Channel createChannel(String aChannel, Page aPage) {
275 LOG.info("Obtaining program for " + aChannel);
276 Action[] programActions = aPage.getActions();
277 List<Program> programs = new ArrayList<Program>();
278 for (Action action : programActions) {
279 String time = action.getContent().element("time").getText().trim();
280 Matcher matcher = _pattern.matcher(time);
281 if (matcher.matches()) {
282 Time begin = new Time(Integer.parseInt(matcher.group(1)),
283 Integer.parseInt(matcher.group(2)));
284 Time end = new Time(Integer.parseInt(matcher.group(3)), Integer
285 .parseInt(matcher.group(4)));
286 TimeInterval interval = new TimeInterval(begin, end);
287 String description = "";
288 String keywords = "";
289 if (!SystemProperties.isNoProgramDetailsRequired()) {
291 Page programInfo = action.execute();
292 description = programInfo.getContent().element(
293 "description").getText().trim();
294 keywords = programInfo.getContent().element("keywords")
296 } catch (PageException e) {
298 .warn("Program details coul dnot be determined for '"
299 + action.getName() + "'");
302 Program program = new Program(aChannel, action.getName(),
303 description, keywords, interval, action);
305 LOG.debug("Got program " + program);
306 programs.add(program);
309 return new Channel(aChannel, programs);
313 * Sends a summary mail to the user.
317 * @throws MessagingException
318 * In case of problems sending mail.
320 private void sendMail(String aText) throws MessagingException {
321 Properties props = new Properties();
322 props.put("mail.transport.protocol", "smtp");
323 props.put("mail.smtp.host", "falcon");
324 props.put("mail.smtp.port", "25");
326 Session mailSession = Session.getInstance(props);
327 Message message = new MimeMessage(mailSession);
329 message.setFrom(new InternetAddress("erik@brakkee.org"));
330 message.setRecipient(Message.RecipientType.TO, new InternetAddress(
331 "erik@brakkee.org"));
332 message.setSentDate(new Date());
333 message.setSubject("KiSS crawler update");
334 message.setText(aText);
335 Transport.send(message);