Top Level Namespace

Defined Under Namespace

Modules: Encoding, IRB, Readline, Termtter, Yharian Classes: Array, Status, String, Symbol, TermtterIrcGateway, User

Constant Summary collapse

DB =
Sequel.sqlite(config.plugins.db.path)
IRC_SERVER =
Net::IRC::Server.new(
  'localhost',
  config.plugins.irc_gw.port,
  TermtterIrcGateway,
  :logger => logger
)
HUGEURL_TARGET_PATTERN =
%r{
    http://tinyurl\.com/[\w/]+
  | http://is\.gd/[\w/]+
  | http://bit\.ly/[\w/]+
  | http://ff\.im/[-\w/]+
  | http://tr\.im/[\w/]+
}x
SHORTURL_MAKERS =
[
  { :host => "api.bit.ly",
    :format => '/shorten?version=2.0.1&longUrl=%s&login=termtter&apiKey=R_e7f22d523a803dbff7f67de18c109856' },
  { :host => "is.gd", :format => '/api.php?longurl=%s' },
  { :host => "tinyurl.com", :format => '/api-create.php?url=%s' },
]
TINYURL_HOOK_COMMANDS =
[:update, :reply]
URI_REGEXP =
URI.regexp(%w(http https ftp))
URL_SHORTTERS =
[
  { :host => "tinyurl.com", :pattern => %r'(http://tinyurl\.com(/[\w/]+))' },
  { :host => "is.gd", :pattern => %r'(http://is\.gd(/[\w/]+))' },
  { :host => "bit.ly", :pattern => %r'(http://bit\.ly(/[\w/]+))' },
  { :host => "ff.im", :pattern => %r'(http://ff\.im(/[-\w/]+))'},
  { :host => "j.mp", :pattern => %r'(http://j\.mp(/[\w/]+))' },
  { :host => "goo.gl", :pattern => %r'(http://goo\.gl(/[\w/]+))' },
]

Instance Method Summary collapse

Instance Method Details

#__dir__Object



2
3
4
# File 'lib/plugins/source.rb', line 2

def __dir__
  File.dirname(File.expand_path(__FILE__))
end

#addr?(arg) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/plugins/whois.rb', line 41

def addr?(arg)
  Resolv::AddressRegex =~ arg
end

#april_foolObject



4
# File 'lib/plugins/april_fool.rb', line 4

def april_fool;april_fool? ? "今日はエイプリルフールではありません。" : "今日はエイプリルフールです。";end

#april_fool?Boolean

Returns:

  • (Boolean)


3
# File 'lib/plugins/april_fool.rb', line 3

def april_fool?;true;end

#configObject



71
72
73
# File 'lib/termtter/config.rb', line 71

def config
  Termtter::Config.instance
end

#confirm(message) ⇒ Object



4
5
6
7
8
# File 'lib/plugins/defaults/confirm.rb', line 4

def confirm(message)
  if config.confirm && !Termtter::Client.confirm(message)
    raise Termtter::CommandCanceled
  end
end

#create_highlineObject



54
55
56
57
58
59
60
61
# File 'lib/termtter/system_extensions.rb', line 54

def create_highline
  HighLine.track_eof = false
  if $stdin.respond_to?(:getbyte) # for ruby1.9
    def $stdin.getc; getbyte
    end
  end
  HighLine.new($stdin)
end

#decrypt(msg, salt) ⇒ Object



14
15
16
17
18
19
# File 'lib/plugins/crypt.rb', line 14

def decrypt(msg, salt)
  decoder = OpenSSL::Cipher::DES.new
  decoder.decrypt
  decoder.pkcs5_keyivgen(salt)
  decoder.update([msg].pack('H*')) + decoder.final
end

#encrypt(msg, salt) ⇒ Object



7
8
9
10
11
12
# File 'lib/plugins/crypt.rb', line 7

def encrypt(msg, salt)
  encoder = OpenSSL::Cipher::DES.new
  encoder.encrypt
  encoder.pkcs5_keyivgen(salt)
  (encoder.update(msg) + encoder.final).unpack('H*').to_s
end

#expand_url(host, path) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/plugins/expand-tinyurl.rb', line 46

def expand_url(host, path)
  res = Termtter::HTTPpool.start(host) do |h|
    h.get(path, { 'User-Agent' => 'Mozilla' })
  end
  return nil unless res.code == "301" or res.code == "302"
  res['Location'].force_encoding(Encoding::UTF_8)
