blob: e564e217c7ff174b9444cb4a72575b1a788d317c [file] [log] [blame]
Prateeksha Singhb44ea4c2018-05-22 11:57:21 +05301from __future__ import unicode_literals
2import frappe, requests
3from frappe import _
4from jinja2 import utils
5from html2text import html2text
6from frappe.utils import sanitize_html
7from frappe.utils.global_search import search
8
9def get_context(context):
10 context.no_cache = 1
11 if frappe.form_dict.q:
12 query = str(utils.escape(sanitize_html(frappe.form_dict.q)))
13 context.title = _('Help Results for "{0}"').format(query)
14 context.route = '/search_help'
15 d = frappe._dict()
16 d.results_sections = get_help_results_sections(query)
17 context.update(d)
18 else:
19 context.title = _('Docs Search')
20
21@frappe.whitelist(allow_guest = True)
22def get_help_results_sections(text):
23 out = []
24 settings = frappe.get_doc("Support Settings", "Support Settings")
25
26 for api in settings.search_apis:
27 results = []
28 if api.source_type == "API":
29 response_json = get_response(api, text)
30 topics_data = get_topics_data(api, response_json)
31 results = prepare_api_results(api, topics_data)
32 else:
33 # Source type is Doctype
34 doctype = api.source_doctype
35 raw = search(text, 0, 20, doctype)
36 results = prepare_doctype_results(api, raw)
37
38 if results:
39 # Add section
40 out.append({
41 "title": api.source_name,
42 "results": results
43 })
44
45 return out
46
47def get_response(api, text):
48 response = requests.get(api.base_url + '/' + api.query_route, data={
49 api.search_term_param_name: text
50 })
51
52 response.raise_for_status()
53 return response.json()
54
55def get_topics_data(api, response_json):
56 if not response_json:
57 response_json = {}
58 topics_data = {} # it will actually be an array
59 key_list = api.response_result_key_path.split(',')
60
61 for key in key_list:
62 topics_data = response_json.get(key) if not topics_data else topics_data.get(key)
63
64 return topics_data or []
65
66def prepare_api_results(api, topics_data):
67 if not topics_data:
68 topics_data = []
69
70 results = []
71 for topic in topics_data:
72 route = api.base_url + '/' + (api.post_route + '/' if api.post_route else "")
73 for key in api.post_route_key_list.split(','):
74 route += unicode(topic[key])
75
76 results.append(frappe._dict({
77 'title': topic[api.post_title_key],
78 'preview': html2text(topic[api.post_description_key]),
79 'route': route
80 }))
81 return results[:5]
82
83def prepare_doctype_results(api, raw):
84 results = []
85 for r in raw:
86 prepared_result = {}
87 parts = r["content"].split(' ||| ')
88
89 for part in parts:
90 pair = part.split(' : ', 1)
91 prepared_result[pair[0]] = pair[1]
92
93 results.append(frappe._dict({
94 'title': prepared_result[api.result_title_field],
95 'preview': prepared_result[api.result_preview_field],
96 'route': prepared_result[api.result_route_field]
97 }))
98
99 return results