Class: NotehubAPI

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

Constant Summary collapse

API_VERSION =
"1.4"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ NotehubAPI



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/notehub/notehub.rb', line 31

def initialize(opts={})

  opts['config_location'] ||= "#{ENV['HOME']}/.notehub"
  opts['config_file'] ||= "#{opts['config_location']}/config.yml"
  opts['notes_db'] ||= "#{opts['config_location']}/notes.db"

  config_file = opts['config_file']
  @notes_db = opts['notes_db']

  # Set up config
  FileUtils.mkdir_p(opts['config_location'],:mode => 0755) unless File.directory? opts['config_location']
  unless File.exists?(config_file)
    new_config = {
      'publisher_id' => "your_publisher_id",
      'secret_key' => "your_secret_key",
      'default_password' => "default password for editing notes",
      'default_theme' => "light",
      'default_font' => 'Georgia'
    }.to_yaml

    File.open(config_file, 'w') { |yf| YAML::dump(new_config, yf) }
  end

  config = YAML.load_file(config_file)
  @pid = config['publisher_id']
  @psk = config['secret_key']
  if config['default_password'] && config['default_password'].length > 0
    @default_password = config['default_password']
  else
    @default_password = false
  end
  @default_theme = config['default_theme'] || 'light'
  @default_font = config['default_font'] || 'Georgia'
  @default_header_font = config['default_header_font'] || 'Georgia'

  # verify config
  if @pid == "your_publisher_id" || @psk == "your_secret_key"
    puts "Please edit #{config_file} and run again"
    Process.exit 1
  end

  # set up notes database
  unless File.exists?(@notes_db)
    new_db = {'notes' => {}}
    File.open(@notes_db, 'w') { |yf| YAML::dump(new_db, yf) }
  end

  # load existing notes
  @notes = YAML.load_file(@notes_db)
end

Instance Attribute Details

#default_fontObject (readonly)

Returns the value of attribute default_font.



29
30
31
# File 'lib/notehub/notehub.rb', line 29

def default_font
  @default_font
end

#default_header_fontObject (readonly)

Returns the value of attribute default_header_font.



29
30
31
# File 'lib/notehub/notehub.rb', line 29

def default_header_font
  @default_header_font
end

#default_passwordObject (readonly)

Returns the value of attribute default_password.



29
30
31
# File 'lib/notehub/notehub.rb', line 29

def default_password
  @default_password
end

#default_themeObject (readonly)

Returns the value of attribute default_theme.



29
30
31
# File 'lib/notehub/notehub.rb', line 29

def default_theme
  @default_theme
end

#notesObject (readonly)

Returns the value of attribute notes.



29
30
31
# File 'lib/notehub/notehub.rb', line 29

def notes
  @notes
end

Instance Method Details

#choose_note(term = ".*") ⇒ Object



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

def choose_note(term=".*")
  # TODO: If there's input on STDIN, gets fails. Use highline?
  puts "Choose a note:"

  list = find_notes(term)
  list.each_with_index { |note, i| puts "% 3d: %s" % [i+1, note['title']] }
  # list.each_with_index { |f,i| puts "% 3d: %s" % [i+1, f] }
  num = ask("Which note?  ", Integer) { |q| q.in = 1..list.length }

  return false if num =~ /^[a-z ]*$/i

  list[num.to_i - 1]
end

#find_notes(term = ".*") ⇒ Object



227
228
229
230
231
232
233
234
235
# File 'lib/notehub/notehub.rb', line 227

def find_notes(term=".*")
  term.gsub!(/\s+/,".*?")
  found_notes = []
  @notes['notes'].each {|k, v|
    v['id'] = k
    found_notes.push(v) if v['title'] =~ /#{term}/i
  }
  found_notes
end

#get_api(params) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/notehub/notehub.rb', line 117

def get_api(params)
  params['version'] = API_VERSION

  uri = URI("http://www.notehub.org/api/note#{params.to_query}")

  Net::HTTP.start(uri.host, uri.port) do |http|
    req = Net::HTTP::Get.new uri
    res = http.request req
    if res && res.code == "200"
      json = JSON.parse(res.body)
      if json['status']['success']
        return json
      else
        raise "GET request returned error: #{json['status']['message']}"
      end
    else
      p res.body if res
      raise "Error retrieving GET request to API"
    end
  end