rescue Exception => e
  Termtter::Client.handle_error(e)
  nil
end

#fib(n) ⇒ Object



3
# File 'lib/plugins/fib_filter.rb', line 3

def fib(n)i=0;j=1;n.times{j=i+i=j};i end

#filter(name, init = {}) ⇒ Object



15
16
17
18
# File 'lib/termtter/system_extensions/termtter_compatibles.rb', line 15

def filter(name, init = {})
  warn "filter method will be removed. Use plugin instead."
  plugin(name, init)
end

#get_draft_index(arg) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/plugins/draft.rb', line 9

def get_draft_index(arg)
  case arg
  when /^\d+$/
    arg.to_i
  when ''
    -1
  else
    nil
  end
end

#get_icon_path(s) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/plugins/growl.rb', line 21

def get_icon_path(s)
  Dir.mkdir_p(config.plugins.growl.icon_cache_dir) unless File.exists?(config.plugins.growl.icon_cache_dir)
  cache_file = "%s/%s%s" % [  config.plugins.growl.icon_cache_dir, 
                              s.user.screen_name, 
                              File.extname(s.user.profile_image_url)  ]
  if !File.exist?(cache_file) || (File.atime(cache_file) + 24*60*60) < Time.now
    File.open(cache_file, "wb") do |f|
      begin
        f << open(URI.escape(s.user.profile_image_url)).read
      rescue OpenURI::HTTPError
        return nil
      end
    end
  end
  cache_file
end

#get_priority(s, priority_keys) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/plugins/growl2.rb', line 75

def get_priority(s,priority_keys)
  priority = 2
  5.times {|n|
    return priority.to_s if priority_keys['user'][n].include?(s.user.screen_name) ||
                            priority_keys['keyword'][n] =~ s.text
    priority -= 1
  }
  return '0'
end

#is_growl(s, growl_keys) ⇒ Object



85
86
87
88
89
# File 'lib/plugins/growl2.rb', line 85

def is_growl(s,growl_keys)
  return true if (growl_keys['user'].empty? && growl_keys['keyword'] == /(?!)/) ||
                 (growl_keys['user'].include?(s.user.screen_name) || growl_keys['keyword'] =~ s.text)
  return false
end

#is_sticky(s, sticky_keys) ⇒ Object



91
92
93
94
# File 'lib/plugins/growl2.rb', line 91

def is_sticky(s,sticky_keys)
  return true if sticky_keys['user'].include?(s.user.screen_name) || sticky_keys['keyword'] =~ s.text
  return false
end

#let(o) {|o| ... } ⇒ Object

Yields:

  • (o)


6
7
8
# File 'lib/plugins/source.rb', line 6

def let(o)
  yield o
end

#list_drafts(drafts) ⇒ Object



3
4
5
6
7
# File 'lib/plugins/draft.rb', line 3

def list_drafts(drafts)
  drafts.each_with_index do |draft, index|
    puts "#{index}: #{draft}"
  end
end

#multibyte_string(text) ⇒ Object



3
4
5
# File 'lib/plugins/truncate.rb', line 3

def multibyte_string(text)
  text.unpack('U*')
end

#open_browser(url) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/termtter/system_extensions.rb', line 63

def open_browser(url)
  if ENV['KDE_FULL_SESSION'] == 'true'
    system 'kfmclient', 'exec', url
  elsif ENV['GNOME_DESKTOP_SESSION_ID']
    system 'gnome-open', url
  elsif !(/not found/ =~ `which exo-open`)
    # FIXME: is fungible system('exo-open').nil? for lambda {...}
    system 'exo-open', url
  else
    case RUBY_PLATFORM.downcase
    when /linux/
      system 'firefox', url
    when /darwin/
      system 'open', url
    when /mswin(?!ce)|mingw|bccwin/
      system 'start', url
    else
      system 'firefox', url
    end
  end
end

#out_put_status(status, color) ⇒ Object



10
11
12
13
14
15
# File 'lib/plugins/system_status.rb', line 10

def out_put_status(status, color)
  formatted_status = ERB.new(config.plugins.system_status.format).result(binding)
  colored_status = color(formatted_status, color)
  print "\e[s\e[1000G\e[#{status.size - 1}D#{colored_status}\e[u"
  $stdout.flush
end

