Class: Tit

Inherits:
Object
  • Object
show all
Defined in:
lib/tit.rb

Overview

Why are you reading the documentation, you cunt?

Constant Summary collapse

VERSION =
[1, 2, 3]
RCFILE =
File.join(ENV["HOME"], ".titrc")
RTFILE =
File.join(ENV["HOME"], ".titrt")
ATFILE =
File.join(ENV["HOME"], ".titat")
READERS =
[:public, :home, :mentions, :user_timeline]
WRITERS =
[:update]
URLS =
{
  :public => "/statuses/public_timeline.xml",
  :home => "/statuses/home_timeline.xml",
  :mentions => "/statuses/mentions.xml",
  :user_timeline => "/statuses/user_timeline.xml",
  :update => "/statuses/update.xml"
}
KEY =
"K2OOlWbQodfm4YV9Fmeg"
SECRET =
"B1HuqK8zoDDLboRAWPqlHTFbLVdkQfquzoUC1MkuM"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTit

Returns a new instance of Tit.



114
115
116
117
118
119
120
121
# File 'lib/tit.rb', line 114

def initialize
  @consumer = OAuth::Consumer.new(KEY, SECRET,
                                  { :site => "https://twitter.com" })
  # get terminal width
  @cols = %x[tput cols].to_i
  # get status count
  @prefs = YAML.load_file(RCFILE)
end

Instance Attribute Details

#optsObject

Returns the value of attribute opts.



122
123
124
# File 'lib/tit.rb', line 122

def opts
  @opts
end

Instance Method Details

#abort(msg) ⇒ Object



300
301
302
303
304
# File 'lib/tit.rb', line 300

def abort(msg)
  error(msg)
  puts @opts
  exit(-1)
end

#error(msg) ⇒ Object



296
297
298
# File 'lib/tit.rb', line 296

def error(msg)
  tuts "#{File.basename $0}: #{msg}"
end

#get_accessObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/tit.rb', line 124

def get_access
  begin
    @access_token = File.open(ATFILE, "r") do |at|
      params = YAML.load(at)
      @userid = params[:screen_name]
      OAuth::AccessToken.from_hash(@consumer, params)
    end
  rescue Errno::ENOENT => e
    request_token = @consumer.get_request_token
    File.open(RTFILE, "w") do |rt|
      YAML.dump(request_token.params, rt)
    end
    File.open(RCFILE, "w") do |rc|
      YAML.dump({count: 10}, rc)
    end
    tuts "Please visit '#{request_token.authorize_url}'."
    tuts "When you finish, provide your pin with `tit --pin PIN'"
    exit(0)
  end
end

#get_tits(action, payload) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/tit.rb', line 171

def get_tits(action, payload)
  api_endpoint = URLS[action]
  if(action == :user_timeline and not payload.nil?)
    api_endpoint.concat("?screen_name=".concat(payload['user'])).concat("&count=#{@prefs[:count]}")
  else
    api_endpoint.concat("?count=#{@prefs[:count]}")
  end
  api_endpoint.concat("&include_entities=true")
  coder = HTMLEntities.new
  Nokogiri.XML(@access_token.get(api_endpoint).body).xpath("//status").map do |xml|
    {
      :username => xml.at_xpath("./user/name").content,
      :userid => xml.at_xpath("./user/screen_name").content,
      :text => xml.xpath("./text").map do |n|
        txt = coder.decode(n.content)
        if not xml.xpath("./entities/urls").nil?
          xml.xpath("./entities/urls/url").map do |url| 
            txt.replace_with_expanded_url! (url.xpath("./expanded_url").map { |expurl| expurl.content })
          end
        end
        txt
      end,
      :timestamp => Time.parse(xml.at_xpath("./created_at").content),
      :id => xml.at_xpath("./id").content.to_i,
      :geo => xml.at_xpath("./geo").instance_eval do
        unless children.empty?
          n, e = children[1].content.split.map { |s| s.to_f }
          "#{n.abs}#{n >= 0 ? 'N' : 'S'} #{e.abs}#{e >= 0 ? 'E' : 'W'}"
        end
      end
    }
  end
