### Home Classes Methods

### In Files

- lib/termtter/system_extensions/termtter_compatibles.rb
- lib/termtter/system_extensions/windows.rb
- lib/termtter/system_extensions.rb
- lib/termtter/config.rb
- lib/plugins/notify-send2.rb
- lib/plugins/copy.rb
- lib/plugins/crypt.rb
- lib/plugins/saykanji.rb
- lib/plugins/notify-send3.rb
- lib/plugins/db.rb
- lib/plugins/system_status.rb
- lib/plugins/w3mimg.rb
- lib/plugins/april_fool.rb
- lib/plugins/draft.rb
- lib/plugins/defaults/keyword.rb
- lib/plugins/defaults/confirm.rb
- lib/plugins/defaults/fib.rb
- lib/plugins/wassr.rb
- lib/plugins/growl.rb
- lib/plugins/say.rb
- lib/plugins/expand-tinyurl.rb
- lib/plugins/primes.rb
- lib/plugins/nuance.rb
- lib/plugins/source.rb
- lib/plugins/gyazo.rb
- lib/plugins/translation.rb
- lib/plugins/translate_tweet.rb
- lib/plugins/whois.rb
- lib/plugins/mecab.rb
- lib/plugins/growl2.rb
- lib/plugins/hugeurl.rb
- lib/plugins/story.rb
- lib/plugins/url.rb
- lib/plugins/fib_filter.rb
- lib/plugins/quicklook.rb
- lib/plugins/irc_gw.rb
- lib/plugins/truncate.rb

### Parent

BasicObject

### Methods

- #__dir__
- #addr?
- #april_fool
- #april_fool?
- #config
- #confirm
- #copy_to_clipboard
- #create_highline
- #decrypt
- #encrypt
- #expand_url
- #fib
- #filter
- #generate_story
- #get_draft_index
- #get_icon_path
- #get_priority
- #is_growl
- #is_sticky
- #let
- #list_drafts
- #load_keywords
- #mecab
- #multibyte_string
- #open_browser
- #out_put_status
- #plugin
- #post_gyazo
- #primes
- #print
- #print_statuses
- #puts
- #quicklook
- #say
- #say_cmd
- #saykanji
- #select_matched
- #source
- #translate
- #translate_by_google
- #truncate
- #url_by_tweet
- #whois?
- #win?

### Files

- ChangeLog
- README.rdoc

### Class/Module Index

Quicksearch

- Termtter
- Termtter::API
- Termtter::ActiveRubytter
- Termtter::Client
- Termtter::Client::DirectMessage
- Termtter::Client::Jakigan
- Termtter::Client::SearchEvent
- Termtter::Client::UserSearchEvent
- Termtter::Command
- Termtter::CommandCanceled
- Termtter::CommandLine
- Termtter::CommandNotFound
- Termtter::Config
- Termtter::ConfigSetup
- Termtter::Crypt
- Termtter::English
- Termtter::Event
- Termtter::HTTPpool
- Termtter::Hook
- Termtter::HookCanceled
- Termtter::Hookable
- Termtter::JSONError
- Termtter::MemoryCache
- Termtter::MemoryCache::MemCacheMock
- Termtter::OptParser
- Termtter::Plugin
- Termtter::Plugin::Screen
- Termtter::Plugins
- Termtter::Plugins::Haml
- Termtter::Plugins::ListSwitch
- Termtter::RubytterProxy
- Termtter::RubytterProxy::FrequentAccessError
- Termtter::RubytterProxy::LimitManager
- Termtter::Status
- Termtter::StdOut
- Termtter::Storage
- Termtter::Storage::SQLite3
- Termtter::Storage::Status
- Termtter::Task
- Termtter::TaskManager
- Termtter::TypableIdGenerator
- Termtter::UserStreamReceiver
- Yharian
- Yharian::Alex
- Yharian::Jenifer
- Yharian::Remark
- Yharian::Speaker
- Yharian::Vicki
- Yharian::Yhara
- HatenaKeywordHaiku
- HatenaKeywordHaiku::Word
- OAuth
- OAuth::AccessToken
- Readline
- Readline::LIBREADLINE
- AAMaker
- Array
- BrowserNotFound
- Growl
- IRB
- Object
- Status
- String
- Symbol
- TermColor
- TermtterIrcGateway
- User

No matching classes.

# Object

### Constants

DB
HUGEURL_TARGET_PATTERN
IRC_SERVER
NATIVE_REFRESH_LINE_METHOD
URL_SHORTTERS

### Public Instance Methods

__dir__() click to toggle source

    # File lib/plugins/source.rb, line 1
    def __dir__
      File.dirname(File.expand_path(__FILE__))
    end

addr?(arg) click to toggle source

    # File lib/plugins/whois.rb, line 40
    def addr?(arg)
      Resolv::AddressRegex =~ arg
    end

april_fool() click to toggle source

    # File lib/plugins/april_fool.rb, line 3
    def april_fool;april_fool? ? "今日はエイプリルフールではありません。" : "今日はエイプリルフールです。";end

april_fool?() click to toggle source

    # File lib/plugins/april_fool.rb, line 2
    def april_fool?;true;end

config() click to toggle source

    # File lib/termtter/config.rb, line 94
    def config
      Termtter::Config.instance
    end

confirm(message) click to toggle source

    # File lib/plugins/defaults/confirm.rb, line 3
    def confirm(message)
      if config.confirm && !Termtter::Client.confirm(message)
        raise Termtter::CommandCanceled
      end
    end

copy_to_clipboard(str) click to toggle source

    # File lib/plugins/copy.rb, line 3
    def copy_to_clipboard(str)
      if /darwin/ =~ RUBY_PLATFORM
        IO.popen("pbcopy", "w") do |io|
          io.print str
        end
      else
        puts "Sorry, this plugin is only in Mac OS X."
      end
      str
    end

create_highline() click to toggle source

    # File lib/termtter/system_extensions.rb, line 55
    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) click to toggle source

    # File lib/plugins/crypt.rb, line 13
    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) click to toggle source

    # File lib/plugins/crypt.rb, line 6
    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) click to toggle source

    # File lib/plugins/expand-tinyurl.rb, line 44
    def expand_url(host, path)
      res = Termtter::HTTPpool.start(host) do |h|
        h.get(path, { 'User-Agent' => 'Mozilla' })
      end
      return nil unless res.code =~ /\A30/
      newurl = res['Location']
      newurl.respond_to?(:force_encoding) ? newurl.force_encoding(Encoding::UTF_8) : newurl
    rescue Exception => e
      Termtter::Client.handle_error(e)
      nil
    end

fib(n) click to toggle source

    # File lib/plugins/defaults/fib.rb, line 1
    def fib(n)i=0;j=1;n.times{j=i+i=j};i end

filter(name, init = {}) click to toggle source

    # File lib/termtter/system_extensions/termtter_compatibles.rb, line 14
    def filter(name, init = {})
      warn "filter method will be removed. Use plugin instead."
      plugin(name, init)
    end

generate_story() click to toggle source

    # File lib/plugins/story.rb, line 2
    def generate_story
      you = config.user_name
      friends = config.plugins.stdout.sweets.dup
      the_man = friends.delete(friends.sample)
      a = friends.delete(friends.sample)
      b = friends.delete(friends.sample)
      c = friends.delete(friends.sample)

      story =   --- アタシの名前は#{you}。心に傷を負った女子高生。      モテカワスリムで恋愛体質の愛されガール♪ アタシがつるんでる友達は援助交際をやってる#{a}、  学校にナイショでキャバクラで働いてる#{b}。  訳あって不良グループの一員になってる#{c}。 友達がいてもやっぱり学校はタイクツ。  今日もミキとちょっとしたことで口喧嘩になった。  女のコ同士だとこんなこともあるからストレスが溜まるよね☆  そんな時アタシは一人でTwitterを使うことにしている。 がんばった自分へのご褒美ってやつ？自分らしさの演出とも言うかな！  ｢あームカツク｣・・。そんなことをつぶやきながらしつこいrepliesを軽くあしらう。  ｢カノジョー、ちょっと話聞いてくれない？｣  どいつもこいつも同じようなツイートしか投稿しない。 Twitterの男はカッコイイけどなんか薄っぺらくてキライだ。  もっと等身大のアタシを見て欲しい。　｢すいません・・。｣・・・またか、とセレブなアタシは思った。  シカトするつもりだったけど、チラっとTwitterの男の顔を見た。「・・！！」　・・・チガウ・・・今までの男とはなにかが決定的に違う。スピリチュアルな感覚がアタシのカラダを駆け巡った・・。「・・（カッコイイ・・！！・・これってtermtter・・？）」男は#{the_man}だった。連れていかれてfibでやすらぎされた。「キャーやめて！」gをキメた。「ガッシ！ボカッ！」アタシはコミッタになった。コミット（笑）
    end

get_draft_index(arg) click to toggle source

    # 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) click to toggle source

    # File lib/plugins/notify-send2.rb, line 17
    def get_icon_path(s)
      /https?:\/\/.+\/(\d+)\/.*?$/ =~ s.user.profile_image_url
      cache_file = "%s/%s-%s%s" % [
        config.plugins.notify_send.icon_cache_dir,
        s.user.screen_name,
        $+,
        File.extname(s.user.profile_image_url)]
      unless File.exist?(cache_file)
        Thread.new(s,cache_file) do |s,cache_file|
          Dir.glob(
            "#{config.plugins.notify_send.icon_cache_dir}/#{s.user.screen_name}-*") {|f|
            File.delete(f)
          }
          begin
            s.user.profile_image_url.sub!(/^https/,'http')
            File.open(cache_file, 'wb') do |f|
              f << open(URI.escape(s.user.profile_image_url)).read
            end
          rescue OpenURI::HTTPError
            cache_file =
              "#{config.plugins.notify_send.icon_cache_dir}/default.png"
          end
        end
      end
      return cache_file
    end

get_priority(s,priority_keys) click to toggle source

    # File lib/plugins/growl2.rb, line 74
    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) click to toggle source

    # File lib/plugins/growl2.rb, line 84
    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) click to toggle source

    # File lib/plugins/growl2.rb, line 90
    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) click to toggle source

    # File lib/plugins/source.rb, line 5
    def let(o)
      yield o
    end

list_drafts(drafts) click to toggle source

    # File lib/plugins/draft.rb, line 3
    def list_drafts(drafts)
      drafts.each_with_index do |draft, index|
        puts "#{index}: #{draft}"
      end
    end

load_keywords() click to toggle source

    # File lib/plugins/defaults/keyword.rb, line 29
    def load_keywords
      public_storage[:keywords] += config.plugins.keyword.keywords
      file = File.expand_path(config.plugins.keyword.file)
      if File.exists?(file)
        public_storage[:keywords] += File.read(file).split(/\n/)
      end
    end

mecab(str) click to toggle source

mecab('これはテストです') #=>

    [["これ", "名詞", "代名詞", "一般", "*", "*", "*", "これ", "コレ", "コレ"],
     ["は", "助詞", "係助詞", "*", "*", "*", "*", "は", "ハ", "ワ"],
     ["テスト", "名詞", "サ変接続", "*", "*", "*", "*", "テスト", "テスト", "テスト"],
     ["です", "助動詞", "*", "*", "*", "特殊・デス", "基本形", "です", "デス", "デス"]]

    # File lib/plugins/mecab.rb, line 7
    def mecab(str)
      IO.popen('mecab', 'r+') {|io|
        io.puts str
        io.close_write
        io.read.split(/\n/).map {|i| i.split(/\t|,/) }[0..-2]
      }
    end

multibyte_string(text) click to toggle source

    # File lib/plugins/truncate.rb, line 2
    def multibyte_string(text)
      text.unpack('U*')
    end

open_browser(url) click to toggle source

    # File lib/termtter/system_extensions.rb, line 66
    def open_browser(url)
      found = case RUBY_PLATFORM.downcase
      when /linux/
        [['xdg-open'], ['x-www-browser'], ['firefox'], ['w3m', '-X']]
      when /darwin/
        [['open']]
      when /mswin(?!ce)|mingw|bccwin/
        [['start']]
      else
        [['xdg-open'], ['firefox'], ['w3m', '-X']]
      end.find do |cmd|
        system *(cmd.dup << url)
        $?.exitstatus != 127
      end
      if found
        # Kernel::__method__ is not suppoted in Ruby 1.8.6 or earlier.
        define_method(:open_browser) {|url| system *(found.dup << url) }
      else
        raise BrowserNotFound
      end
    end

out_put_status(status, color) click to toggle source

    # File lib/plugins/system_status.rb, line 9
    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 = {}) click to toggle source

    # File lib/termtter/system_extensions/termtter_compatibles.rb, line 2
    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_gyazo() click to toggle source

    # File lib/plugins/gyazo.rb, line 3
    def post_gyazo
      browser_cmd = 'firefox'
      gyazo_url = ""

      idfile = ENV['HOME'] + "/.gyazo.id"

      id = nil
      if File.exist?(idfile)
        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 = --#{boundary}\rcontent-disposition: form-data; name="id"\r\r#{id}\r--#{boundary}\rcontent-disposition: form-data; name="imagedata"\r\r#{imagedata}\r\r--#{boundary}--\r

      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
      }
      gyazo_url
    end

primes(n) click to toggle source

    # File lib/plugins/primes.rb, line 2
    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

print(str) click to toggle source

    # File lib/termtter/system_extensions/windows.rb, line 58
    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

print_statuses(statuses, sort = true, time_format = nil) click to toggle source

    # File lib/plugins/wassr.rb, line 48
    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 = ''

      user_login_ids = []
      statuses.sort{|a, b| a.epoch <=> b.epoch}.each do |s|
        text = s.text
        user_login_ids << s.user_login_id unless user_login_ids.include?(s.user_login_id)
        status_color = config.plugins.stdout.colors[user_login_ids.index(s.user_login_id) % 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) click to toggle source

    # File lib/termtter/system_extensions/windows.rb, line 81
    def puts(str)
      print str
      STDOUT.puts
    end

quicklook(url) click to toggle source

    # File lib/plugins/quicklook.rb, line 11
    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) click to toggle source

    # File lib/plugins/saykanji.rb, line 45
    def say(who, text)
      text_to_say = text.gsub(URI.regexp(['http', 'https']), 'U.R.I.')
      voices = %(Alex Alex Bruce Fred Ralph Agnes Kathy Vicki)
      voice = voices[who.hash % voices.size]
      system 'say', '-v', voice, text_to_say
    end

say_cmd(s) click to toggle source

    # File lib/plugins/nuance.rb, line 1
    def say_cmd(s)
      return unless /darwin/ =~ RUBY_PLATFORM
      system 'say "'+s+'" >/dev/null 2> /dev/null'
    end

saykanji(text, say_speed) click to toggle source

    # File lib/plugins/saykanji.rb, line 20
    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

select_matched(statuses) click to toggle source

    # File lib/plugins/defaults/keyword.rb, line 21
    def select_matched(statuses)
      regexp = Regexp.union(*public_storage[:keywords].map(&:to_s))
      statuses.select do |status|
        /#{regexp}/ =~ status.text ||
          (config.plugins.keyword.apply_user_name == true && /#{regexp}/ =~ status[:user][:screen_name])
      end
    end

source(pluginname) click to toggle source

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

translate(text, langpair) click to toggle source

    # File lib/plugins/translation.rb, line 7
    def translate(text, langpair)
      text = Termtter::API.twitter.show(text)[:text] if /^\d+$/ =~ text

      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

translate_by_google(text,o={}) click to toggle source

    # File lib/plugins/translate_tweet.rb, line 8
    def translate_by_google(text,o={})
      opt = {:from => "",:to => "en"}.merge(o)
      j = JSON.parse(open(
        "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q="     +"#{CGI.escape(text)}&langpair=#{CGI.escape("#{opt[:from]}|#{opt[:to]}")}").read)
      j["responseData"]["translatedText"] rescue nil
    end

truncate(s) click to toggle source

    # File lib/plugins/source.rb, line 16
    def truncate(s)
      s.each_char.take(140).join
    end

url_by_tweet(t) click to toggle source

    # File lib/plugins/url.rb, line 1
    def url_by_tweet(t)
      "http://twitter.com/#{t.user.screen_name}/status/#{t.id}"
    end

whois?(arg) click to toggle source

    # File lib/plugins/whois.rb, line 24
    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?() click to toggle source

    # File lib/termtter/system_extensions.rb, line 2
    def win?
      !!(RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.