Debian Codegraph @

lib/ninix/dll/niseshiori.rb

raw
1 # -*- coding: utf-8 -*-
2 #
3 # niseshiori.rb - a "偽栞" compatible Shiori module for ninix
4 # Copyright (C) 2001, 2002 by Tamito KAJIYAMA
5 # Copyright (C) 2002, 2003 by MATSUMURA Namihiko <[email protected]>
6 # Copyright (C) 2002-2019 by Shyouzou Sugitani <[email protected]>
7 # Copyright (C) 2003 by Shun-ichi TAHARA <[email protected]>
8 #
9 # This program is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License (version 2) as
11 # published by the Free Software Foundation. It is distributed in the
12 # hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
13 # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 # PURPOSE. See the GNU General Public License for more details.
15 #
16
17 require_relative "../logging"
18
19
20 module Niseshiori
21
22 REVISION = '$Revision: 1.28 $' ## FIXME
23
24 # tree node types
25 ADD_EXPR = 1
26 MUL_EXPR = 2
27 UNARY_EXPR = 3
28 PRIMARY_EXPR = 4
29
30 def self.list_dict(top_dir)
31 buf = []
32 begin
33 filelist = []
34 Dir.foreach(top_dir, :encoding => 'UTF-8') do |file|
35 next if file == '..' or file == '.'
36 filelist << file
37 end
38 rescue #except OSError:
39 filelist = []
40 end
41 re_dict_filename = Regexp.new('\Aai.*\.(dtx|txt)\z')
42 for filename in filelist
43 unless re_dict_filename.match(filename).nil?
44 buf << File.join(top_dir, filename)
45 end
46 end
47 return buf
48 end
49
50
51 class NiseShiori
52
53 def initialize
54 @dict = {}
55 @type_chains = {}
56 @word_chains = {}
57 @keywords = {}
58 @responses = {}
59 @greetings = {}
60 @events = {}
61 @resources = {}
62 @variables = {}
63 @dbpath = nil
64 @expr_parser = ExprParser.new()
65 @username = ''
66 @ai_talk_interval = 180
67 @ai_talk_count = 0
68 @surf0 = 0
69 @surf1 = 10
70 @event = nil
71 @reference = nil
72 @jump_entry = nil
73 @motion_area = nil
74 @motion_count = 0
75 @mikire = 0
76 @kasanari = 0
77 @otherghost = []
78 @to = ''
79 @sender = ''
80 end
81
82 def load(top_dir)
83 # read dictionaries
84 dictlist = Niseshiori.list_dict(top_dir)
85 return 1 if dictlist.empty?
86 for path in dictlist
87 read_dict(path)
88 end
89 # read variables
90 @dbpath = File.join(top_dir, 'niseshiori.db')
91 load_database(@dbpath)
92 return 0
93 end
94
95 def load_database(path)
96 begin
97 open(path, encoding='utf-8') do |f|
98 dic = {}
99 for line in f
100 if line.start_with?('# ns_st: ')
101 begin
102 @ai_talk_interval = Integer(line[9..-1])
103 rescue #except ValueError:
104 #pass
105 end
106 next
107 elsif line.start_with?('# ns_tn: ')
108 @username = line[9..-1].strip()
109 next
110 end
111 begin
112 name, value = line.split('=', 2)
113 name.strip!
114 value.strip!
115 rescue #except ValueError:
116 Logging::Logging.error(
117 'niseshiori.py: malformed database (ignored)')
118 return
119 end
120 dic[name] = value
121 end
122 end
123 rescue #except IOError:
124 return
125 end
126 @variables = dic
127 end
128
129 def save_database
130 return if @dbpath.nil?
131 begin
132 open(@dbpath, 'w') do |f|
133 f.write('# ns_st: ' + @ai_talk_interval.to_i.to_s + "\n")
134 f.write('# ns_tn: ' + @username.to_s + "\n")
135 for name in @variables.keys
136 value = @variables[name]
137 unless name.start_with?('_')
138 f.write(name.to_s + '=' + value.to_s + "\n")
139 end
140 end
141 end
142 rescue #except IOError:
143 Logging::Logging.error('niseshiori.py: cannot write database (ignored)')
144 return
145 end
146 end
147
148 def finalize
149 #pass
150 end
151
152 Re_type = Regexp.new('\A\\\(m[szlchtep?]|[dk])')
153 Re_user = Regexp.new('\A\\\u[a-z]')
154 Re_category = Regexp.new('\A\\\(m[szlchtep]|[dk])?\[([^\]]+)\]')
155
156 def read_dict(path)
157 # read dict file and decrypt if necessary
158 buf = []
159 open(path, 'rb') do |f|
160 basename = File.basename(path, ".*")
161 ext = File.extname(path)
162 ext = ext.downcase
163 if ext == '.dtx'
164 buf = decrypt(f.read())
165 else
166 buf = f.readlines()
167 end
168 end
169 # omit empty lines and comments and merge continuous lines
170 definitions = []
171 decode = lambda {|line| line.force_encoding('CP932').encode('UTF-8', :invalid => :replace, :undef => :replace) }
172 in_comment = false
173 i, j = 0, buf.length
174 while i < j
175 line = buf[i].strip()
176 i += 1
177 next if line.empty?
178 if i == 1 and line.start_with?('#Charset:')
179 charset = line[9..-1].force_encoding('ascii').strip()
180 if ['UTF-8', 'EUC-JP', 'EUC-KR'].include?(charset) # XXX
181 decode = lambda {|line| line.force_encoding(charset).encode('UTF-8', :invalid => :replace, :undef => :replace) }
182 end
183 next
184 elsif line.start_with?('/*')
185 in_comment = true
186 next
187 elsif line.start_with?('*/')
188 in_comment = false
189 next
190 elsif in_comment or line.start_with?('#') or line.start_with?('//')
191 next
192 end
193 lines = [line]
194 while i < j and not buf[i].nil? and \
195 (buf[i].start_with?(' ') or buf[i].start_with?("\t"))
196 lines << buf[i].strip()
197 i += 1
198 end
199 definitions << lines.join('')
200 end
201 # parse each line
202 for line in definitions
203 line = decode.call(line)
204 # special case: words in a category
205 match = Re_category.match(line)
206 unless match.nil?
207 line = line[match.end(0)..-1].strip()
208 if line.empty? or not line.start_with?(',')
209 syntax_error(path, line)
210 next
211 end
212 words = split(line).map {|s| s.strip unless s.strip.empty? }
213 words.delete(nil)
214 cattype = match.to_a[1]
215 catlist = match.to_a[2..-1]
216 for cat in catlist.map {|s| s.strip }
217 if cattype.nil?
218 keylist = [[nil, cat]]
219 else
220 keylist = [[nil, cat], [cattype, cat]]
221 end
222 for key in keylist
223 value = (@dict.include?(key) ? @dict[key] : [])
224 value.concat(words)
225 @dict[key] = value
226 end
227 end
228 unless cattype.nil?
229 key = ['\\', cattype].join('')
230 value = (@dict.include?(key) ? @dict[key] : [])
231 value.concat(words)
232 @dict[key] = value
233 end
234 next
235 end
236 # other cases
237 begin
238 command, argv = split(line, :maxcount => 1)
239 command.strip!
240 argv.strip!
241 rescue #except ValueError:
242 syntax_error(path, line)
243 next
244 end
245 if command == '\ch'
246 argv = split(argv).map {|s| s.strip }
247 case argv.length
248 when 5
249 t1, w1, t2, w2, c = argv
250 when 4
251 t1, w1, t2, w2 = argv
252 c = nil
253 when 3
254 t1, w1, c = argv
255 t2 = w2 = nil
256 else
257 syntax_error(path, line)
258 next
259 end
260 if Re_type.match(t1).nil? and Re_user.match(t1).nil?
261 syntax_error(path, line)
262 next
263 end
264 unless c.nil?
265 ch_list = (@type_chains.include?(t1) ? @type_chains[t1] : [])
266 ch_list << [c, w1]
267 @type_chains[t1] = ch_list
268 end
269 next if t2.nil?
270 if Re_type.match(t2).nil? and Re_user.match(t2).nil?
271 syntax_error(path, line)
272 next
273 end
274 unless c.nil?
275 ch_list = (@type_chains.include?(t2) ? @type_chains[t2] : [])
276 ch_list << [c, w2]
277 @type_chains[t2] = ch_list
278 end
279 m1 = ['%', t1[1..-1]].join('')
280 m2 = ['%', t2[1..-1]].join('')
281 key = [m1, w1]
282 dic = (@word_chains.include?(key) ? @word_chains[key] : {})
283 ch_list = (dic.include?(m2) ? dic[m2] : [])
284 unless ch_list.include?([c, w2])
285 ch_list << [c, w2]
286 dic[m2] = ch_list
287 @word_chains[key] = dic
288 end
289 key = [m2, w2]
290 dic = (@word_chains.include?(key) ? @word_chains[key] : {})
291 ch_list = (dic.include?(m1) ? dic[m1] : [])
292 unless ch_list.include?([c, w1])
293 ch_list << [c, w1]
294 dic[m1] = ch_list
295 @word_chains[key] = dic
296 end
297 ch_list = (@dict.include?(t1) ? @dict[t1] : [])
298 unless ch_list.include?(w1)
299 ch_list << w1
300 @dict[t1] = ch_list
301 end
302 ch_list = (@dict.include?(t2) ? @dict[t2] : [])
303 unless ch_list.include?(w2)
304 ch_list << w2
305 @dict[t2] = ch_list
306 end
307 elsif not Re_type.match(command).nil? or not Re_user.match(command).nil?
308 words = split(argv).map {|s| s.strip unless s.strip.empty? }
309 words.delete(nil)
310 value = (@dict.include?(command) ? @dict[command] : [])
311 value.concat(words)
312 @dict[command] = value
313 elsif ['\dms', '\e'].include?(command)
314 value = (@dict.include?(command) ? @dict[command] : [])
315 value << argv
316 @dict[command] = value
317 elsif command == '\ft'
318 argv = split(argv, :maxcount => 2).map {|s| s.strip }
319 if argv.length != 3
320 syntax_error(path, line)
321 next
322 end
323 w, t, s = argv
324 if Re_type.match(t).nil?
325 syntax_error(path, line)
326 next
327 end
328 @keywords[[w, t]] = s
329 elsif command == '\re'
330 argv = split(argv, :maxcount => 1).map {|s| s.strip }
331 if argv.length == 2
332 cond = parse_condition(argv[0])
333 re_list = (@responses.include?(cond) ? @responses[cond] : [])
334 re_list << argv[1]
335 @responses[cond] = re_list
336 end
337 elsif command == '\hl'
338 argv = split(argv, :maxcount => 1).map {|s| s.strip }
339 if argv.length == 2
340 hl_list = (@greetings.include?(argv[0]) ? @greetings[argv[0]] : [])
341 hl_list << argv[1]
342 @greetings[argv[0]] = hl_list
343 end
344 elsif command == '\ev'
345 argv = split(argv, :maxcount => 1).map {|s| s.strip }
346 if argv.length == 2
347 cond = parse_condition(argv[0])
348 ev_list = (@events.include?(cond) ? @events[cond] : [])
349 ev_list << argv[1]
350 @events[cond] = ev_list
351 end
352 elsif command == '\id'
353 argv = split(argv, :maxcount => 1).map {|s| s.strip }
354 if argv.length == 2
355 if ['sakura.recommendsites',
356 'kero.recommendsites',
357 'sakura.portalsites'].include?(argv[0])
358 id_list = (@resources.include?(argv[0]) ? @resources[argv[0]] : '')
359 unless id_list.empty?
360 id_list = [id_list, "\2"].join('')
361 end
362 id_list = [id_list, argv[1].gsub(' ', "\1")].join('')
363 @resources[argv[0]] = id_list
364 else
365 @resources[argv[0]] = argv[1]
366 end
367 end
368 elsif command == '\tc'
369 #pass
370 else
371 syntax_error(path, line)
372 end
373 end
374 end
375
376 def split(line, maxcount: nil)
377 buf = []
378 count = 0
379 end_ = pos = 0
380 while maxcount.nil? or count < maxcount
381 pos = line.index(',', pos)
382 if pos.nil? or pos < 0
383 break
384 elsif pos > 0 and line[pos - 1] == '\\'
385 pos += 1
386 else
387 unless pos.zero?
388 buf << line[end_..pos-1]
389 count += 1
390 end
391 end
392 end_ = pos = (pos + 1)
393 end
394 buf << line[end_..-1]
395 return buf.map {|s| s.gsub('\\,', ',') }
396 end
397
398 def syntax_error(path, line)
399 Logging::Logging.debug(
400 'niseshiori.py: syntax error in ' + File.basename(path, ".*"))
401 Logging::Logging.debug(line)
402 end
403
404 Re_comp_op = Regexp.new('<[>=]?|>=?|=')
405 COND_COMPARISON = 1
406 COND_STRING = 2
407
408 def parse_condition(condition)
409 buf = []
410 for expr in condition.split('&', -1).map {|s| s.strip }
411 match = Re_comp_op.match(expr)
412 unless match.nil?
413 buf << [COND_COMPARISON, [
414 expr[0..match.begin(0)-1].strip(),
415 match.to_s,
416 expr[match.end(0)..-1].strip()]]
417 else
418 buf << [COND_STRING, expr]
419 end
420 end
421 return buf
422 end
423
424 def decrypt(data)
425 buf = []
426 a = 0x61
427 i = 0
428 j = data.length
429 line = []
430 while i < j
431 if data[i].ord == 64 # == '@'[0]
432 i += 1
433 buf << line.join('')
434 line = []
435 next
436 end
437 y = data[i].ord
438 i += 1
439 x = data[i].ord
440 i += 1
441 x -= a
442 a += 9
443 y -= a
444 a += 2
445 a = 0x61 if a > 0xdd
446 line << ((x & 0x03) | ((y & 0x03) << 2) | \
447 ((y & 0x0c) << 2) | ((x & 0x0c) << 4)).chr
448 end
449 return buf
450 end
451
452 def getaistringrandom
453 result = get_event_response('OnNSRandomTalk')
454 result = get('\e') if result.nil? or result.empty?
455 return result
456 end
457
458 def get_event_response(event,
459 ref0=nil, ref1=nil, ref2=nil, ref3=nil,
460 ref4=nil, ref5=nil, ref6=nil, ref7=nil)
461 ref = [ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7]
462 if ['OnSecondChange', 'OnMinuteChange'].include?(event)
463 if ref[1] == 1
464 @mikire += 1
465 script = get_event_response('OnNSMikireHappen')
466 return script unless script.nil?
467 elsif @mikire > 0
468 @mikire = 0
469 return get_event_response('OnNSMikireSolve')
470 end
471 if ref[2] == 1
472 @kasanari += 1
473 script = get_event_response('OnNSKasanariHappen')
474 return script unless script.nil?
475 elsif @kasanari > 0
476 @kasanari = 0
477 return get_event_response('OnNSKasanariHappen')
478 end
479 if event == 'OnSecondChange' and @ai_talk_interval > 0
480 @ai_talk_count += 1
481 if @ai_talk_count == @ai_talk_interval
482 @ai_talk_count = 0
483 if not @otherghost.empty? and \
484 (0..10).to_a.sample.zero?
485 target = []
486 for name, s0, s1 in @otherghost
487 if @greetings.include?(name)
488 target << name
489 end
490 end
491 unless target.empty?
492 @to = target.sample
493 end
494 unless @to.empty?
495 @current_time = Time.now
496 s = @greetings[@to].sample
497 unless s.empty?
498 s = replace_meta(s)
499 while true
500 match = Re_ns_tag.match(s)
501 break if match.nil?
502 value = eval_ns_tag(match.to_s)
503 s = [s[0..match.begin(0)-1],
504 value.to_s,
505 s[match.end(0)..-1]].join('')
506 end
507 end
508 return s
509 end
510 end
511 return getaistringrandom()
512 end
513 end
514 return nil
515 elsif event == 'OnMouseMove'
516 if @motion_area != [ref[3], ref[4]]
517 @motion_area = [ref[3], ref[4]]
518 @motion_count = 0
519 else
520 @motion_count += 5 # sensitivity
521 end
522 elsif event == 'OnSurfaceChange'
523 @surf0 = ref[0]
524 @surf1 = ref[1]
525 elsif event == 'OnUserInput' and ref[0] == 'ninix.niseshiori.username'
526 @username = ref[1]
527 save_database()
528 return '\e'
529 elsif event == 'OnCommunicate'
530 @event = ''
531 @reference = [ref[1]]
532 if ref[0] == 'user'
533 @sender = 'User'
534 else
535 @sender = ref[0]
536 end
537 candidate = []
538 for cond in @responses.keys
539 if eval_condition(cond)
540 candidate << cond
541 end
542 end
543 script = nil
544 @to = ref[0]
545 unless candidate.empty?
546 cond = candidate.sample
547 script = @responses[cond].sample
548 end
549 if (script.nil? or script.empty?) and @responses.include?('nohit')
550 script = @responses['nohit'].sample
551 end
552 if script.nil? or script.empty?
553 @to = ''
554 else
555 script = replace_meta(script)
556 while true
557 match = Re_ns_tag.match(script)
558 break if match.nil?
559 value = eval_ns_tag(match.to_s)
560 script = [script[0..match.begin(0)-1],
561 value.to_s,
562 script[match.end(0)..-1]].join('')
563 end
564 end
565 @sender = ''
566 return script
567 end
568 key = 'action'
569 @dict[key] = []
570 @event = event
571 @reference = ref
572 @current_time = Time.now
573 for condition in @events.keys
574 actions = @events[condition]
575 if eval_condition(condition)
576 @dict[key].concat(actions)
577 end
578 end
579 script = get(key, :default => nil)
580 @ai_talk_count = 0 unless script.nil?
581 @event = nil
582 @reference = nil
583 return script # unless script.nil?
584 end
585
586 def otherghostname(ghost_list)
587 @otherghost = []
588 for ghost in ghost_list
589 name, s0, s1 = ghost.split(1.chr, 3)
590 @otherghost << [name, s0, s1]
591 end
592 return ''
593 end
594
595 def communicate_to
596 to = @to
597 @to = ''
598 return to
599 end
600
601 def eval_condition(condition)
602 for cond_type, expr in condition
603 return false unless eval_conditional_expression(cond_type, expr)
604 end
605 return true
606 end
607
608 def eval_conditional_expression(cond_type, expr)
609 case cond_type
610 when COND_COMPARISON
611 value1 = expand_meta(expr[0])
612 value2 = expr[2]
613 begin
614 op1 = Integer(value1)
615 op2 = Integer(value2)
616 rescue #except ValueError:
617 op1 = value1.to_s
618 op2 = value2.to_s
619 end
620 case expr[1]
621 when '>='
622 return op1 >= op2
623 when '<='
624 return op1 <= op2
625 when '>'
626 return op1 > op2
627 when '<'
628 return op1 < op2
629 when '='
630 return op1 == op2
631 when '<>'
632 return op1 != op2
633 end
634 when COND_STRING
635 return true if @event.include?(expr)
636 for ref in @reference
637 return true if not ref.nil? and ref.to_s.include?(expr)
638 end
639 return false
640 else
641 return false
642 end
643 end
644
645 Re_ns_tag = Regexp.new('\\\(ns_(st(\[[0-9]+\])?|cr|hl|rf\[[^\]]+\]|ce|tc\[[^\]]+\]|tn(\[[^\]]+\])?|jp\[[^\]]+\]|rt)|set\[[^\]]+\])')
646
647 def get(key, default: '')
648 @current_time = Time.now
649 s = expand(key, '', :default => default)
650 unless s.nil? or s.empty?
651 while true
652 match = Re_ns_tag.match(s)
653 break if match.nil?
654 value = eval_ns_tag(match.to_s)
655 s = [s[0..match.begin(0)-1], value.to_s, s[match.end(0)..-1]].join('')
656 end
657 end
658 return s
659 end
660
661 def eval_ns_tag(tag)
662 value = ''
663 if tag == '\ns_cr'
664 @ai_talk_count = 0
665 elsif tag == '\ns_ce'
666 @to = ''
667 elsif tag == '\ns_hl'
668 if not @otherghost.empty?
669 @to = @otherghost.sample[0]
670 elsif tag.start_with?('\ns_st[') and tag.end_with?(']')
671 begin
672 num = Integer(tag[7..-2])
673 rescue #except ValueError:
674 @pass
675 else
676 case num
677 when 0
678 @ai_talk_interval = 0
679 when 1
680 @ai_talk_interval = 420
681 when 2
682 @ai_talk_interval = 180
683 when 3
684 @ai_talk_interval = 60
685 else
686 @ai_talk_interval = [[num, 4].max, 999].min
687 end
688 save_database()
689 @ai_talk_count = 0
690 end
691 elsif tag.start_with?('\ns_jp[') and tag.end_with?(']')
692 name = tag[7..-2]
693 @jump_entry = name
694 value = get_event_response('OnNSJumpEntry')
695 value = '' if value.nil? or value.empty?
696 @jump_entry = nil
697 elsif tag.start_with?('\set[') and tag.end_with?(']')
698 statement = tag[5..-2]
699 unless statement.include?('=')
700 Logging::Logging.debug('niseshiori.py: syntax error')
701 Logging::Logging.debug(tag)
702 else
703 name, expr = statement.split('=', :maxcount => 2)
704 name.strip!
705 expr .strip!
706 value = eval_expression(expr)
707 unless value.nil?
708 @variables[name] = value
709 unless name.start_with?('_')
710 save_database()
711 end
712 Logging::Logging.debug('set ' + name.to_s + ' = "' + value.to_s + '"')
713 else
714 Logging::Logging.debug('niseshiori.py: syntax error')
715 Logging::Logging.debug(tag)
716 end
717 end
718 end
719 elsif tag == '\ns_rt'
720 value = '\a'
721 elsif tag == '\ns_tn'
722 value = '\![open,inputbox,ninix.niseshiori.username,-1]'
723 elsif tag.start_with?('\ns_tn[') and tag.end_with?(']')
724 @username = tag[7..-2]
725 save_database()
726 end
727 return value
728 end
729
730 Re_meta = Regexp.new('%((rand([1-9]|\[[0-9]+\])|selfname2?|sakuraname|keroname|username|friendname|year|month|day|hour|minute|second|week|ghostname|sender|ref[0-7]|surf[01]|word|ns_st|get\[[^\]]+\]|jpentry|plathome|platform|move|mikire|kasanari|ver)|(dms|(m[szlchtep?]|[dk])(\[[^\]]*\])?|\[[^\]]*\]|u[a-z])([2-9]?))')
731
732 def replace_meta(s)
733 pos = 0
734 buf = []
735 variables = {}
736 variable_chains = []
737 while true
738 match = Re_meta.match(s, pos)
739 if match.nil?
740 buf << s[pos..-1]
741 break
742 end
743 unless match.begin(0).zero?
744 buf << s[pos..match.begin(0)-1]
745 end
746 meta = match.to_s
747 unless match[4].nil? # %ms, %dms, %ua, etc.
748 unless variables.include?(meta)
749 chained_meta = ['%', match[4]].join('')
750 break_flag = false
751 for chains in variable_chains
752 if chains.include?(meta)
753 candidates_A, candidates_B = chains[chained_meta]
754 unless candidates_A.empty?
755 word = candidates_A.sample
756 candidates_A.delete(word)
757 else
758 word = candidates_B.sample
759 candidates_B.delete(word)
760 end
761 if candidates_A.empty? and candidates_B.empty?
762 chains.delete(chained_meta)
763 end
764 Logging::Logging.debug('chained: ' + meta.to_s + ' => ' + word.to_s)
765 break_flag = true
766 break
767 end
768 end
769 unless break_flag
770 if match[4] == 'm?'
771 word = expand(
772 ['\\',
773 ['ms', 'mz', 'ml',
774 'mc', 'mh', 'mt',
775 'me', 'mp'].sample].join(''), s)
776 else
777 word = expand(
778 ['\\', match[4]].join(''), s)
779 end
780 end
781 chains = find_chains([chained_meta, word], s)
782 prefix = 'chain:'
783 for k in chains.keys
784 candidates_A, candidates_B = chains[k]
785 for w in candidates_A
786 Logging::Logging.debug(prefix.to_s + ' ' + k.to_s + ', ' + w.to_s)
787 prefix = ' '
788 end
789 for w in candidates_B
790 Logging::Logging.debug(prefix.to_s + ' ' + k.to_s + ', ' + w.to_s)
791 prefix = ' '
792 end
793 end
794 variables[meta] = word
795 variable_chains << chains
796 end
797 buf << variables[meta]
798 else
799 buf << expand_meta(meta).to_s
800 end
801 pos = match.end(0)
802 end
803 t = buf.join('')
804 return t
805 end
806
807 def expand(key, context, default: '')
808 choices = []
809 for keyword, word in (@type_chains.include?(key) ? @type_chains[key] : [])
810 if context.include?(keyword)
811 Logging::Logging.debug('chain keyword: ' + keyword.to_s)
812 choices << word
813 end
814 end
815 if choices.empty?
816 match = Re_category.match(key)
817 key = match.to_a[1..2] unless match.nil?
818 choices = @dict[key]
819 end
820 if choices.nil? or choices.empty?
821 if key.is_a?(Array)
822 key = ('(' + key[0].to_s + ', ' + key[1..-1].to_s + ')')
823 end
824 Logging::Logging.debug(key.to_s + ' not found')
825 return default
826 end
827 s = choices.sample
828 t = replace_meta(s)
829 if key.is_a?(Array)
830 if key[0].nil?
831 key = ('\\[' + key[1].to_s + ']')
832 else
833 key = ('\\' + key[0].to_s + '[' + key[1].to_s + ']')
834 end
835 end
836 Logging::Logging.debug([key, '=>', s].join(''))
837 Logging::Logging.debug([' ' * key.length, '=>', t].join(''))
838 return t
839 end
840
841 def find_chains(key, context)
842 chains = {}
843 dic = @word_chains.include?(key) ? @word_chains[key] : {}
844 for chained_meta in dic.keys
845 candidates_A = []
846 candidates_B = []
847 for keyword, chained_word in dic[chained_meta]
848 if not keyword.nil? and context.include?(keyword)
849 candidates_A << chained_word
850 else
851 candidates_B << chained_word
852 end
853 end
854 chains[chained_meta] = [candidates_A, candidates_B]
855 end
856 return chains
857 end
858
859 WEEKDAY_NAMES = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
860
861 def expand_meta(name)
862 if ['%selfname', '%selfname2', '%keroname', '%friendname'].include?(name)
863 result = name
864 elsif name == '%sakuraname'
865 result = '%selfname'
866 elsif name == '%username'
867 result = (@username or '%username')
868 elsif name.start_with?('%get[') and name.end_with?(']')
869 value = (@variables.include?(name[5..-2]) ? @variables[name[5..-2]] : '?')
870 begin
871 result = Integer(value)
872 rescue #except ValueError:
873 result = value
874 end
875 elsif name.start_with?('%rand[') and name.end_with?(']')
876 n = name[6..-2].to_i
877 result = (1..n).to_a.sample
878 elsif name.start_with?('%rand') and name.length == 6
879 n = name[5].to_i
880 result = (10**(n - 1)..10**n - 1).to_a.sample
881 elsif name.start_with?('%ref') and name.length == 5 and \
882 '01234567'.include?(name[4])
883 if @reference.nil?
884 result = ''
885 else
886 n = name[4].to_i
887 if @reference[n].nil?
888 result = ''
889 else
890 result = @reference[n]
891 end
892 end
893 elsif name == '%jpentry'
894 if @jump_entry.nil?
895 result = ''
896 else
897 result = @jump_entry
898 end
899 elsif name == '%year'
900 result = @current_time.year.to_s
901 elsif name == '%month'
902 result = @current_time.month.to_s
903 elsif name == '%day'
904 result = @current_time.day.to_s
905 elsif name == '%hour'
906 result = @current_time.hour.to_s
907 elsif name == '%minute'
908 result = @current_time.min.to_s
909 elsif name == '%second'
910 result = @current_time.to_s
911 elsif name == '%week'
912 result = WEEKDAY_NAMES[@current_time.wday]
913 elsif name == '%ns_st'
914 result = @ai_talk_interval
915 elsif name == '%surf0'
916 result = @surf0.to_s
917 elsif name == '%surf1'
918 result = @surf1.to_s
919 elsif ['%plathome', '%platform'].include?(name) ## FIXME
920 result = 'ninix'
921 elsif name == '%move'
922 result = @motion_count.to_s
923 elsif name == '%mikire'
924 result = @mikire.to_s
925 elsif name == '%kasanari'
926 result = @kasanari.to_s
927 elsif name == '%ver' ## FIXME
928 if REVISION[1..10] == 'Revision: '
929 result = ('偽栞 for ninix (rev.' + REVISION[11..-3] + ')')
930 else
931 result = '偽栞 for ninix'
932 end
933 elsif name == '%sender'
934 unless @sender.empty?
935 result = @sender
936 else
937 result = ''
938 end
939 elsif name == '%ghost'
940 if not @to.empty?
941 result = @to
942 elsif not @otherghost.empty?
943 result = @otherghost.sample[0]
944 else
945 result = ''
946 end
947 else
948 result = ['\\', name].join('')
949 end
950 return result
951 end
952
953 def eval_expression(expr)
954 tree = @expr_parser.parse(expr)
955 return tree.nil? ? nil : interp_expr(tree)
956 end
957
958 def __interp_add_expr(tree)
959 value = interp_expr(tree[0])
960 1.step(tree.length-1, 2) do |i|
961 operand = interp_expr(tree[i + 1])
962 begin
963 if tree[i] == '+'
964 value = (Integer(value) + Integer(operand))
965 elsif tree[i] == '-'
966 value = (Integer(value) - Integer(operand))
967 end
968 rescue #except ValueError:
969 value = [value, tree[i], operand].join('')
970 end
971 end
972 return value
973 end
974
975 def __interp_mul_expr(tree)
976 value = interp_expr(tree[0])
977 1.step(tree.length-1, 2) do |i|
978 operand = interp_expr(tree[i + 1])
979 begin
980 case tree[i]
981 when '*'
982 value = (Integer(value) * Integer(operand))
983 when '/'
984 value = (Integer(value) / Integer(operand)).to_i
985 when '\\'
986 value = (Integer(value) % Integer(operand))
987 end
988 rescue #except (ValueError, ZeroDivisionError):
989 value = [value, tree[i], operand].join('')
990 end
991 end
992 return value
993 end
994
995 def __interp_unary_expr(tree)
996 operand = interp_expr(tree[1])
997 begin
998 case tree[0]
999 when '+'
1000 return Integer(operand)
1001 when '-'
1002 return - Integer(operand)
1003 end
1004 rescue #except ValueError:
1005 return [tree[0], operand].join('')
1006 end
1007 end
1008
1009 def __interp_primary_expr(tree)
1010 if is_number(tree[0])
1011 return tree[0].to_i
1012 elsif tree[0].start_with?('%')
1013 return expand_meta(tree[0])
1014 end
1015 begin
1016 return @variables[tree[0]]
1017 rescue #except KeyError:
1018 return '?'
1019 end
1020 end
1021
1022 __expr = {
1023 ADD_EXPR => '__interp_add_expr',
1024 MUL_EXPR => '__interp_mul_expr',
1025 UNARY_EXPR => '__interp_unary_expr',
1026 PRIMARY_EXPR => '__interp_primary_expr',
1027 }
1028
1029 def interp_expr(tree)
1030 key = tree[0]
1031 if @__expr.include?(key)
1032 return method(@__expr[key]).call(self, tree[1..-1])
1033 else
1034 fail RuntimeError('should not reach here')
1035 end
1036 end
1037
1038 def is_number(s)
1039 return (not s.nil? and not s.empty? and s.chars.map.all? {|c| '0123456789'.include?(c) })
1040 end
1041 end
1042
1043
1044 class ExprError < StandardError # ValueError
1045 #pass
1046 end
1047
1048
1049 class ExprParser
1050
1051 def initialize
1052 #pass
1053 end
1054
1055 def show_progress(func, buf)
1056 if buf.nil?
1057 Logging::Logging.debug(func.to_s + '() -> syntax error')
1058 else
1059 Logging::Logging.debug(func.to_s + '() -> ' + buf.to_s)
1060 end
1061 end
1062
1063 Re_token_A = Regexp.new('\A[()*/\+-]|\d+|\s+')
1064 Re_token_B = Regexp.new('[()*/\+-]|\d+|\s+')
1065
1066 def tokenize(data)
1067 buf = []
1068 end_ = 0
1069 while true
1070 match = NiseShiori::Re_meta.match(data, end_)
1071 unless match.nil?
1072 buf << match.to_s
1073 end_ = match.end(0)
1074 next
1075 end
1076 match = Re_token_A.match(data, end_)
1077 unless match.nil?
1078 unless match.to_s.strip().empty?
1079 buf << match.to_s
1080 end
1081 end_ = match.end(0)
1082 next
1083 end
1084 match = Re_token_B.match(data, end_)
1085 unless match.nil?
1086 buf << data[end_..match.begin(0)-1]
1087 unless match.to_s.strip().empty?
1088 buf << match.to_s
1089 end
1090 end_ = match.end(0)
1091 else
1092 if end_ < data.length
1093 buf << data[end_..-1]
1094 end
1095 break
1096 end
1097 end
1098 return buf
1099 end
1100
1101 def parse(data)
1102 @tokens = tokenize(data)
1103 begin
1104 return get_expr()
1105 rescue #except ExprError:
1106 return nil # syntax error
1107 end
1108 end
1109
1110 # internal
1111 def done
1112 @tokens.empty?
1113 end
1114
1115 def pop
1116 begin
1117 return @tokens.shift
1118 rescue #except IndexError:
1119 raise ExprError
1120 end
1121 end
1122
1123 def look_ahead(index: 0)
1124 begin
1125 return @tokens[index]
1126 rescue #except IndexError:
1127 raise ExprError
1128 end
1129 end
1130
1131 def match(s)
1132 fail ExprError if pop() != s
1133 end
1134
1135 def get_expr
1136 buf = get_add_expr()
1137 fail ExprError unless done()
1138 show_progress('get_expr', buf)
1139 return buf
1140 end
1141
1142 def get_add_expr
1143 buf = [ADD_EXPR]
1144 while true
1145 buf << get_mul_expr()
1146 break if done() or not ['+', '-'].include?(look_ahead())
1147 buf << pop() # operator
1148 end
1149 buf = buf[1] if buf.length == 2
1150 show_progress('get_add_expr', buf)
1151 return buf
1152 end
1153
1154 def get_mul_expr
1155 buf = [MUL_EXPR]
1156 while true
1157 buf << get_unary_expr()
1158 break if done() or not ['*', '/', '\\'].include?(look_ahead())
1159 buf << pop() # operator
1160 end
1161 buf = buf[1] if buf.length == 2
1162 show_progress('get_mul_expr', buf)
1163 return buf
1164 end
1165
1166 def get_unary_expr
1167 if ['+', '-'].include?(look_ahead())
1168 buf = [UNARY_EXPR, pop(), get_unary_expr()]
1169 else
1170 buf = get_primary_expr()
1171 end
1172 show_progress('get_unary_expr', buf)
1173 return buf
1174 end
1175
1176 def get_primary_expr
1177 if look_ahead() == '('
1178 match('(')
1179 buf = get_add_expr()
1180 match(')')
1181 else
1182 buf = [PRIMARY_EXPR, pop()]
1183 end
1184 show_progress('get_primary_expr', buf)
1185 return buf
1186 end
1187 end
1188
1189 # <<< EXPRESSION SYNTAX >>>
1190 # expr := add-expr
1191 # add-expr := mul-expr (add-op mul-expr)*
1192 # add-op := '+' | '-'
1193 # mul-expr := unary-expr (mul-op unary-expr)*
1194 # mul-op := '*' | '/' | '\'
1195 # unary-expr := unary-op unary-expr | primary-expr
1196 # unary-op := '+' | '-'
1197 # primary-expr := identifier | constant | '(' add-expr ')'
1198
1199
1200 class Shiori < NiseShiori
1201 attr_reader :dict, :type_chains, :word_chains, :keywords, :responses, :greetings, :events
1202
1203 def initialize(dll_name)
1204 super()
1205 @dll_name = dll_name
1206 end
1207
1208 def load(dir: nil)
1209 super(dir)
1210 return 1
1211 end
1212
1213 def unload
1214 finalize
1215 end
1216
1217 def find(top_dir, dll_name)
1218 result = 0
1219 result = 100 unless Niseshiori.list_dict(top_dir).empty?
1220 return result
1221 end
1222
1223 def show_description
1224 Logging::Logging.info(
1225 "Shiori: NiseShiori compatible module for ninix\n" \
1226 " Copyright (C) 2001, 2002 by Tamito KAJIYAMA\n" \
1227 " Copyright (C) 2002, 2003 by MATSUMURA Namihiko\n" \
1228 " Copyright (C) 2002-2019 by Shyouzou Sugitani\n" \
1229 " Copyright (C) 2003 by Shun-ichi TAHARA")
1230 end
1231
1232 def request(req_string)
1233 header = req_string.split(/\r?\n/, 0)
1234 req_header = {}
1235 line = header.shift
1236 unless line.empty?
1237 line = line.strip()
1238 req_list = line.split(nil, -1)
1239 if req_list.length >= 2
1240 command = req_list[0].strip()
1241 protocol = req_list[1].strip()
1242 end
1243 for line in header
1244 line = line.encode('utf-8', :invalid => :replace, :undef => :replace).strip()
1245 next if line.empty?
1246 next unless line.include?(':')
1247 key, value = line.split(':', 2)
1248 key.strip!
1249 value.strip!
1250 begin
1251 value = Integer(value)
1252 rescue
1253 #pass
1254 end
1255 req_header[key] = value
1256 end
1257 end
1258 result = ''
1259 to = nil
1260 if req_header.include?('ID')
1261 if req_header['ID'] == 'dms'
1262 result = get('\dms')
1263 elsif req_header['ID'] == 'OnAITalk'
1264 result = getaistringrandom()
1265 elsif ['\\ms', '\\mz', '\\ml', '\\mc', '\\mh',
1266 '\\mt', '\\me', '\\mp'].include?(req_header['ID'])
1267 result = get(req_header['ID'])
1268 elsif req_header['ID'] == '\\m?'
1269 result = get(['\\ms', '\\mz', '\\ml',
1270 '\\mc', '\\mh', '\\mt',
1271 '\\me', '\\mp'].sample)
1272 elsif req_header['ID'] == 'otherghostname'
1273 otherghost = []
1274 for n in 0..127
1275 if req_header.include?(['Reference', n.to_s].join(''))
1276 otherghost <<
1277 req_header[['Reference', n.to_s].join('')]
1278 end
1279 end
1280 result = otherghostname(otherghost)
1281 elsif req_header['ID'] == 'OnTeach'
1282 if req_header.include?('Reference0')
1283 #teach(req_header['Reference0'])
1284 #pass ## FIXME
1285 end
1286 else
1287 result = @resources[req_header['ID']]
1288 if result.nil?
1289 ref = []
1290 for n in 0..7
1291 if req_header.include?(['Reference', n.to_s].join(''))
1292 ref <<
1293 req_header[['Reference', n.to_s].join('')]
1294 else
1295 ref << nil
1296 end
1297 end
1298 ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7 = ref
1299 result = get_event_response(
1300 req_header['ID'],
1301 ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7)
1302 end
1303 end
1304 result = '' if result.nil?
1305 to = communicate_to()
1306 end
1307 result = ["SHIORI/3.0 200 OK\r\n",
1308 "Sender: Niseshiori\r\n",
1309 "Charset: UTF-8\r\n",
1310 "Value: ",
1311 result,
1312 "\r\n"].join("")
1313 unless to.nil?
1314 result = [result,
1315 "Reference0: ",
1316 to,
1317 "\r\n"].join("")
1318 end
1319 result = [result, "\r\n"].join("")
1320 return result.encode('utf-8', :invalid => :replace, :undef => :replace)
1321 end
1322 end
1323 end