class Qnap::DownloadStation

Constants

API_METHODS
API_VERSION
APP_NAME
PROTOCOL

Public Class Methods

new(host, username = ENV['QNAP_USERNAME'], password = ENV['QNAP_PASSWORD']) click to toggle source
# File lib/qnap/download_station.rb, line 63
def initialize(host, username = ENV['QNAP_USERNAME'], password = ENV['QNAP_PASSWORD'])

        raise ArgumentError.new("No username defined") if username.nil?
        raise ArgumentError.new("No password defined") if password.nil?

        @host     = host
        @username = username
        @password = password
        @sid      = nil
end
session(*args) { |ds| ... } click to toggle source
# File lib/qnap/download_station.rb, line 20
def self.session(*args)
        ds = self.new *args
        begin
                yield ds
        ensure
                ds.logout
        end
end

Public Instance Methods

get_sid() click to toggle source
# File lib/qnap/download_station.rb, line 59
def get_sid
        @sid ||= misc_login(user: @username, pass: Base64.encode64(@password))[:sid]
end
logout() click to toggle source
# File lib/qnap/download_station.rb, line 29
def logout
        return unless @sid

        data = misc_logout

        @sid = nil
        data
end
misc_login(params={}) click to toggle source
# File lib/qnap/download_station.rb, line 38
def misc_login(params={})
        # override the auto-gen method
        # otherwise `get_sid` is called
        despatch_query(uri_for_path(:misc, :login), params)
end

Private Instance Methods

despatch_query(uri, params) click to toggle source
# File lib/qnap/download_station.rb, line 81
def despatch_query(uri, params)
        req = Net::HTTP::Post.new uri
        req.form_data = params

        response = Net::HTTP.start(
                uri.host,
                uri.port,
                use_ssl: PROTOCOL == 'https',
                verify_mode: OpenSSL::SSL::VERIFY_NONE
        ) do |https|
                https.request req
        end

        data = JSON.parse response.read_body, symbolize_names: true

        if (data.key?(:error) and data[:error] > 0)
                raise RuntimeError.new "Error response from #{uri} -> #{data}"
        end

        data
end
uri_for_path(app, endpoint) click to toggle source
# File lib/qnap/download_station.rb, line 76
def uri_for_path(app, endpoint)
        path = [app, endpoint].map { |s| s.to_s.gsub(/(^|_)(.)/){ $2.upcase } }.join "/"
        URI "#{PROTOCOL}://#{@host}/#{APP_NAME}/#{API_VERSION}/#{path}"
end