#!/usr/bin/env ruby # coding: utf-8 require "pupil" require "pupil/keygen" require "yaml" require "fileutils" require "readline" require "optparse" require "pp" class String def undent gsub /^.{#{slice(/^ +/).length}}/, '' end end class Eyedrops VERSION = "1.0" end class Credentials attr_accessor :credentials def initialize(file) FileUtils.touch file unless FileTest.exists? file @credentials_file = file @credentials = YAML.load_file(file) end def save YAML.dump(@credentials, File.open(@credentials_file, "w")) end def create token = Pupil::Keygen.new.interactive @credentials ||= Hash.new @credentials.update({token[:screen_name] => token.reject{|k, v| k == :screen_name }}) self.save return token end end def display_help puts <<-EOD.undent Usage: eyedrops [OPTIONS] eyedrops> twitter #=> Prepared Pupil instance options: -i, --inspect\tDisplay inspected results -a name, --account name\tSign-in account name -h, --help\tShow help -v, --version\tShow version eyedrops commands: help\tShow help quit\tExit eyedrops show-account\tDisplay active account EOD end # Initialize home_dir = `echo $HOME`.strip eyedrops_dir = File.join(home_dir, ".eyedrops") credentials_file = File.join(eyedrops_dir, "credentials") Dir.mkdir eyedrops_dir unless FileTest.exists? eyedrops_dir cred = Credentials.new(credentials_file) unless cred.credentials cred.create end ProgramConfig = Hash.new OptionParser.new do |opts| opts.on("-i", "--inspect") do ProgramConfig[:inspect] = true end opts.on("-u", "--user [USER]") do |user| ProgramConfig[:user] = user end opts.on("-h", "--help") do display_help exit end opts.on("-v", "--version") do puts "Eyedrops #{Eyedrops::VERSION} with Pupil-#{Pupil::VERSION}" exit end opts.parse!(ARGV) end puts "Eyedrops, the interactive Pupil | Version: Eyedrops-#{Eyedrops::VERSION} with Pupil-#{Pupil::VERSION}" # Account selecting if ProgramConfig[:user] account = ProgramConfig[:user] else num = 1 cred.credentials.keys.each do |name| puts "#{num}. #{name}" num += 1 end puts "#{num}. Add Account" sel = Readline.readline("Choose account: ", false).to_i if sel == cred.credentials.keys.size + 1 cred.create sel = cred.credentials.keys.size end account = cred.credentials.keys[sel-1] end puts "Preparing Pupil instance..." twitter = Pupil.new(cred.credentials[account]) puts "Signed with @#{account}" while(true) begin line = Readline.readline("eyedrops> ", true) break if line =~ /^(exit|quit)$/ arr = line.split(" ") command = arr.first option = arr[1, arr.size] case command.to_sym when :help display_help when :"show-account" puts "Signed with @#{account}" else result = eval(line) puts "=> #{result.inspect}" if ProgramConfig[:inspect] end rescue => exception puts exception end end