-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathSearchService.cs
More file actions
80 lines (69 loc) · 1.85 KB
/
SearchService.cs
File metadata and controls
80 lines (69 loc) · 1.85 KB
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
using System;
using System.Collections.Generic;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
namespace Docs.Logic
{
public class Search
{
public string Query { get; set; }
}
public class SearchResponse : IHasResponseStatus
{
public SearchResponse()
{
this.Results = new List<Page>();
}
public string Query { get; set; }
public List<Page> Results { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class SearchService : Service
{
public PageManager PageManager { get; set; }
public object Get(Search request)
{
var results = new List<Page>();
foreach (var page in PageManager.Pages)
{
var contents = page.GetContent().StripMarkdownMarkup();
var pos = 0;
if ((pos = contents.IndexOf(request.Query, StringComparison.CurrentCultureIgnoreCase)) != -1)
{
var resultPage = page.DeepClone();
var snippet = GetSnippet(contents, pos);
resultPage.Content = snippet.Replace(request.Query, "**" + request.Query + "**");
results.Add(resultPage);
}
}
return new SearchResponse {
Query = request.Query,
Results = results
};
}
private static string GetSnippet(string contents, int pos)
{
var startPos = pos - 50;
var endPos = pos + 100;
if (endPos >= contents.Length)
{
endPos = contents.Length - 1;
startPos = endPos - 100;
}
if (startPos < 0) startPos = 0;
if (contents[startPos] != ' ')
{
var wordBoundaryPos = contents.LastIndexOf(' ', startPos);
if (wordBoundaryPos != -1) startPos = wordBoundaryPos + 1;
}
if (contents[endPos] != ' ')
{
var wordBoundaryPos = contents.IndexOf(' ', endPos);
if (wordBoundaryPos != -1) endPos = wordBoundaryPos;
}
var snippet = contents.Substring(startPos, endPos - startPos);
return snippet;
}
}
}