end

#list_notes(term = ".*") ⇒ Object



220
221
222
223
224
225
# File 'lib/notehub/notehub.rb', line 220

def list_notes(term=".*")
  notes = find_notes(term)
  notes.each {|note|
    puts "> #{note['title']} [ #{note['id']} ]"
  }
end

#new_note(text, pass = false, options = {}) ⇒ Object



139
140
141
142
143
144
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
170
171
172
173
174
175
# File 'lib/notehub/notehub.rb', line 139

def new_note(text, pass=false, options={})
  options[:theme] ||= nil
  options[:font] ||= nil

  params = {}
  params['note'] = text.strip
  params['pid'] = @pid
  params['signature'] = Digest::MD5.hexdigest(@pid + @psk + text.strip)
  params['password'] = Digest::MD5.hexdigest(pass) if pass
  params['version'] = API_VERSION

  params['theme'] = options[:theme] unless options[:theme].nil?
  params['text-font'] = options[:font] unless options[:font].nil?
  params['header-font'] = options[:header_font] unless options[:header_font].nil?

  res = post_api(params)

  if res && res['status']['success']
    note_data = read_note(res['noteID'])
    note = {
      'title' => note_data['title'][0..80],
      'id' => res['noteID'],
      'url' => res['longURL'],
      'short' => res['shortURL'],
      'stats' => note_data['statistics'],
      'pass' => pass || ""
    }
    store_note(note)
    return note
  else
    if res
      raise "Failed: #{res['status']['comment']} "
    else
      raise "Failed to create note"
    end
  end
end

#post_api(params, action = "post") ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/notehub/notehub.rb', line 87

def post_api(params, action="post")
  uri = URI("http://www.notehub.org/api/note")

  if action == "put"
    req = Net::HTTP::Put.new(uri)
  else
    req = Net::HTTP::Post.new(uri)
  end
  req.set_form_data(params)

  res = Net::HTTP.start(uri.hostname, uri.port) do |http|
    http.request(req)
  end

  case res
  when Net::HTTPSuccess, Net::HTTPRedirection
    json = JSON.parse(res.body)
    if json['status']['success']
      return json
    else
      raise "POST request returned error: #{json['status']['message']}"
    end
  else
    # res.value
    p res.body if res
    raise "Error retrieving POST request to API"
  end
  # res = Net::HTTP.post_form(uri, params)
end

#read_note(id) ⇒ Object



215
216
217
218
# File 'lib/notehub/notehub.rb', line 215

def read_note(id)
  params = {'noteID' => id}
  get_api(params)
end

#store_note(note) ⇒ Object



82
83
84
85
# File 'lib/notehub/notehub.rb', line 82

def store_note(note)
  @notes['notes'][note['id']] = note
  File.open(@notes_db, 'w') { |yf| YAML::dump(@notes, yf) }
end

#update_note(id, text, pass = false) ⇒ Object



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
# File 'lib/notehub/notehub.rb', line 177

def update_note(id, text, pass=false)
  # TODO: Signature invalid
  params = {}
  pass ||= @default_password
  # raise "Password required for update" unless pass

  md5_pass = Digest::MD5.hexdigest(pass)

  params['password'] =  md5_pass
  params['noteID'] = id
  params['note'] = text.strip
  params['pid'] = @pid
  sig = @pid + @psk + id + text.strip + md5_pass
  params['signature'] = Digest::MD5.hexdigest(sig)
  params['version'] = API_VERSION
  res = post_api(params,"put")

  if res && res['status']['success']
    note_data = read_note(id)
    note = {
      'title' => note_data['title'][0..80].strip,
      'id' => id,
      'url' => res['longURL'],
      'short' => res['shortURL'],
      'stats' => note_data['statistics'],
      'pass' => pass || ""
    }
    store_note(note)
    return note
  else
    if res
      raise "Failed: #{res['status']['comment']} "
    else
      raise "Failed to update note"
    end
  end
end