4 // Copyright (C) 2004 Novell, Inc.
8 // Permission is hereby granted, free of charge, to any person obtaining a
9 // copy of this software and associated documentation files (the "Software"),
10 // to deal in the Software without restriction, including without limitation
11 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 // and/or sell copies of the Software, and to permit persons to whom the
13 // Software is furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 // DEALINGS IN THE SOFTWARE.
28 using System
.Collections
;
30 using System
.Reflection
;
33 using System
.Xml
.Serialization
;
37 namespace Beagle
.Daemon
{
39 public class FilterFactory
{
41 static private bool Debug
= false;
43 static FilterFactory ()
45 ReflectionFu
.ScanEnvironmentForAssemblies ("BEAGLE_FILTER_PATH", PathFinder
.FilterDir
,
46 delegate (Assembly a
) {
47 int n
= ScanAssemblyForFilters (a
);
48 Logger
.Log
.Debug ("Loaded {0} filter{1} from {2}",
49 n
, n
== 1 ? "" : "s", a
.Location
);
53 /////////////////////////////////////////////////////////////////////////
56 static private ICollection
CreateFilters (Uri uri
, string extension
, string mime_type
)
58 Hashtable matched_filters_by_flavor
= FilterFlavor
.NewHashtable ();
60 foreach (FilterFlavor flavor
in filter_types_by_flavor
.Keys
) {
61 if (flavor
.IsMatch (uri
, extension
, mime_type
)) {
62 Filter matched_filter
= null;
65 matched_filter
= (Filter
) Activator
.CreateInstance ((Type
) filter_types_by_flavor
[flavor
]);
67 if (flavor
.MimeType
!= null)
68 matched_filter
.MimeType
= flavor
.MimeType
;
69 if (flavor
.Extension
!= null)
70 matched_filter
.Extension
= flavor
.Extension
;
72 } catch (Exception e
) {
75 matched_filters_by_flavor
[flavor
] = matched_filter
;
79 foreach (DictionaryEntry entry
in matched_filters_by_flavor
) {
80 FilterFlavor flav
= (FilterFlavor
) entry
.Key
;
81 Filter filter
= (Filter
) entry
.Value
;
84 Logger
.Log
.Debug ("Found matching filter: {0}, Weight: {1}", filter
, flav
.Weight
);
87 return matched_filters_by_flavor
.Values
;
90 static public int GetFilterVersion (string filter_name
)
92 if (filter_versions_by_name
.Contains (filter_name
)) {
93 return (int) filter_versions_by_name
[filter_name
];
99 /////////////////////////////////////////////////////////////////////////
101 static public ICollection
CreateFiltersFromMimeType (string mime_type
)
103 return CreateFilters (null, null, mime_type
);
106 static public ICollection
CreateFilterFromExtension (string extension
)
108 return CreateFilters (null, extension
, null);
111 static public ICollection
CreateFiltersFromPath (string path
)
113 string guessed_mime_type
= XdgMime
.GetMimeType (path
);
114 string extension
= Path
.GetExtension (path
);
115 return CreateFilters (UriFu
.PathToFileUri (path
), extension
, guessed_mime_type
);
118 static public ICollection
CreateFiltersFromUri (Uri uri
)
121 return CreateFiltersFromPath (uri
.LocalPath
);
123 return CreateFilters (uri
, null, null);
126 static public ICollection
CreateFiltersFromIndexable (Indexable indexable
)
128 string path
= indexable
.ContentUri
.LocalPath
;
129 string extension
= Path
.GetExtension (path
);
130 string mime_type
= indexable
.MimeType
;
131 return CreateFilters (UriFu
.PathToFileUri (path
), extension
, mime_type
);
134 /////////////////////////////////////////////////////////////////////////
136 static private bool ShouldWeFilterThis (Indexable indexable
)
138 if (indexable
.Filtering
== IndexableFiltering
.Never
139 || indexable
.NoContent
)
142 if (indexable
.Filtering
== IndexableFiltering
.Always
)
145 // Our default behavior is to try to filter non-transient file
146 // indexable and indexables with a specific mime type attached.
147 if (indexable
.IsNonTransient
|| indexable
.MimeType
!= null)
153 static public bool FilterIndexable (Indexable indexable
, TextCache text_cache
, out Filter filter
)
156 ICollection filters
= null;
158 if (indexable
.Filtering
== IndexableFiltering
.AlreadyFiltered
)
161 if (! ShouldWeFilterThis (indexable
)) {
162 indexable
.NoContent
= true;
168 // First, figure out which filter we should use to deal with
171 // If a specific mime type is specified, try to index as that type.
172 if (indexable
.MimeType
!= null)
173 filters
= CreateFiltersFromMimeType (indexable
.MimeType
);
175 if (indexable
.ContentUri
.IsFile
) {
176 path
= indexable
.ContentUri
.LocalPath
;
178 // Otherwise sniff the mime-type from the file
179 if (indexable
.MimeType
== null)
180 indexable
.MimeType
= XdgMime
.GetMimeType (path
);
182 if (filters
== null || filters
.Count
== 0) {
183 filters
= CreateFiltersFromIndexable (indexable
);
186 if (Directory
.Exists (path
)) {
187 indexable
.MimeType
= "inode/directory";
188 indexable
.NoContent
= true;
189 if (! indexable
.ValidTimestamp
)
190 indexable
.Timestamp
= Directory
.GetLastWriteTimeUtc (path
);
191 } else if (File
.Exists (path
)) {
192 // Set the timestamp to the best possible estimate (if no timestamp was set by the backend)
193 if (! indexable
.ValidTimestamp
)
194 indexable
.Timestamp
= File
.GetLastWriteTimeUtc (path
);
196 Logger
.Log
.Warn ("No such file: {0}", path
);
201 // We don't know how to filter this, so there is nothing else to do.
202 if (filters
.Count
== 0) {
203 if (! indexable
.NoContent
) {
204 indexable
.NoContent
= true;
206 Logger
.Log
.Debug ("No filter for {0} ({1})", path
!= null ? path
: indexable
.Uri
.ToString (), indexable
.MimeType
);
213 foreach (Filter candidate_filter
in filters
) {
215 Logger
.Log
.Debug ("Testing filter: {0}", candidate_filter
);
217 // Hook up the snippet writer.
218 if (candidate_filter
.SnippetMode
&& text_cache
!= null) {
219 if (candidate_filter
.OriginalIsText
&& indexable
.IsNonTransient
) {
220 text_cache
.MarkAsSelfCached (indexable
.Uri
);
221 } else if (indexable
.CacheContent
) {
222 TextWriter writer
= text_cache
.GetWriter (indexable
.Uri
);
223 candidate_filter
.AttachSnippetWriter (writer
);
227 if (indexable
.Crawled
)
228 candidate_filter
.EnableCrawlMode ();
230 // Set the filter's URI
231 candidate_filter
.Uri
= indexable
.Uri
;
233 // allow the filter access to the indexable's properties
234 candidate_filter
.IndexableProperties
= indexable
.Properties
;
236 // Open the filter, copy the file's properties to the indexable,
237 // and hook up the TextReaders.
239 bool succesful_open
= false;
240 TextReader text_reader
;
241 Stream binary_stream
;
244 succesful_open
= candidate_filter
.Open (path
);
245 else if ((text_reader
= indexable
.GetTextReader ()) != null)
246 succesful_open
= candidate_filter
.Open (text_reader
);
247 else if ((binary_stream
= indexable
.GetBinaryStream ()) != null)
248 succesful_open
= candidate_filter
.Open (binary_stream
);
250 if (succesful_open
) {
251 foreach (Property prop
in candidate_filter
.Properties
)
252 indexable
.AddProperty (prop
);
253 indexable
.SetTextReader (candidate_filter
.GetTextReader ());
254 indexable
.SetHotTextReader (candidate_filter
.GetHotTextReader ());
257 Logger
.Log
.Debug ("Successfully filtered {0} with {1}", path
, candidate_filter
);
259 filter
= candidate_filter
;
262 Logger
.Log
.Debug ("Unsuccessfully filtered {0} with {1}, falling back", path
, candidate_filter
);
263 candidate_filter
.Cleanup ();
268 Logger
.Log
.Debug ("None of the matching filters could process the file: {0}", path
);
273 static public bool FilterIndexable (Indexable indexable
, out Filter filter
)
275 return FilterIndexable (indexable
, null, out filter
);
278 static public bool FilterIndexable (Indexable indexable
)
280 Filter filter
= null;
282 return FilterIndexable (indexable
, null, out filter
);
285 /////////////////////////////////////////////////////////////////////////
287 private static Hashtable filter_types_by_flavor
= new Hashtable ();
288 private static Hashtable filter_versions_by_name
= new Hashtable ();
290 static private int ScanAssemblyForFilters (Assembly assembly
)
294 foreach (Type t
in ReflectionFu
.ScanAssemblyForClass (assembly
, typeof (Filter
))) {
295 Filter filter
= null;
298 filter
= (Filter
) Activator
.CreateInstance (t
);
299 } catch (Exception ex
) {
300 Logger
.Log
.Error (ex
, "Caught exception while instantiating {0}", t
);
306 filter_versions_by_name
[t
.ToString ()] = filter
.Version
;
308 foreach (FilterFlavor flavor
in filter
.SupportedFlavors
) {
309 filter_types_by_flavor
[flavor
] = t
;
310 FilterFlavor
.Flavors
.Add (flavor
);
321 /////////////////////////////////////////////////////////////////////////
323 public class FilteredStatus
326 private string filter_name
;
327 private int filter_version
;
335 [XmlAttribute ("Uri")]
336 public string UriAsString
{
338 return UriFu
.UriToEscapedString (uri
);
342 uri
= UriFu
.EscapedStringToUri (value);
346 public string FilterName
{
347 get { return filter_name; }
348 set { filter_name = value; }
351 public int FilterVersion
{
352 get { return filter_version; }
353 set { filter_version = value; }
356 public static FilteredStatus
New (Indexable indexable
, Filter filter
)
358 FilteredStatus status
= new FilteredStatus ();
360 status
.Uri
= indexable
.Uri
;
361 status
.FilterName
= filter
.GetType ().ToString ();
362 status
.FilterVersion
= filter
.Version
;