end

#poll(wait, action, notify) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/tit.rb', line 239

def poll(wait, action, notify)
  tits = {}
  get_tits(action).reverse.each do |status|
    show_tit(status)
    tits[status[:id]] = status
  end
  last_update = Time.now()
  loop do
    print "\r", " " * (s = "Last update was at #{last_update.strftime "%X"}, " +
                       "next update at #{(Time.now + wait).strftime "%X"}"
                       print s
                       STDOUT.flush
                       sleep(wait)
                       s.length), "\r"
    begin
      num_tits = get_tits(action).reverse.reject do |status|
        tits.include? status[:id]
      end.each_with_index do |status, i|
        if i == 0
          tuts "more updates (at #{Time.now.strftime "%X"}):"
          puts ""
        end
        show_tit(status)
        tits[status[:id]] = status
      end.length
      %x[#{notify} '#{num_tits} new tit#{num_tits == 1 ? '' : 's'}!'] unless notify.nil? or num_tits == 0
      last_update = Time.now()
    rescue SocketError, Errno::ENETUNREACH, Errno::ETIMEDOUT, NoMethodError => e
      tuts "networking error, will try again later"
    end
  end
end

#run(options) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
# File 'lib/tit.rb', line 272

def run(options)
  if READERS.include? options[:action]
    if options[:wait].nil?
      get_tits(options[:action], options[:payload]).reverse.each &method(:show_tit)
    else
      poll(options[:wait], options[:action], options[:notify])
    end
  elsif options[:action] == :update
    update options[:payload]
  end
end

#show_tit(status) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/tit.rb', line 220

def show_tit(status)
  person = if status[:userid].eql? @userid
             "you"
           else
             "#{status[:username]} (#{status[:userid]})"
           end
  at = status[:timestamp].time_ago_in_words
  if status[:geo].nil?
    tuts "#{person} said, #{at}:"
  else
    tuts "#{person} said, #{at}, from #{status[:geo]}:"
  end

  status[:text].each do |line|
    line.wrapped(@cols - 2).each { |l| puts "  #{l}" }
  end
  puts ""
end

#tuts(*strs) ⇒ Object



292
293
294
# File 'lib/tit.rb', line 292

def tuts(*strs)
  strs.each { |s| puts s.to_s.wrapped(@cols) }
end

#update(payload) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/tit.rb', line 205

def update(payload)
  if payload["status"] == STDIN
    payload["status"] = STDIN.read
  end

  if payload["status"].length > 140
    tuts "your status is too long (by #{payload["status"].length - 140} characters)"
    tuts "here is what would get posted:"
    payload["status"][0...140].wrapped(@cols - 2).each { |l| puts "  #{l}" }
    exit(-1)
  end

  @access_token.post(URLS[:update], payload)
end

#update_count(count) ⇒ Object



284
285
286
287
288
289
290
# File 'lib/tit.rb', line 284

def update_count(count)
  @prefs[:count] = count
  File.open(RCFILE, "w") do |rc|
    YAML.dump(@prefs, rc)
  end
  exit(0)
end

#use_pin(pin) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/tit.rb', line 145

def use_pin(pin)
  begin
    request_token = File.open(RTFILE, "r") do |rt|
      params = YAML.load(rt)
      OAuth::RequestToken.from_hash(@consumer, params)
    end
  rescue Errno::ENOENT => e
    tuts "You lost your old token, gotta try again."
    get_access
  end
  begin
    @access_token = request_token.get_access_token(:oauth_verifier => pin)
  rescue OAuth::Unauthorized => e
    tuts "Sorry, that's an old pin."
    File.delete(RTFILE)
    get_access
  end
  File.open(ATFILE, "w") do |at|
    YAML.dump(@access_token.params, at)
  end
  File.delete(RTFILE)
  tuts "Thanks, you're done with authentication."
  tuts "Keep #{ATFILE} secure and intact.  If it's compromised, I can't " +
    "revoke your token."
end