#plugin(name, init = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/termtter/system_extensions/termtter_compatibles.rb', line 3

def plugin(name, init = {})
  warn "plugin method will be removed. Use Termtter::Client.plug instead."
  unless init.empty?
    init.each do |key, value|
      config.plugins.__refer__(name.to_sym).__assign__(key.to_sym, value)
    end
  end
  load "plugins/#{name}.rb"
rescue Exception => e
  Termtter::Client.handle_error(e)
end

#post_gyazoObject



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
# File 'lib/plugins/gyazo.rb', line 3

def post_gyazo
  browser_cmd = 'firefox'
  gyazo_url = ""
  
  idfile = ENV['HOME'] + "/.gyazo.id"
  
  id = ''
  if File.exist?(idfile) then
    id = File.read(idfile).chomp
  else
    id = Time.new.strftime("%Y%m%d%H%M%S")
    File.open(idfile,"w").print(id+"\n")
  end
  
  tmpfile = "/tmp/image_upload#{$$}.png"
  
  system "import #{tmpfile}"
  
  imagedata = File.read(tmpfile)
  File.delete(tmpfile)
  
  boundary = '----BOUNDARYBOUNDARY----'
  
  data = <<EOF
--#{boundary}\r
content-disposition: form-data; name="id"\r
\r
#{id}\r
--#{boundary}\r
content-disposition: form-data; name="imagedata"\r
\r
#{imagedata}\r
\r
--#{boundary}--\r
EOF

  header ={
    'Content-Length' => data.length.to_s,
    'Content-type' => "multipart/form-data; boundary=#{boundary}"
  }

  Net::HTTP.start("gyazo.com",80){|http|
    res = http.post("/upload.cgi",data,header)
    url = res.response.to_ary[1]
    puts url
    system "#{browser_cmd} #{url}"
    gyazo_url = url
  }
  return gyazo_url
end

#primes(n) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/plugins/primes.rb', line 3

def primes(n)
  return "" if n < 3
  table = []
  (2 .. n).each do |i|
    table << i
  end

  prime = []
  loop do
    prime << table[0]
    table = table.delete_if {|x| x % prime.max == 0 }
    break if table.max < (prime.max ** 2)
  end

  r = (table+prime).sort {|a, b| a<=>b }
  r.join(', ')
end


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/termtter/system_extensions/windows.rb', line 59

