File: FilterHtml.cs

package info (click to toggle)
beagle 0.2.12-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 12,204 kB
  • ctags: 16,188
  • sloc: cs: 91,628; sh: 27,627; ansic: 10,646; makefile: 2,248; xml: 15
file content (318 lines) | stat: -rw-r--r-- 9,058 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//
// FilterHtml.cs
//
// Copyright (C) 2005 Debajyoti Bera <dbera.web@gmail.com>
// Copyright (C) 2004 Novell, Inc.
//

//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//


using System;
using System.Collections;
using System.IO;
using System.Text;
using SW=System.Web;

using Beagle.Daemon;
using Beagle.Util;

using HtmlAgilityPack;

namespace Beagle.Filters {

	public class FilterHtml : Beagle.Daemon.Filter {
		// When see <b> push "b" in the stack
		// When see </b> pop from the stack
		// For good error checking, we should compare
		// current element with what was popped
		// Currently, we just pop, this might allow
		// unmatched elements to pass through
		private Stack hot_stack;
		private Stack ignore_stack;
		private bool building_text;
		private StringBuilder builder;

		// delegate types
		public delegate int AppendTextCallback (string s);
		public delegate void AddPropertyCallback (Beagle.Property p);
		public delegate void AppendSpaceCallback ();
		public delegate void HotCallback ();

		// delegates
		private new AppendTextCallback AppendText;
		private new AddPropertyCallback AddProperty;
		private new AppendSpaceCallback AppendWhiteSpace;
		private new AppendSpaceCallback AppendStructuralBreak;
		private new HotCallback HotUp;
		private new HotCallback HotDown;

		public FilterHtml (bool register_filter)
		{
			if (register_filter) {
				// 1: Add meta keyword fields as meta:key
				SetVersion (1);
				RegisterSupportedTypes ();
				SnippetMode = true;

				AppendText = new AppendTextCallback (base.AppendText);
				AddProperty = new AddPropertyCallback (base.AddProperty);
				AppendWhiteSpace = new AppendSpaceCallback (base.AppendWhiteSpace);
				AppendStructuralBreak = new AppendSpaceCallback (base.AppendStructuralBreak);
				HotUp = new HotCallback (base.HotUp);
				HotDown = new HotCallback (base.HotDown);
			}

			hot_stack = new Stack ();
			ignore_stack = new Stack ();
			building_text = false;
			builder = new StringBuilder ();
		}

		public FilterHtml () : this (true) {}

		// Safeguard against spurious stack pop ups...
		// caused by mismatched tags in bad html files
		// FIXME: If matching elements is not required
		// and if HtmlAgilityPack matches elements itself,
		// then we can just use a counter hot_stack_depth
		// instead of the hot_stack
		private void SafePop (Stack st)
		{
			if (st != null && st.Count != 0)
				st.Pop ();
		}
		
		protected bool NodeIsHot (String nodeName) 
		{
			return nodeName == "b"
				|| nodeName == "u"
				|| nodeName == "em"
				|| nodeName == "strong"
				|| nodeName == "big"
				|| nodeName == "h1"
				|| nodeName == "h2"
				|| nodeName == "h3"
				|| nodeName == "h4"
				|| nodeName == "h5"
				|| nodeName == "h6"
				|| nodeName == "i"
				|| nodeName == "th";
		}

		protected static bool NodeBreaksText (String nodeName) 
		{
			return nodeName == "td"
				|| nodeName == "a"
				|| nodeName == "div"
				|| nodeName == "option";
		}

		protected static bool NodeBreaksStructure (string nodeName)
		{
			return nodeName == "p"
				|| nodeName == "br"
				|| nodeName == "h1"
				|| nodeName == "h2"
				|| nodeName == "h3"
				|| nodeName == "h4"
				|| nodeName == "h5"
				|| nodeName == "h6";
		}
		
		protected static bool NodeIsContentFree (String nodeName) 
		{
			return nodeName == "script"
				|| nodeName == "map"
				|| nodeName == "style";
		}

