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 =
[2, 1, 7]
RCFILE =
File.join(ENV["HOME"], ".titrc")
RTFILE =
File.join(ENV["HOME"], ".titrt")
ATFILE =
File.join(ENV["HOME"], ".titat")
READERS =
[:public, :home, :mentions, :user_timeline, :direct_messages]
WRITERS =
[:update, :new_direct_message]
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",
  :direct_messages => "/direct_messages.xml",
  :new_direct_message => "/direct_messages/new.xml"
}
KEY =
"K2OOlWbQodfm4YV9Fmeg"
SECRET =
"B1HuqK8zoDDLboRAWPqlHTFbLVdkQfquzoUC1MkuM"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTit

Returns a new instance of Tit.



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

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.



124
125
126
# File 'lib/tit.rb', line 124

def opts
  @opts
end

Instance Method Details

#abort(msg) ⇒ Object



363
364
365
366
367
# File 'lib/tit.rb', line 363

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

#error(msg) ⇒ Object



359
360
361
# File 'lib/tit.rb', line 359

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

#get_accessObject



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

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, :tco => true}, 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



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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/tit.rb', line 173

def get_tits(action, payload)
  # Build the API Endpoint
  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")
  
  # I'll use this to decode HTML entities.
  coder = HTMLEntities.new
  
  # Parse XML
  xmlbody = @access_token.get(api_endpoint).body
  
  # Errors
  Nokogiri.XML(xmlbody).xpath("//errors").map do |xml|
    if xml.at_xpath("./error").content == "This application is not allowed to access or delete your direct messages"
      abort("Your OAuth key is not authorized for direct messaging.\nDelete #{TITAT} and run tit without arguments to reauthorize.")
    end
  end
  
  # no errors - get tits
  if action != :direct_messages
    Nokogiri.XML(xmlbody).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 }) unless @prefs[:tco].eql?("TRUE")
            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
  else
    # get the dms
    Nokogiri.XML(xmlbody).xpath("//direct_message").map do |xml|
      {
        :username => xml.at_xpath("./sender/name").content,
        :userid => xml.at_xpath("./sender_screen_name").content,
        :text => xml.xpath("./text").map {|n| coder.decode(n.content)},
        :timestamp => Time.parse(xml.at_xpath("./created_at").content),
        :id => xml.at_xpath("./id").content.to_i,
      }
    end
  end
end

#poll(wait, action, notify) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/tit.rb', line 290

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



323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/tit.rb', line 323

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]
  elsif options[:action] == :new_direct_message
    send_dm options[:payload]
  end
end

#send_dm(payload) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/tit.rb', line 252

def send_dm(payload)
  # Count URLs only as t.co length, not full length.
  if payload["text"].length > 140
    tuts "your message is too long (by #{payload["text"].length - 140} characters)"
    tuts "here is what would get posted:"
    payload["text"][0...140].wrapped(@cols - 2).each { |l| puts "  #{l}" }
    exit(-1)
  end
  
  response = @access_token.post(URLS[:new_direct_message], payload)
  
  # Check the response for errors
  Nokogiri.XML(response).xpath("//hash").map do |xml|
      if xml.at_xpath("./error")
        abort("you cannot send a dm to someone who doesn't follow you")
      end
  end
end

#show_tit(status) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/tit.rb', line 271

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



355
356
357
# File 'lib/tit.rb', line 355

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

#update(payload) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/tit.rb', line 235

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

  # Count URLs only as t.co length, not full length.

  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



337
338
339
340
341
342
343
344
# File 'lib/tit.rb', line 337

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

#update_tco(tco) ⇒ Object



346
347
348
349
350
351
352
353
# File 'lib/tit.rb', line 346

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

#use_pin(pin) ⇒ Object



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

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