def print(str)
  str.to_s.gsub("\xef\xbd\x9e", "\xe3\x80\x9c").split(/(\e\[\d*[a-zA-Z])/).each do |token|
    case token
    when /\e\[(\d+)m/
      color = $1.to_i > 90 ? ($1.to_i % 60) : $1.to_i
      $wSetConsoleTextAttribute.call $hStdOut, $colorMap[color].to_i
    when /\e\[\d*[a-zA-Z]/
      # do nothing
    else
      loop do
        begin
          STDOUT.print $iconv_u8_to_sj.iconv(token)
          break
        rescue Iconv::Failure
          STDOUT.print "#{$!.success}?"
          token = $!.failed[1..-1]
        end
      end
    end
  end
  $wSetConsoleTextAttribute.call $hStdOut, $oldColor
  $iconv_u8_to_sj.iconv(nil)
end


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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/plugins/wassr.rb', line 49

def print_statuses(statuses, sort = true, time_format = nil)
  return unless statuses and statuses.first
  unless time_format
    t0 = Time.now
    t1 = Time.at(statuses.first[:epoch])
    t2 = Time.at(statuses.last[:epoch])
    time_format =
      if [t0.year, t0.month, t0.day] == [t1.year, t1.month, t1.day] \
        and [t1.year, t1.month, t1.day] == [t2.year, t2.month, t2.day]
        '%H:%M:%S'
      else
        '%y/%m/%d %H:%M'
      end
  end

  output_text = ''

   = []
  statuses.sort{|a, b| a.epoch <=> b.epoch}.each do |s|
    text = s.text
     << s. unless .include?(s.)
    status_color = config.plugins.stdout.colors[.index(s.) % config.plugins.stdout.colors.size]
    status = "#{s.user.screen_name}: #{TermColor.escape(text)}"

    time = "[wassr] [#{Time.at(s.epoch).strftime(time_format)}]"
    id = s.id
    source =
      case s.source
      when />(.*?)</ then $1
      when 'web' then 'web'
      end

    erbed_text = ERB.new('<90><%=time%></90> <<%=status_color%>><%=status%></<%=status_color%>>').result(binding)
    output_text << TermColor.parse(erbed_text) + "\n"
  end

  if config.plugins.stdout.enable_pager && ENV['LINES'] && statuses.size > ENV['LINES'].to_i
    file = Tempfile.new('termtter')
    file.print output_text
    file.close
    system "#{config.plugins.stdout.pager} #{file.path}"
    file.close(true)
  else
    print output_text
  end
end

#puts(str) ⇒ Object



82
83
84
85
# File 'lib/termtter/system_extensions/windows.rb', line 82

def puts(str)
  print str
  STDOUT.puts
end

#quicklook(url) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/plugins/quicklook.rb', line 12

def quicklook(url)
  tmpdir = Pathname.new(config.plugins.quicklook.quicklook_tmpdir)
  path   = tmpdir + Pathname.new(url).basename

  Thread.new do
    open(path, 'w') do |f|
      f.write(open(url).read)
    end
    system("qlmanage -p #{path} > /dev/null 2>&1")
  end
end

#say(who, text) ⇒ Object

say

String -> String -> IO ()



6
7
8
9
10
# File 'lib/plugins/say.rb', line 6

def say(who, what)
  voices = %w(Alex Alex Bruce Fred Ralph Agnes Kathy Vicki)
  voice = voices[who.hash % voices.size]
  system 'say', '-v', voice, what
end

#saykanji(text, say_speed) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/plugins/saykanji.rb', line 21

def saykanji(text, say_speed)
  text_without_uri = text.gsub(URI.regexp(['http', 'https']), 'URI').
    gsub('', '').gsub(/[-―]/, '').gsub('&', 'アンド').
    delete("\n\`\'\"<>[]()|:;#")
  text_wakati = `echo #{text_without_uri}|mecab -O wakati`.split(' ')
  text_wakati.map!{ |i|
    if /[@a-zA-Z]/ =~ i && File.file?(config.plugins.saykanji.kana_english_dict_path)
      kana_english = `grep -i "\\"#{i}\\"" #{config.plugins.saykanji.kana_english_dict_path}`
      unless kana_english.empty?
        /^"(.+?)"/.match(kana_english).to_a[1]
      else
        i
      end
    elsif i == ''
      ''
    elsif i == ''
      ''
    else
      i
    end
  }
  text_to_say = `echo #{text_wakati.join}|mecab -O yomi`
  system "SayKana -s #{say_speed} \"#{text_to_say}\" 2>/dev/null"
end

#source(pluginname) ⇒ Object



10
11
12
13
14
15
# File 'lib/plugins/source.rb', line 10

def source(pluginname)
  File.read(
    let(
      Pathname(__dir__) + "#{pluginname}.rb") {|a|
        File.exist?(a) ? a : Pathname(__dir__) + "defaults/#{pluginname}.rb" })
end

#translate(text, langpair) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/plugins/translation.rb', line 8

def translate(text, langpair)
  req = Net::HTTP::Post.new('/translate_t')
  req.add_field('Content-Type', 'application/x-www-form-urlencoded')
  req.add_field('User-Agent', 'Mozilla/5.0')
  Net::HTTP.version_1_2 # Proxy に対応してない
  Net::HTTP.start('translate.google.co.jp', 80) {|http|
    response = http.request(req, "langpair=#{langpair}&text=#{URI.escape(text)}")
    doc = Nokogiri::HTML.parse(response.body, nil, 'utf-8')
    return doc.css('#result_box').text
  }
end

#truncate(text, length = 140, omission = "...") ⇒ Object



17
18
19
# File 'lib/plugins/source.rb', line 17

def truncate(s)
  s.each_char.take(140).join
end

#uriObject

Need install “SayKana” & “MeCab (UTF-8)” SayKana

http://www.a-quest.com/aquestalk/saykana/

MeCab

http://mecab.sourceforge.net/


9
# File 'lib/plugins/saykanji.rb', line 9

require 'uri'

#whois?(arg) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/plugins/whois.rb', line 25

def whois?(arg)
  if addr? arg 
    begin
      Resolv.getname(arg)
    rescue => e
      e.message
    end
  else
    begin
      Resolv.getaddress(arg)
    rescue => e
      e.message
    end
  end
end

#win?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/termtter/system_extensions.rb', line 3

def win?
  !!(RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/)
end