Class: Gyunyu::Token

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
lib/gyunyu/token.rb

Constant Summary collapse

API_KEY =
'0af285d87a0798cdd4751acfb02fc058'
SHARED_SECRET =
'f0611feb04a04e1d'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeToken

Returns a new instance of Token.



10
11
12
# File 'lib/gyunyu/token.rb', line 10

def initialize
  RTM::API.init( API_KEY, SHARED_SECRET )
end

Class Method Details

.getObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/gyunyu/token.rb', line 14

def self.get
  @self = self.new
  token = @self.load

  if ( !token )
    token = @self.request
    @self.save( token )
  end

  RTM::API.token = token
  token
end

.purgeObject



27
28
29
30
31
32
33
34
# File 'lib/gyunyu/token.rb', line 27

def self.purge
  RTM::API.token = nil
  self.new.instance_eval {
    while ( File.exist?( magazine ) )
      rm( magazine )
    end
  }
end

Instance Method Details

#dotfileObject



73
74
75
# File 'lib/gyunyu/token.rb', line 73

def dotfile
  File.join( ENV['HOME'], '.gyunyu' )
end

#envObject



69
70
71
# File 'lib/gyunyu/token.rb', line 69

def env
  ENV['RTMSTAT_TOKEN']
end

#loadObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/gyunyu/token.rb', line 50

def load
  token = nil

  if ( File.exist?( magazine ) )
    open( magazine, 'r+b' ) { |f|
      # TODO WARN if permission is too loose
      f.flock( File::LOCK_SH )
      token = f.read
      f.flock( File::LOCK_UN )
    }
  end

  token
end

#magazineObject



65
66
67
# File 'lib/gyunyu/token.rb', line 65

def magazine
  env || dotfile
end

#requestObject



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/gyunyu/token.rb', line 77

def request
  frob = RTM::Auth::GetFrob.new.invoke
  url  = RTM::API.get_auth_url('read', frob)
  puts "open RTM with browser and accept API KEY."
  puts "and hit enter."
  system("open '#{url}'")
  STDIN.gets

  res = RTM::Auth::GetToken.new(frob).invoke
  res[:token]
end

#save(token) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/gyunyu/token.rb', line 36

def save( token )
  if ( !File.exist?( magazine ) )
    open( magazine, 'w', 0600 ) { }
  end

  open( magazine, 'r+b', 0600 ) { |f|
    f.flock( File::LOCK_EX )
    f.truncate(0)
    f.print token
    f.flock( File::LOCK_UN )
  }
  token
end