]> git.plutz.net Git - rigidfind/blob - index.cgi
use temp files when unzipping documents
[rigidfind] / index.cgi
1 #!/bin/sh
2
3 . "${_EXEC:-${0%/*}}/cgilite/cgilite.sh"
4 . "${_EXEC:-${0%/*}}/cgilite/storage.sh"
5 . "${_EXEC:-${0%/*}}/cgilite/json.sh"
6
7 [ "$_DATE" ] || _DATE="$(date +%s)"
8
9 debug "$REQUEST_METHOD  $REQUEST_URI    $SERVER_PROTOCOL        $_DATE"
10
11 ingest() {
12   local J="$1" ztmp="${TMP:-/tmp}/zipfile_$$.zip"
13
14   # json_get "$J" title
15   # json_get "$J" parts.comments
16
17   case $(json_get "$J" title) in
18     *.md|*.txt|*.csv)
19       printf %s "$content" |base64 -d
20       ;;
21     *.pdf)
22       printf %s "$content" |base64 -d \
23       | pdftotext - -
24       ;;
25     *.doc)
26       printf %s "$content" |base64 -d \
27       | catdoc /dev/stdin
28       ;;
29     *.xls)
30       printf %s "$content" |base64 -d \
31       | xls2csv /dev/stdin
32       ;;
33     *.ppt)
34       printf %s "$content" |base64 -d \
35       | catppt /dev/stdin
36       ;;
37     *.html|*.xml|*.svg)
38       printf %s "$content" |base64 -d \
39       | sed 's;<[^>]*>;;g'
40       ;;
41     *.docx)
42       printf %s "$content" |base64 -d >"$ztmp"
43       unzip -qc "$ztmp" word/document.xml \
44       | head -c 128M | sed 's;<[^>]*>;;g'
45       rm -- "$ztmp"
46       ;;
47     *.xlsx)
48       printf %s "$content" |base64 -d >"$ztmp"
49       unzip -qc "$ztmp" xl/sharedStrings.xml \
50       | head -c 128M | sed 's;<[^>]*>; ;g'
51       rm -- "$ztmp"
52       ;;
53     *.odt)
54       printf %s "$content" |base64 -d >"$ztmp"
55       unzip -qc "$ztmp" content.xml \
56       | head -c 128M | sed 's;<[^>]*>;;g'
57       rm -- "$ztmp"
58       ;;
59     *.ods|*.odp)
60       printf %s "$content" |base64 -d >"$ztmp"
61       unzip -qc "$ztmp" content.xml \
62       | head -c 128M | sed 's;<[^>]*>; ;g'
63       rm -- "$ztmp"
64       ;;
65     *):;;
66   esac
67 }
68
69 search() {
70   local index="$1" words w num total freq doc date J
71   shift 1; words="$@"
72
73   words="$(printf %s\\n "$words" | awk '
74     BEGIN { # Field separator FS should include punctuation, including Unicode Block U+2000 - U+206F
75             if ( length("ยก") == 1 )  # Utf-8 aware AWK
76             FS = "([] \\t\\n\\r!\"#'\''()*+,./:;<=>?\\\\^_`{|}~[-]|%[0-9A-Fa-f]{2}|'"$(printf '[\342\200\200-\342\201\257]')"')+";
77             else                     # UTF-8 Hack
78             FS = "([] \\t\\n\\r!\"#'\''()*+,./:;<=>?\\\\^_`{|}~[-]|%[0-9A-Fa-f]{2}|'"$(printf '\342\200[\200-\277]|\342\201[\201-\257]')"')+";
79             fi
80           }
81       { for (n = 1; n <= NF; n++) printf "%s  ", tolower($n); }
82   ')"
83
84   for w in ${words}; do
85     [ ! -f "${index}/$w" ] && continue
86   
87     while read num total freq doc date; do
88       printf '%s-%i  %f\n' "${doc}" "${date}" "$freq"
89     done <"${index}/$w"
90   done \
91   | awk '
92         { cnt[$1]++; weight[$1] = weight[$1] ? weight[$1] + $2 : $2; }
93     END { m = 0; for (d in cnt) m = ( m < cnt[d] ) ? cnt[d] : m;
94           for (d in cnt) if ( cnt[d] == m ) printf "%f    %s\n", weight[d], d;
95         }
96   ' \
97   | sort -nr \
98   | while read freq doc; do
99     date="${doc##*-}" doc="$(UNSTRING "${doc%-*}")"
100
101     if J="$(DBM "$_records" get "$doc")"; then
102       [ "$date" -eq "$(json_get obj:"$J" _indexdate)" ] \
103       && printf '%f     %s      %s\n' \
104          "$freq" "$(STRING "$doc")" "$(STRING "$J")"
105     fi
106   done
107 }
108
109 _INDEX="${PATH_INFO#/}" _INDEX="${_INDEX%%/*}"
110 _records="${_DATA}/${_INDEX}/_0_DOCS"
111
112 if   [ "$REQUEST_METHOD" = "PUT" ]; then
113   _doc="${PATH_INFO#"/${_INDEX}/_doc"}"
114
115   J="$(head -c "${CONTENT_LENGTH:-0}")"
116   # Don't use json parser to get content field
117   # Content can be very large and the json parser is slow
118   content="$(printf %s\\n "$J" |sed -E '
119     :X; $bY; N; bX; :Y;
120     s;^.*,[ \t\r\n]*"content"[ \t\r\n]*:[ \t\r\n]*";;
121     s;".*$;;
122     s;\\;;g;
123   ')"
124   J="$(printf %s\\n "$J" |sed -E '
125     :X; $bY; N; bX; :Y;
126     s;,[ \t\r\n]*"content"[ \t\r\n]*:[ \t\r\n]*"[^"]*";;
127   ')"
128   J="$(json_load "${J}")"
129
130   debug "Content: ${#content} bytes"
131   debug "$(json_dump "$J")"
132
133   if [ "${#content}" -gt 0 ]; then
134     ingest "$J" "$content"\
135     | "${_EXEC}/concordance.sh" \
136       "$_DATA/$_INDEX/" "$(STRING "$_doc")      $_DATE"
137   fi
138
139   J="${J#obj:}"
140   J="$(DB2 "$J" set _indexdate num:"$_DATE")"
141
142   if [ "${#content}" -eq 0 ]; then
143     printf '%s: %s\r\n' "Status" "200 OK"
144     result="updated"
145   elif DBM "$_records" insert "$_doc" "$J"; then
146     printf '%s: %s\r\n' "Status" "201 Created" "Location" "/${_INDEX}/_doc/$(URL "$_doc")" \
147     result="created"
148   elif DBM "$_records" update "$_doc" "$J"; then
149     printf '%s: %s\r\n' "Status" "200 OK"
150     result="updated"
151   else
152     printf '%s\r\n' "Status: 500 Internal Server Error" ""
153     exit 0
154   fi
155
156   cat <<-EOF
157         X-elastic-product: Elasticsearch\r
158         content-type: application/vnd.elasticsearch+json;compatible-with=8\r
159         \r
160         { "_index": $(json_dump str:"${_INDEX}"),
161           "_id": $(json_dump str:"$_doc"),
162           "result": "$result",
163           "_indexdate": $_DATE
164         }
165         EOF
166   exit 0
167
168 elif [ "$REQUEST_METHOD" = "DELETE" ]; then
169   _doc="${PATH_INFO#"/${_INDEX}/_doc"}"
170
171   if   DBM "$_records" get "$_doc"; then
172     if   DBM "$_records" delete "$_doc"; then
173       printf '%s: %s\r\n' "Status" "200 OK"
174       result="deleted"
175     else
176       printf '%s\r\n' "Status: 500 Internal Server Error" ""
177       exit 0
178     fi
179   else
180     printf '%s: %s\r\n' "Status" "404 Not Found"
181     result="not_found"
182   fi
183
184   cat <<-EOF
185         X-elastic-product: Elasticsearch\r
186         content-type: application/vnd.elasticsearch+json;compatible-with=8\r
187         \r
188         { "_index": $(json_dump str:"${_INDEX}"),
189           "_id": $(json_dump str:"$_doc"),
190           "result": "$result",
191           "_indexdate": $_DATE
192         }
193         EOF
194   exit 0
195
196 elif [ "$REQUEST_METHOD" = "POST" ]; then
197   J="$(json_load "$(head -c "${CONTENT_LENGTH:-0}")")"
198   J="$(json_get "$J" query.bool.must.bool.should)"
199
200   words="$(
201     for j in $(DB2 "$J" iterate @); do
202       json_get "$(UNSTRING "$j")" match_phrase_prefix.content
203     done 2>/dev/null
204   )"
205
206   results="@    $(
207     search "${_DATA}/${_INDEX}" $words \
208     | while read -r score id source; do
209       S="$(DB2   "" set _index  str:"${_INDEX}")"
210       S="$(DB2 "$S" set _id     str:"$(UNSTRING "${id#/}")")"
211       S="$(DB2 "$S" set _score  num:"$score")"
212       S="$(DB2 "$S" set _source obj:"$(UNSTRING "$source")")"
213       printf 'obj:%s\t' "$(STRING "$S")"
214     done
215   )"
216   results="${results%   }"
217
218   cat <<-EOF
219         Status: 200 OK\r
220         X-elastic-product: Elasticsearch\r
221         Content-Type: application/vnd.elasticsearch+json;compatible-with=8\r
222         \r
223         { "took":0,
224           "timed_out":false,
225           "_shards":{"total":1,"successful":1,"skipped":0,"failed":0},
226           "hits": {
227             "total":{"value": $(DB2 "$results" count @) ,"relation":"eq"},
228             "max_score": $(json_get "arr:$results" '[0]._score' 2>&- || printf 0),
229             "hits": $(json_dump "arr:$results")
230           }
231         }
232         EOF
233
234 elif [ "$REQUEST_METHOD" = "HEAD" ]; then
235   accept="$(HEADER Accept)"
236   [ ! "${accept#*"vnd.elasticsearch+json"*}" ] \
237   && ctype="${accept}" || ctype="application/json"
238
239   cat <<-EOF
240         HTTP/1.1 200 OK\r
241         X-elastic-product: Elasticsearch\r
242         content-type: ${ctype}\r
243         \r
244         EOF
245   exit 0
246
247 elif [ "$REQUEST_METHOD" = "GET" ]; then
248   accept="$(HEADER Accept)"
249   [ ! "${accept#*"vnd.elasticsearch+json"*}" ] \
250   && ctype="${accept}" || ctype="application/json"
251
252   cat <<-EOF
253         HTTP/1.1 200 OK\r
254         X-elastic-product: Elasticsearch\r
255         content-type: ${ctype}\r
256         \r
257         EOF
258         
259   if [ "$PATH_INFO" = "/${_INDEX}/" ]; then
260   cat <<-EOF
261         { $(json_dump str:"${_INDEX}"): {
262             "aliases":{},
263             "mappings": {
264               "properties": {
265                 "content": {"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},
266                 "hash":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},
267                 "metatags":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},
268                 "owner":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},
269                 "parts":{"properties":{"comments":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}}}},
270                 "provider":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},
271                 "share_names":{"properties":{"paul":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}}}},
272                 "source":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}},
273                 "title":{"type":"text","fields":{"keyword":{"type":"keyword","ignore_above":256}}}
274               }
275             },
276             "settings": {
277               "index": {
278                 "routing":{"allocation":{"include":{"_tier_preference":"data_content"}}},
279                 "number_of_shards":"1",
280                 "provided_name": $(json_dump str:"${_INDEX}"),
281                 "creation_date": "$(stat -c %W "${_DATA}/${_INDEX}")",
282                 "number_of_replicas":"1",
283                 "uuid":"0000000000000000000000",
284                 "version":{"created":"8500010"}
285               }
286             }
287           }
288         }
289         EOF
290   else
291     cat <<-EOF
292         { "name" : "head",
293           "cluster_name" : "elasticsearch",
294           "version" : {
295             "number" : "8.12.1",
296             "lucene_version" : "9.9.2",
297             "minimum_wire_compatibility_version" : "7.17.0",
298             "minimum_index_compatibility_version" : "7.0.0"
299           },
300           "tagline" : "You Know, for Search"
301         }
302         EOF
303   fi
304   exit 0
305
306 else
307   printf '%s\r\n' "Status: 500 Internal Server Error" ""
308   exit 0
309 fi