		protected bool HandleNodeEvent (HtmlNode node)
		{
			switch (node.NodeType) {
				
			case HtmlNodeType.Document:
			case HtmlNodeType.Element:
				if (node.Name == "title") {
					if (node.StartTag) {
						builder.Length = 0;
						building_text = true;
					} else {
						String title = HtmlEntity.DeEntitize (builder.ToString ().Trim ());
						AddProperty (Beagle.Property.New ("dc:title", title));
						builder.Length = 0;
						building_text = false;
					}
				} else if (node.Name == "meta") {
	   				string name = node.GetAttributeValue ("name", "");
           				string content = node.GetAttributeValue ("content", "");
					if (name != "" && content != "")
						AddProperty (Beagle.Property.New ("meta:" + name, content));
				} else if (! NodeIsContentFree (node.Name)) {
					bool isHot = NodeIsHot (node.Name);
					bool breaksText = NodeBreaksText (node.Name);
					bool breaksStructure = NodeBreaksStructure (node.Name);

					if (breaksText)
						AppendWhiteSpace ();

					if (node.StartTag) {
						if (isHot) {
							if (hot_stack.Count == 0)
								HotUp ();
							hot_stack.Push (node.Name);
						}
						if (node.Name == "img") {
							string attr = node.GetAttributeValue ("alt", "");
							if (attr != "") {
								AppendText (HtmlEntity.DeEntitize (attr));
								AppendWhiteSpace ();
							}
						} else if (node.Name == "a") {
							string attr = node.GetAttributeValue ("href", "");
							if (attr != "") {
								AppendText (HtmlEntity.DeEntitize (SW.HttpUtility.UrlDecode (attr)));
								AppendWhiteSpace ();
							}
						}
					} else { // (! node.StartTag)
						if (isHot) {
							SafePop (hot_stack);
							if (hot_stack.Count == 0)
								HotDown ();
						}	
						if (breaksStructure)
							AppendStructuralBreak ();
					}

					if (breaksText)
						AppendWhiteSpace ();
				} else {
					// so node is a content-free node
					// ignore contents of such node
					if (node.StartTag)
						ignore_stack.Push (node.Name);
					else
						SafePop (ignore_stack);
				}
				break;
				
			case HtmlNodeType.Text:
				// FIXME Do we need to trim the text ?
				String text = ((HtmlTextNode)node).Text;
				if (ignore_stack.Count != 0)
					break; // still ignoring ...
				if (building_text)
					builder.Append (text);
				else
					AppendText (HtmlEntity.DeEntitize (text));
				//if (hot_stack.Count != 0)
				//Console.WriteLine (" TEXT:" + text + " ignore=" + ignore_stack.Count);
				break;
			}

			if (! AllowMoreWords ())
				return false;
			return true;
		}

		override protected void DoOpen (FileInfo info)
		{
			Encoding enc = null;

			foreach (Property prop in IndexableProperties) {
				if (prop.Key != StringFu.UnindexedNamespace + "encoding")
					continue;

				try {
					enc = Encoding.GetEncoding ((string) prop.Value);
				} catch (NotSupportedException) {
					// Encoding passed in isn't supported.  Maybe
					// we'll get lucky detecting it from the
					// document instead.
				}

				break;
			}

			if (enc == null) {
				// we need to tell the parser to detect encoding,
				HtmlDocument temp_doc = new HtmlDocument ();
				enc = temp_doc.DetectEncoding (Stream);
				//Console.WriteLine ("Detected encoding:" + (enc == null ? "null" : enc.EncodingName));
				temp_doc = null;
				Stream.Seek (0, SeekOrigin.Begin);
			}

			HtmlDocument doc = new HtmlDocument ();
			doc.ReportNode += HandleNodeEvent;
			doc.StreamMode = true;
			// we already determined encoding
			doc.OptionReadEncoding = false;
	
			try {
				if (enc == null)
					doc.Load (Stream);
				else
					doc.Load (Stream, enc);
			} catch (NotSupportedException) {
				doc.Load (Stream, Encoding.ASCII);
			} catch (Exception e) {
				Log.Debug (e, "Exception while filtering HTML file");
			}

			Finished ();
		}

		public void ExtractText (string html_string,
					 AppendTextCallback append_text_cb,
					 AddPropertyCallback add_prop_cb,
					 AppendSpaceCallback append_white_cb,
					 AppendSpaceCallback append_break_cb,
					 HotCallback hot_up_cb,
					 HotCallback hot_down_cb)
		{
			AppendText = append_text_cb;
			AddProperty = add_prop_cb;
			AppendWhiteSpace = append_white_cb;
			AppendStructuralBreak = append_break_cb;
			HotUp = hot_up_cb;
			HotDown = hot_down_cb;

			HtmlDocument doc = new HtmlDocument ();
			doc.ReportNode += HandleNodeEvent;
			doc.StreamMode = true;
	
			try {
				doc.LoadHtml (html_string);
			} catch (Exception e) {
				Log.Debug (e, "Exception while filtering html string [{0}]", html_string);
			}

		}

		virtual protected void RegisterSupportedTypes () 
		{
			AddSupportedFlavor (FilterFlavor.NewFromMimeType ("text/html"));
		}
	}

}