Last active
August 15, 2016 07:00
-
-
Save tanelj/fadf23ea1f020dfbed5f to your computer and use it in GitHub Desktop.
This script uploads files to your Voog site over API. More about Voog API: http://www.voog.com/developers/api/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This script uploads files to your Voog site over API. | |
# | |
# Run this script: | |
# | |
# ruby voog_assets_uploader.rb | |
# | |
# Required gems: | |
# gem install voog_api) | |
# gem install mime-types | |
# | |
# More about Voog API: http://www.voog.com/developers/api/ | |
require 'voog_api' # v0.0.11 or newer | |
require 'mime/types' | |
# Your Voog site host | |
@voog_host = 'mycompany.voog.com' | |
# Your Voog API token host | |
# Read more: http://www.voog.com/support/guides/developers/developer-account-basics#generate-api-token | |
@voog_token = 'xxxxxxxxxxxx' | |
@assets_folder = 'assets' # 'assets' | |
# Upload assets to your Voog site. | |
# Existing assets are sipped. | |
def upload_assets(dir) | |
if Dir.exists?(dir) | |
files = Dir.glob(File.join(dir, '*.*')) | |
puts "Processing #{files.size} files:\n" | |
files.each.with_index(1) do |file, index| | |
filename = File.basename(file) | |
if file_by_name(filename) | |
puts "#{index}: #{file} - (SKIPPING)" | |
next | |
end | |
sleep 5 if index % 10 == 0 | |
sleep 10 if index % 100 == 0 | |
mime_type = MIME::Types.type_for(file).first | |
content_type = mime_type ? mime_type.content_type : 'application/octet-stream' | |
puts "#{index}: #{file} - (#{File.size(file)} - #{content_type})..." | |
asset = client.create_asset(filename: filename, size: File.size(file), content_type: content_type) | |
conn = Faraday.new() do |f| | |
f.adapter :net_http | |
end | |
conn.headers[:x_amz_acl] = 'public-read' | |
conn.headers[:content_type] = content_type | |
conn.headers[:content_length] = File.size(file).to_s | |
response = conn.put(asset.upload_url, Faraday::UploadIO.new(file, content_type)) | |
if response.success? | |
client.confirm_asset(asset.id) | |
else | |
puts "Error on uploading to S3: #{response.body.inspect}" | |
end | |
end | |
end | |
end | |
# Get list of existing assets. | |
def assets | |
@assets ||= client.assets | |
end | |
# Check existing files | |
def file_by_name(filename) | |
@file_by_name ||= assets.each_with_object({}) { |e, h| h[e.filename] = e } | |
@file_by_name[filename] | |
end | |
# Return Voog API client | |
def client | |
@client ||= Voog::Client.new(@voog_host, @voog_token, protocol: :http, auto_paginate: true, raise_on_error: true) | |
end | |
def clear_cache! | |
@assets = nil | |
@file_by_name = nil | |
@client = nil | |
end | |
clear_cache! | |
upload_assets(@assets_folder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment