In Files

Files

Termtter::Client

It depends on defaults/fib.rb


config.plugins.alias.aliases = { :e => 'exit', :q => 'exit'}

Public Class Methods

alias(alias_name, command) click to toggle source
Alias for: register_alias
alias_command(arg) click to toggle source
# File lib/plugins/command_plus.rb, line 11
def alias_command(arg)
  original, new = arg.split(/\s+/)
  if @commands[original.to_sym]
    @commands[new.to_sym] = @commands[original.to_sym].clone
    @commands[new.to_sym].name    = new.to_sym
    @commands[new.to_sym].aliases = []
    @commands[new.to_sym].help    = ''
    puts "alias '#{original}' to '#{new}'."
  else
    raise "#{original} command is not found."
  end
end
collect_hashtags(text) click to toggle source
# File lib/plugins/defaults/standard_completion.rb, line 55
def self.collect_hashtags(text)
  text.force_encoding("UTF-8") if text.respond_to?(:force_encoding)
  public_storage[:hashtags_for_completion] += text.scan(/#([0-9A-Za-z_]+)/).flatten
end
delete_and_replace(recent, pattern_reg, replace, global) click to toggle source
# File lib/plugins/replace.rb, line 3
def self.delete_and_replace(recent, pattern_reg, replace, global)
  new_text =
    if global
      recent.text.gsub(pattern_reg, replace)
    else
      recent.text.sub(pattern_reg, replace)
    end

  param =
    if recent.in_reply_to_status_id
      {:in_reply_to_status_id => recent.in_reply_to_status_id}
    else
      {}
    end

  if new_text == recent.text
    puts "It was not replaced."
    raise Termtter::CommandCanceled
  end

  if /^y?$/ !~ Readline.readline("\"replace #{new_text}\" [Y/n] ", false)
    puts 'canceled.'
    raise Termtter::CommandCanceled
  else
    result = Termtter::API.twitter.remove_status(recent.id)
    puts "deleted => #{result.text}"
    result = Termtter::API.twitter.update(new_text, param)
    puts "updated => #{result.text}"
  end
end
delete_command(arg) click to toggle source
# File lib/plugins/command_plus.rb, line 3
def delete_command(arg)
  if @commands.delete(arg.to_sym)
    puts "#{arg} command is deleted."
  else
    raise "#{arg} command is not found."
  end
end
delete_output(name) click to toggle source
# File lib/plugins/multi_output.rb, line 9
def delete_output(name)
  @outputs.delete(name)
end
delete_task(key) click to toggle source
# File lib/plugins/searchline.rb, line 6
def delete_task(key)
  @task_manager.delete_task(key) # returns nil if task for key is not exist
end
encode(text, encoding) click to toggle source
# File lib/plugins/encoding.rb, line 4
def self.encode text, encoding
  return text unless encoding

  if RUBY_VERSION >= '1.9'
    begin
      text = text.encode encoding
    rescue
      # no encodings exception
    end
  else
    begin 
      require 'nkf'
    rescue
      return text
    end

    text = case encoding
           when 'utf-8'
             NKF.nkf('-w', text)
           when 'euc-jp'
             NKF.nkf('-e', text)
           when 'sjis'
             NKF.nkf('-s', text)
           else
             text
           end
  end
end
expand_tco_urls!(text, urls) click to toggle source
# File lib/plugins/defaults/expand_tco_url.rb, line 13
def self.expand_tco_urls!(text, urls)
  urls.each do |u|
    next unless u[:expanded_url]
    text[/#{Regexp.escape(u[:url])}/] = u[:expanded_url]
  end
end
fetch_title_data(uri) click to toggle source
# File lib/plugins/appendtitle.rb, line 11
def self.fetch_title_data(uri) # returns {:title, :uri} | {:uri} | nil
  return unless uri
  key = %{ plugins appendtitle title-data}.push(Digest::SHA1.hexdigest(uri)).join('-')
  if v = memory_cache.get(key)
    logger.debug "appendtitle: cache hit for #{uri}"
    return v
  end

  memory_cache.set(key, {}, config.plugins.appendtitle.cache_expire) # to avoid duplicate fetch
  logger.debug "appendtitle: fetching title for #{uri}"
  data = {}
  uri_fetch = uri
  begin
    io = URI.parse(uri_fetch).read
    base_uri = io.base_uri.to_s
    base_uri = uri_fetch if base_uri.length > 1000
    data[:uri] = base_uri
    charset = io.scan(/charset="?([^\s"]*)/).flatten.inject(Hash.new{0}){|a, b| a[b]+=1; a}.to_a.sort_by{|a|a[1]}.reverse.first[0] # XXX: scan charset from source
    begin # title
      source = Nokogiri(io, base_uri, charset)
      title = source.at('title').text rescue nil
      title ||= source.at('h1').text rescue nil
      title ||= source.at('h2').text rescue nil
      title = title.gsub(/\n/, '').gsub(/\s+/, ' ') if title
      data[:title] = title if title
    rescue
    end
    memory_cache.set(key, data, config.plugins.appendtitle.cache_expire)
    data
  rescue RuntimeError => error
    # example: redirection forbidden: http://bit.ly/gSarwN -> https://github.com/jugyo/termtter/commit/6e5fa4455a5117fb6c10bdf82bae52cfcf57a91f
    if error.message =~ /^redirection forbidden/
      logger.debug "appendtitle: #{error.message}"
      uri_fetch = error.message.split(/\s+/).last
      retry
    end
  rescue Timeout::Error, StandardError => error
    logger.debug "appendtitle: error #{uri}, #{error.class.to_s}: #{error.message}"
    nil
  end
end
find_group_candidates(a, b) click to toggle source
# File lib/plugins/group.rb, line 8
def self.find_group_candidates(a, b)
  config.plugins.group.groups.keys.map {|k| k.to_s}.
    grep(/^#{Regexp.quote a}/).
    map {|u| b % u }
end
friends(max) click to toggle source
# File lib/plugins/stream.rb, line 16
def friends(max)
  Status.group(:user_id).
    select(:user_id, :screen_name).
    join(:users, :id => :user_id).
    order(:COUNT.sql_function.desc).take(max)
end
gen_pass(master_pass) click to toggle source
# File lib/plugins/md5pass.rb, line 10
def self.gen_pass(master_pass)
    salt = config.plugins.md5pass.salt
    len = config.plugins.md5pass.len
    times = config.plugins.md5pass.times
    url = "http://#{config.host}/"
    user = config.user_name
    str = (url + salt + user + master_pass) * (2 ** times);
    Base64.encode64(Digest::MD5.digest(str))[0, len]
end
get_group_of(screen_name) click to toggle source
# File lib/plugins/group.rb, line 14
def self.get_group_of(screen_name)
  config.plugins.group.groups.select{ |k, v| v.include? screen_name}.map{|a| a.first}
end
is_member?(status, group = nil) click to toggle source
# File lib/plugins/group.rb, line 55
def self.is_member?(status, group = nil)
  if group
    config.plugins.group.groups[group].include? status.user.screen_name
  else
    config.plugins.group.groups.values.flatten.include? status.user.screen_name
  end
end
list_name_to_slug(list_name) click to toggle source
# File lib/plugins/defaults/list.rb, line 181
def self.list_name_to_slug(list_name)
  list_name[/([^\/]*)$/]
end
load_history() click to toggle source
# File lib/plugins/history.rb, line 16
def self.load_history
  filename = File.expand_path(config.plugins.history.filename)
  keys = config.plugins.history.keys

  if File.exist?(filename)
    begin
      history = Marshal.load Zlib::Inflate.inflate(File.read(filename))
    rescue Zlib::BufError => e
      ui = create_highline
      delete = ui.ask("Unable to read #{filename}. Do you wish to remove it?")
      if delete =~ /^y/
        if File.delete(filename) > 1
          puts "Removed #{filename}"
        end
      end
      history = nil
    end
    if history
      keys.each do |key|
        public_storage[key] = history[key] if history[key]
      end
      Readline::HISTORY.push *history[:history] if history[:history]
      puts "history loaded(#{File.size(filename)/1000}kb)"
    end
  end
end
mongo_db() click to toggle source
# File lib/plugins/mongo.rb, line 6
def mongo_db
  @mongo_db ||= Mongo::Connection.new('localhost', 27017, :pool_size => 5, :timeout => 5).db(config.plugins.mongo.db_name)
end
open_editor(path) click to toggle source
# File lib/plugins/defaults/plugin.rb, line 40
def self.open_editor(path)
  # TODO: change to common method or use launchy
  system ENV['EDITOR'] || 'vim', path
end
open_uri(uri) click to toggle source
# File lib/plugins/open_url.rb, line 5
def self.open_uri(uri)
  unless config.plugins.open_url.browser.empty?
    system config.plugins.open_url.browser, uri
  else
    case RUBY_PLATFORM
    when /linux/
      system 'xdg-open', uri
    when /mswin(?!ce)|mingw|bccwin/
      system 'explorer', uri
    else
      system 'open', uri
    end
  end
end
output_favorites(target, threshold) click to toggle source
# File lib/plugins/favotter.rb, line 10
def output_favorites(target, threshold)
  favorites = parse("http://favotter.matope.com/user.php?user=#{target}&threshold=#{threshold}")

  public_storage[:favorited_ids].clear
  alphabet = '$a'
  max_amount_width = favorites.map {|f| now = f[2].to_s.size }.max
  favorites.reverse.each do |id, text, amount, users|
    public_storage[:favorited_ids][alphabet] = id
    color = fav_color(amount)
    fav   = "fav#{amount == 1 ? '' : 's'}"
    favorites_info = "(#{amount} #{fav})".rjust(max_amount_width + 7)
    format = "<GREEN>#{favorites_info} #{alphabet}</GREEN> <YELLOW>%s</YELLOW>: <#{color}>%s</#{color}>"
    values = [users.join(', '), CGI.escape(text)]
    puts CGI.unescape(TermColor.parse(format % values ))
    alphabet.succ!
  end
end
plugin_files(include_system_plugins = false) click to toggle source
# File lib/plugins/defaults/plugin.rb, line 50
def self.plugin_files(include_system_plugins = false)
  files = Dir["#{Termtter::CONF_DIR}/plugins/*.rb"]
  files += Dir["#{File.expand_path(File.dirname(__FILE__))}/*.rb"] if include_system_plugins
  files
end
post_quote(s, comment = nil) click to toggle source
# File lib/plugins/quote.rb, line 6
def self.post_quote(s, comment = nil)
  if s.user.protected && config.plugins.quote.confirm_protected &&
      !confirm("#{s.user.screen_name} is protected! Are you sure?", false)
    return
  end

  comment += ' ' unless comment.nil?
  text = ERB.new(config.plugins.quote.format).result(binding)
  Termtter::API.twitter.update(text)
  puts "=> #{text}"

  return text
end
post_reply_retweet(s, comment = nil) click to toggle source
# File lib/plugins/reply_retweet.rb, line 6
def self.post_reply_retweet(s, comment = nil)
  if s.user.protected && config.plugins.reply_retweet.confirm_protected &&
      !confirm("#{s.user.screen_name} is protected! Are you sure?", false)
    return
  end

  text = s.text.gsub(/RT.+\z/, '')
  comment += ' ' unless comment.nil?
  text = ERB.new(config.plugins.reply_retweet.format).result(binding)
  Termtter::API.twitter.update(text)
  puts "=> #{text}"

  return text
end
post_retweet(s, comment = nil) click to toggle source
# File lib/plugins/defaults/retweet.rb, line 14
def self.post_retweet(s, comment = nil)
  s[:user][:protected] and
    config.plugins.retweet.confirm_protected and
    !confirm("#{s.user.screen_name} is protected! Are you sure?", false) and
    return

  # NOTE: If it's possible, this plugin tries to
  #   use the default RT feature twitter provides.
  if comment.nil? && config.plugins.retweet.official_retweet
    begin
      Termtter::API.twitter.retweet(s.id)
      # TODO: Vimshell support
      puts TermColor.parse("<blue>=&gt; RT @#{s.user.screen_name}: #{s.text}</blue>")
      return
    rescue Rubytter::APIError  # XXX: just for transition period
      if $!.to_s == 'Not found'
        Termtter::Client.logger.warn "Failed official retweet. Set twitter langage to English in https://twitter.com/account/settings or set config.plugins.retweet.official_retweet to false."
      else
        raise
      end
    end
  end
  comment += ' ' unless comment.nil?
  rt_or_qt = (config.plugins.retweet.quotetweet and comment) ? 'QT' : 'RT'
  text = ERB.new(config.plugins.retweet.format).result(binding)
  params = config.plugins.retweet.as_reply ? {:in_reply_to_status_id => s.id} : {}
  Termtter::API.twitter.update(text, params)
  puts "=> #{text}"
end
puts(message) click to toggle source
# File lib/plugins/multi_output.rb, line 13
def puts message
  @outputs.each_value do |block|
    block.call(message)
  end
end
register_alias(alias_name, command) click to toggle source
# File lib/plugins/defaults/alias.rb, line 23
def register_alias(alias_name, command)
  @aliases[alias_name.to_sym] = command.to_s
end
Also aliased as: alias
register_output(as, &block) click to toggle source
# File lib/plugins/multi_output.rb, line 5
def register_output(as, &block)
  @outputs[as] = block
end
remove_alias(alias_name) click to toggle source
# File lib/plugins/defaults/alias.rb, line 28
def remove_alias(alias_name)
  @aliases.delete alias_name.to_sym
end
save_history() click to toggle source
# File lib/plugins/history.rb, line 43
def self.save_history
  filename = File.expand_path(config.plugins.history.filename)
  keys = config.plugins.history.keys
  history = { }
  keys.each do |key|
    history[key] = public_storage[key]
  end
  max_of_history = config.plugins.history.max_of_history
  history[:history] = Readline::HISTORY.to_a.reverse.uniq.reverse
  if history[:history].size > max_of_history
    history[:history] = history[:history][-max_of_history..-1]
  end

  File.open(filename, 'w') do |f|
    f.write Zlib::Deflate.deflate(Marshal.dump(history))
  end
  puts "history saved(#{File.size(filename)/1000}kb)"
end
scrape_group(group) click to toggle source
# File lib/plugins/scrape.rb, line 13
def self.scrape_group(group)
  members = config.plugins.group.groups[group] || []
  scrape_members(members)
end
scrape_members(members) click to toggle source
# File lib/plugins/scrape.rb, line 4
def self.scrape_members(members)
  statuses = []
  members.each_with_index do |member, index|
    puts "member #{index+1}/#{members.size} #{member}"
    statuses += Termtter::API.twitter.user_timeline(member, :include_entities => 1)
  end
  statuses
end
search_plugin_file(name, include_system_plugins = false) click to toggle source
# File lib/plugins/defaults/plugin.rb, line 45
def self.search_plugin_file(name, include_system_plugins = false)
  regex = /#{Regexp.quote(name + '.rb')}$/
  plugin_files(include_system_plugins).detect {|f| regex =~ f}
end
shorten_url(url, host, format) click to toggle source

returns nil if not shorten

# File lib/plugins/tinyurl.rb, line 49
def self.shorten_url(url, host, format)
  return url if config.plugins.tinyurl.ignore_regexp =~ url # already shorten
  url_enc = URI.escape(url, /[^a-zA-Z0-9.:]/)
  res = Termtter::HTTPpool.start(host) do |h|
    h.get(format % url_enc)
  end
  if res.code == '200'
    result = res.body
    if /"(http.*?)"/ =~ result
      result = $1
    elsif /"statusCode": "ERROR"/ =~ result
      return nil
    end
    result
  else
    nil
  end
end
swap_timeline_format(format) click to toggle source
# File lib/plugins/stream.rb, line 35
def swap_timeline_format(format)
  original = config.plugins.stdout.timeline_format
  if /\$orig/ =~ format
    format.gsub!(/\$orig/, original)
  end
  config.plugins.stdout.timeline_format = format
  yield
  config.plugins.stdout.timeline_format = original
end
wassr_update(text) click to toggle source
# File lib/plugins/multi_post.rb, line 4
def wassr_update(text)
  if text.match(/^(\d+)\s+(.+)$/) and
      (s = Termtter::API.twitter.show($1) rescue nil)
    tmp_text = "@#{s.user.screen_name} #{$2}"
  else
    tmp_text = text
  end

  Net::HTTP.version_1_2
  req = Net::HTTP::Post.new("/statuses/update.json?")
  req.basic_auth config.plugins.wassr.username, config.plugins.wassr.password
  Net::HTTP.start('api.wassr.jp', 80) do |http|
    res = http.request(req, "status=#{URI.escape(tmp_text)}&source=Termtter")
  end
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.