Class: CDNConnect::APIClient
- Inherits:
-
Object
- Object
- CDNConnect::APIClient
- Defined in:
- lib/cdnconnect_api.rb
Overview
Used to easily interact with CDN Connect API.
Constant Summary collapse
- @@application_name =
'cdnconnect-api-ruby'
- @@application_version =
'0.3.3'
- @@user_agent =
@@application_name + ' v' + @@application_version
- @@api_host =
'https://api.cdnconnect.com'
- @@api_version =
'v1'
Instance Method Summary collapse
-
#access_token ⇒ String
OAuth2 value.
-
#app_host ⇒ String
The CDN Connect App host.
-
#client_id ⇒ String
OAuth2 parameter.
-
#client_secret ⇒ String
OAuth2 parameter.
-
#code ⇒ String
OAuth2 value.
-
#create_path(options = {}) ⇒ APIResponse
Create a folder path.
-
#delete(api_path) ⇒ APIResponse
Executes a DELETE request to an API URL and returns a response object.
-
#delete_object(options = {}) ⇒ APIResponse
Delete object info, which can be either a file or folder.
-
#failed_uploads ⇒ Array
An array of files which failed.
-
#get(api_path, data = {}) ⇒ APIResponse
Executes a GET request to an API URL and returns a response object.
-
#get_object(options = {}) ⇒ APIResponse
Get object info, which can be either a file or folder.
- #human_file_size(bytes) ⇒ Object
-
#initialize(options = {}) ⇒ APIClient
constructor
Creates a client to authorize interactions with the API using the OAuth 2.0 protocol.
-
#post(api_path, data) ⇒ APIResponse
Executes a POST request to an API URL and returns a response object.
-
#put(api_path, data) ⇒ APIResponse
Executes a PUT request to an API URL and returns a response object.
-
#redirect_uri ⇒ String
OAuth2 value.
-
#rename_object(options = {}) ⇒ APIResponse
Rename object, which can be either a file or folder.
-
#scope ⇒ String
OAuth2 parameter.
-
#state ⇒ String
OAuth2 parameter.
-
#upload(options = {}) ⇒ APIResponse
Upload a file or multiple files from a local machine to a folder within a CDN Connect app.
Constructor Details
#initialize(options = {}) ⇒ APIClient
Creates a client to authorize interactions with the API using the OAuth 2.0 protocol. This can be given a known API Key (access_token) or can use OAuth 2.0 web application flow designed for 3rd party web sites (clients).
73 74 75 76 77 78 79 80 81 82 83 84 85 86 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 |
# File 'lib/cdnconnect_api.rb', line 73 def initialize(={}) # Normalize key to String to allow indifferent access. = .inject({}) { |accu, (k, v)| accu[k.to_s] = v; accu } # Initialize all of the options @client_id = ["client_id"] @client_secret = ["client_secret"] @scope = ["scope"] @state = ["state"] @code = ["code"] @redirect_uri = ["redirect_uri"] ["access_token"] = ["access_token"] || ["api_key"] # both work @access_token = ["access_token"] @app_host = ["app_host"] @@api_host = ["api_host"] || @@api_host @prefetched_upload_urls = {} @upload_queue = {} @failed_uploads = [] log_device = ["log_device"] || STDOUT @logger = Logger.new(log_device, 10, 1024000) @logger.sev_threshold = ["log_sev_threshold"] || Logger::WARN if ["api_key"] != nil and ["app_host"] == nil err_msg = 'app_host option required when using api_key option' @logger.error(err_msg) raise ArgumentError, err_msg end @logger.debug("#{@@user_agent}, #{@@api_host}") # Create the OAuth2 client which will be used to authorize the requests @client = Signet::OAuth2::Client.new(:client_id => client_id, :client_secret => @client_secret, :scope => @scope, :state => @state, :code => @code, :redirect_uri => @redirect_uri, :access_token => @access_token) return self end |
Instance Method Details
#access_token ⇒ String
OAuth2 value. An API Key (commonly known as an access_token) which was previously created within CDN Connect’s account for a specific app.
865 866 867 |
# File 'lib/cdnconnect_api.rb', line 865 def access_token @access_token end |
#app_host ⇒ String
The CDN Connect App host. For example, demo.cdnconnect.com is a CDN Connect app host. The app host value should not include https://, http:// or a URL path.
875 876 877 |
# File 'lib/cdnconnect_api.rb', line 875 def app_host @app_host end |
#client_id ⇒ String
OAuth2 parameter. A unique identifier issued to the client to identify itself to CDN Connect’s authorization server. This is issued by CDN Connect to external clients. This is only needed if an API Key isn’t already known.
805 806 807 |
# File 'lib/cdnconnect_api.rb', line 805 def client_id @client_id end |
#client_secret ⇒ String
OAuth2 parameter. A secret issued by the CDN Connect’s authorization server, which is used to authenticate the client. Do not confuse this is an access_token or an api_key. This is only required if an API Key isn’t already known. A client secret should not be shared.
817 818 819 |
# File 'lib/cdnconnect_api.rb', line 817 def client_secret @client_secret end |
#code ⇒ String
OAuth2 value. The authorization code received from the authorization server.
847 848 849 |
# File 'lib/cdnconnect_api.rb', line 847 def code @code end |
#create_path(options = {}) ⇒ APIResponse
Create a folder path. If any of the folders within the given path do not already exist they will be created.
687 688 689 690 |
# File 'lib/cdnconnect_api.rb', line 687 def create_path(={}) api_path = [:path] + '/create-path.json' get(api_path) end |
#delete(api_path) ⇒ APIResponse
Executes a DELETE request to an API URL and returns a response object. DELETE requests are used when (you guessed it) deleting data.
735 736 737 |
# File 'lib/cdnconnect_api.rb', line 735 def delete(api_path) fetch(:api_path => api_path, :method => 'DELETE') end |
#delete_object(options = {}) ⇒ APIResponse
Delete object info, which can be either a file or folder.
676 677 678 679 |
# File 'lib/cdnconnect_api.rb', line 676 def delete_object(={}) api_path = [:path] + '.json' delete(api_path) end |
#failed_uploads ⇒ Array
An array of files which failed.
893 894 895 |
# File 'lib/cdnconnect_api.rb', line 893 def failed_uploads @failed_uploads end |
#get(api_path, data = {}) ⇒ APIResponse
Executes a GET request to an API URL and returns a response object. GET requests are used when reading data.
700 701 702 |
# File 'lib/cdnconnect_api.rb', line 700 def get(api_path, data={}) fetch(:api_path => api_path, :method => 'GET', :data => data) end |
#get_object(options = {}) ⇒ APIResponse
Get object info, which can be either a file or folder.
640 641 642 643 644 645 646 647 648 649 650 |
# File 'lib/cdnconnect_api.rb', line 640 def get_object(={}) api_path = [:path] + '.json' data = {} if [:files] == true data[:files] = true end if [:folders] == true data[:folders] = true end get(api_path, data) end |
#human_file_size(bytes) ⇒ Object
897 898 899 900 901 902 903 904 905 906 |
# File 'lib/cdnconnect_api.rb', line 897 def human_file_size(bytes) begin units = %w{B KB MB GB TB} e = (Math.log(bytes)/Math.log(1024)).floor s = "%.2f" % (bytes.to_f / 1024**e) s.sub(/\.?0*$/, units[e]) rescue bytes end end |
#post(api_path, data) ⇒ APIResponse
Executes a POST request to an API URL and returns a response object. POST requests are used when creating data.
712 713 714 |
# File 'lib/cdnconnect_api.rb', line 712 def post(api_path, data) fetch(:api_path => api_path, :method => 'POST', :data => data) end |
#put(api_path, data) ⇒ APIResponse
Executes a PUT request to an API URL and returns a response object. PUT requests are used when updating data.
724 725 726 |
# File 'lib/cdnconnect_api.rb', line 724 def put(api_path, data) fetch(:api_path => api_path, :method => 'PUT', :data => data) end |
#redirect_uri ⇒ String
OAuth2 value. The redirection URI used in the initial request.
855 856 857 |
# File 'lib/cdnconnect_api.rb', line 855 def redirect_uri @redirect_uri end |
#rename_object(options = {}) ⇒ APIResponse
Rename object, which can be either a file or folder.
662 663 664 665 666 |
# File 'lib/cdnconnect_api.rb', line 662 def rename_object(={}) api_path = [:path] + '/rename.json' data = { :new_name => [:new_name] } put(api_path, data) end |
#scope ⇒ String
OAuth2 parameter. The scope of the access request, expressed either as an Array or as a space-delimited String. This is only required if an API Key isn’t already known.
828 829 830 |
# File 'lib/cdnconnect_api.rb', line 828 def scope @scope end |
#state ⇒ String
OAuth2 parameter. An unguessable random string designed to allow the client to maintain state to protect against cross-site request forgery attacks. This is only required if an API Key isn’t already known.
839 840 841 |
# File 'lib/cdnconnect_api.rb', line 839 def state @state end |
#upload(options = {}) ⇒ APIResponse
Upload a file or multiple files from a local machine to a folder within a CDN Connect app. The upload method provides numerous ways to upload files or files, to include recursively drilling down through local folders and uploading only files that match your chosen extensions. If any of the folders within the upload path do not already exist then they will be created automatically.
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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'lib/cdnconnect_api.rb', line 175 def upload(={}) # Make sure we've got good source data before starting the upload prepare_upload() # Place all of the source files in an upload queue for each destination folder. # Up to 25 files can be sent in one POST request. As uploads are successful # the files will be removed from the queue and uploading will stop when # each directory's upload queue is empty. build_upload_queue() # The returning response object. Its empty to start with then as # uploads complete it fills this up with each upload's response info api_response = CDNConnect::APIResponse.new() # If there are files in the upload_queue then start the upload process while @upload_queue.length > 0 # Get the destination_path in the list of upload queues destination_path = @upload_queue.keys[0] @logger.debug("destination_path: #{destination_path}") # Check if we have a prefetched upload url before requesting a new one upload_url = get_prefetched_upload_url(destination_path) if upload_url == nil # We do not already have an upload url created. The first upload request # will need to make a request for an upload url. After the first upload # each upload response will also include a new upload url which can be used # for the next upload when uploading to the same folder. upload_url_response = self.get_upload_url(destination_path) if upload_url_response.is_error return upload_url_response end upload_url = upload_url_response.get_result('upload_url') upload_id = upload_url_response.get_result('upload_id') @logger.debug("Received new upload url, #{upload_id}") else @logger.debug("Use prefetched upload url") end # Build the data that gets sent in the POST request post_data = build_post_data(:destination_path => destination_path, :destination_file_name => [:destination_file_name], :queue_processing => .fetch(:queue_processing, true), :create_upload_url => .fetch(:create_upload_url, true), :webhook_url => [:webhook_url], :webhook_format => [:webhook_format]) # Build the request to send to the API # Uses the Faraday: https://github.com/lostisland/faraday conn = Faraday.new() do |req| req.headers = { 'User-Agent' => @@user_agent } req.request :multipart req.adapter :net_http end # Kick off the request! http_response = conn.post upload_url, post_data # w00t! Convert the http response into APIResponse and see what's up upload_response = APIResponse.new(http_response) for msg in upload_response.msgs @logger.info("Upload " + msg["status"] + ": " + msg["text"]) end # merge the two together so we build one awesome response # object with everything you need to know about every upload api_response.merge(upload_response) # Read the response and see what we got if upload_response.is_server_error # There was a server error, empty the active upload queue failed_upload_attempt(destination_path) @logger.error(upload_response.body) # put the upload url back in the list # of prefetched urls so it can be reused set_prefetched_upload_url(destination_path, upload_url) else # successful upload, clear out the active upload queue # and remove uploaded files from the upload queue successful_upload_attempt(destination_path) @logger.info("Successful upload") # an upload response also contains a new upload url. # Save it for the next upload to the same destination. new_upload_url = upload_response.get_result('upload_url') new_upload_id = upload_response.get_result('upload_url_upload_id') if new_upload_url != nil @logger.debug("Received upload url in upload response, #{new_upload_id}") set_prefetched_upload_url(destination_path, new_upload_url) end end end return api_response end |