Class: Neocities::Client

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

Constant Summary collapse

API_URI =
'https://neocities.org/api/'

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client

Returns a new instance of Client.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/neocities/client.rb', line 16

def initialize(opts={})
  @uri = URI.parse API_URI
  @http = HTTPClient.new force_basic_auth: true
  @opts = opts

  unless opts[:api_key] || (opts[:sitename] && opts[:password])
    raise ArgumentError, 'client requires a login (sitename/password) or an api_key'
  end

  if opts[:api_key]
    @http.default_header = {'Authorization' => "Bearer #{opts[:api_key]}"}
  else
    @http.set_auth API_URI, opts[:sitename], opts[:password]
  end

end

Instance Method Details

#delete(*paths) ⇒ Object



65
66
67
# File 'lib/neocities/client.rb', line 65

def delete(*paths)
  post 'delete', 'filenames[]' => paths
end

#get(path, params = {}) ⇒ Object



73
74
75
76
77
78
# File 'lib/neocities/client.rb', line 73

def get(path, params={})
  uri = @uri+path
  uri.query = URI.encode_www_form params
  resp = @http.get uri
  JSON.parse resp.body, symbolize_names: true
end

#info(sitename) ⇒ Object



69
70
71
# File 'lib/neocities/client.rb', line 69

def info(sitename)
  get 'info', sitename: sitename
end

#keyObject



37
38
39
# File 'lib/neocities/client.rb', line 37

def key
  get 'key'
end

#list(path = nil) ⇒ Object



33
34
35
# File 'lib/neocities/client.rb', line 33

def list(path=nil)
  get 'list', :path => path
end

#post(path, args = {}) ⇒ Object



80
81
82
83
84
# File 'lib/neocities/client.rb', line 80

def post(path, args={})
  uri = @uri+path
  resp = @http.post uri, args
  JSON.parse resp.body, symbolize_names: true
end

#upload(path, remote_path = nil) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/neocities/client.rb', line 45

def upload(path, remote_path=nil)
  path = Pathname path

  unless path.exist?
    raise ArgumentError, "#{path.to_s} does not exist."
  end

  rpath = (remote_path || path.basename)

  res = upload_hash rpath, Digest::SHA1.file(path.to_s).hexdigest

  if res[:files] && res[:files][remote_path.to_s.to_sym] == true
    return {result: 'error', error_type: 'file_exists', message: 'file already exists and matches local file, not uploading'}
  else
    File.open(path.to_s) do |file|
      post 'upload', rpath => file
    end
  end
end

#upload_hash(remote_path, sha1_hash) ⇒ Object



41
42
43
# File 'lib/neocities/client.rb', line 41

def upload_hash(remote_path, sha1_hash)
  post 'upload_hash', remote_path => sha1_hash
end