Images not loading in emails with CDN Hosts url rails - ruby

I recently moved all my app assets to CDN and everything is working fine. All images are loading in views. But my problem is my images are not loading in emails which I am sending from my application. I have specified my CDN Path in production.rb file also but still not working. When I inspect that image in email, I didn't even getting src for that image.
I am loading my images using image_tag.
Can anyone please help me on this:
Production.rb:
config.action_controller.asset_host = AssetsCdn.new
config.action_mailer.asset_host = AssetsCdn.new
config.action_mailer.default_url_options = { :host => 'localhost', :protocol => 'http' }
config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = false config.action_mailer.default :charset => "utf-8"
config.action_mailer.delivery_method = :smtp #:mailhopper
AssetsCdn Class:
require 'zlib'
class AssetsCdn
CSS_CDN = "cdn-css"
CSS_CDN_0 = "cdn-css0"
CSS_CDN_1 = "cdn-css1"
CSS_CDN_2 = "cdn-css2"
JS_CDN = "cdn-js"
JS_CDN_0 = "cdn-js0"
JS_CDN_1 = "cdn-js1"
JS_CDN_2 = "cdn-js2"
ASSETS_CDN = "cdn-assets"
ASSETS_CDN_0 = "cdn-assets0"
ASSETS_CDN_1 = "cdn-assets1"
ASSETS_CDN_2 = "cdn-assets2"
ALL = [CSS_CDN_0, CSS_CDN_1, CSS_CDN_2, JS_CDN_0, JS_CDN_1, JS_CDN_2, ASSETS_CDN_0, ASSETS_CDN_1, ASSETS_CDN_2]
def call(source, request = nil)
cdn_index = Zlib.crc32(source) % 3
if source.ends_with?('.css')
url("#{CSS_CDN}#{cdn_index}", request)
elsif source.ends_with?('.js')
url("#{JS_CDN}#{cdn_index}", request)
else
url("#{ASSETS_CDN}#{cdn_index}", request)
end
end
def url(cdn_subdomain, request = nil)
return "//#{cdn_subdomain}-#{localhost}:3000"
end
end
TIA.

action_mailer.assets_host doesn't accept protocol relative URLs. Instead URLs have to start with with a protocol like http:// or https://.
This makes kind of sense, because usually emails aren't opened in a browser and email clients are not able to inherit the protocol from a patent html document like browsers do.

Related

How to get image classification prediction from GCP AIPlatform in ruby?

I'm new with ruby and I want to use GCP AIPlatform but I'm struggeling with the payload.
So far, I have :
client = ::Google::Cloud::AIPlatform::V1::PredictionService::Client.new do |config|
config.endpoint = "#{location}-aiplatform.googleapis.com"
end
img = File.open(imgPath, 'rb') do |img|
'data:image/png;base64,' + Base64.strict_encode64(img.read)
end
instance = Instance.new(:content => img)
request = Google::Cloud::AIPlatform::V1::PredictRequest.new(
endpoint: "projects/#{project}/locations/#{location}/endpoints/#{endpoint}",
instances: [instance]
)
result = client.predict request
p result
Here is my proto
message Instance {
required bytes content = 1;
};
But I have the following error : Invalid type Instance to assign to submessage field 'instances'
I read the documentation but for ruby SDK it's a bit light.
The parameters are OK, the JS example here : https://github.com/googleapis/nodejs-ai-platform/blob/main/samples/predict-image-object-detection.js is working with those parameters
What am I doing wrong ?
I managed it
client = Google::Cloud::AIPlatform::V1::PredictionService::Client.new do |config|
config.endpoint = "#{location}-aiplatform.googleapis.com"
end
img = File.open(imgPath, 'rb') do |img|
Base64.strict_encode64(img.read)
end
instance = Google::Protobuf::Value.new(:struct_value => {:fields => {
:content => {:string_value => img}
}})
endpoint = "projects/#{project}/locations/#{location}/endpoints/#{endpoint}"
request = Google::Cloud::AIPlatform::V1::PredictRequest.new(
endpoint: endpoint,
instances: [instance]
)
result = client.predict request
p result
The use of the Google::Protobuf::Value looks ugly to me but it works

Post to Sinatra API with hyperresource

I built an app in Sinatra with Roar (hal/JSON) and now I'm trying to post a new item from my client to this API.
In my Sinatra app I have routes like these:
get '/todos/new' do
#pagetitle = 'New Todo'
#todo = Todo.new
#todo.extend(TodoRepresenter)
#todo.to_json
erb :'todos/new'
end
post "/todos" do
#todo = Todo.new(params[:todo])
if #todo.save
redirect "todos/#{#todo.id}"
else
erb :"todos/new"
end
end
And my client.rb looks like this:
require 'hyperresource'
class ApiRequest < HyperResource
api = ApiRequest.new(root: 'http://127.0.0.1:9393',
headers: {'Accept' => 'application/vnd.http://127.0.0.1:9393.v1+json'})
api.post '/todos/new', { :title => "a"}
This doesn't work. The only way of get a working client is the get function:
require 'hyperresource'
class ApiRequest < HyperResource
api = ApiRequest.new(root: 'http://127.0.0.1:9393/todos/13',
headers: {'Accept' => 'application/vnd.http://127.0.0.1:9393.v1+json'})
todo = api.get
output = todo.body
puts output
I don't know how to solve this, and the Github page doesn't tell me either.
I changed the API slightly:
get '/todos' do
#pagetitle = 'New Todo'
#todo = Todo.new
erb :'todos/new'
end
post "/todos/new" do
#todo = Todo.new(params[:todo])
#todo.extend(TodoRepresenter)
#todo.to_json
if #todo.save
redirect "todos/#{#todo.id}"
else
erb :"todos/new"
end
end
and also the way of posting in my client:
todo = api.get.new_todo.post(title: "Test")
In my API console I now get:
D, [2014-11-04T17:11:41.875218 #11111] DEBUG -- : Todo Load (0.1ms) SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT 1 [["id", 0]]
ActiveRecord::RecordNotFound - Couldn't find Todo with 'id'=new:
and a lot of other code.
In my client console I get a lot of code, with a hyper resource server error and a lot of other code.

How do I access the Magento REST API with Ruby?

I want to start working with Magento's REST API, but I can't seem to get it working.
To start with I need to get access tokens, here's what I'm trying:
require 'oauth'
#consumer = OAuth::Consumer.new("4200100753b2c8b03bde1f5b062c5a80", "c06abdcb734c85dfd7bb115c6a67ae4d", {:site=>"http://178.62.173.99/"})
#request_token = #consumer.get_request_token
# => oauth-0.4.7/lib/oauth/consumer.rb:216:in `token_request': 404 Not Found (OAuth::Unauthorized)
But I keep getting a 404 error.
What should I try next?
Here's a Ruby module I've written to create an access token for the Magento REST API:
module Token
def create_consumer
OAuth::Consumer.new(
CONSUMER_KEY,
CONSUMER_SECRET,
:request_token_path => '/oauth/initiate',
:authorize_path=>'/admin/oauth_authorize',
:access_token_path=>'/oauth/token',
:site => URL
)
end
def request_token(args = {})
args[:consumer].get_request_token(:oauth_callback => URL)
end
def get_authorize_url(args = {})
args[:request_token].authorize_url(:oauth_callback => URL)
end
def authorize_application(args = {})
m = Mechanize.new
m.get(args[:authorize_url]) do |login_page|
auth_page = login_page.form_with(:action => "#{URL}/index.php/admin/oauth_authorize/index/") do |form|
form.elements[1].value = ADMIN_USERNAME
form.elements[2].value = ADMIN_PASSWORD
end.submit
authorize_form = auth_page.forms[0]
#callback_page = authorize_form.submit
end
#callback_page.uri.to_s
end
def extract_oauth_verifier(args = {})
callback_page = "#{args[:callback_page]}".gsub!("#{URL}/?", '')
callback_page_query_string = CGI::parse(callback_page)
callback_page_query_string['oauth_verifier'][0]
end
def get_access_token(args = {})
args[:request_token].get_access_token(:oauth_verifier => args[:oauth_verifier])
end
def save_tokens_to_json(args = {})
auth = {}
auth[:time] = Time.now
auth[:token] = args[:access_token].token
auth[:secret] = args[:access_token].secret
File.open("#{args[:path]}#{args[:filename]}.json", 'w') {|f| f.write(auth.to_json)}
auth
end
def get_new_access_tokens
new_consumer = self.create_consumer
new_request_token = self.request_token(consumer: new_consumer)
new_authorize_url = self.get_authorize_url(request_token: new_request_token)
authorize_new_application = self.authorize_application(authorize_url: new_authorize_url)
extract_new_oauth_verifier = self.extract_oauth_verifier(callback_page: authorize_new_application)
new_access_token = self.get_access_token(request_token: new_request_token, oauth_verifier: extract_new_oauth_verifier)
save_tokens_to_json(filename: 'magento_oauth_access_tokens', path: '/', access_token: new_access_token)
return 'Successfully obtained new access tokens.'
end
end
Run #get_new_access_tokens to get an access token.
Don't forget to define the following variable:
CONSUMER_KEY
CONSUMER_SECRET
URL
ADMIN_USERNAME
ADMIN_PASSWORD
Check out mage on rails. It should work right out of the box. Check out this page for annotated ruby code showcasing the oauth flow

How can I upload files to Redmine via ActiveResource / REST API?

I am trying to batch-upload images to Redmine and link them each to a certain wiki pages.
The docs (Rest_api, Using the REST API with Ruby) mention some aspects, but the examples fail in various ways. I also tried to derive ideas from the source - without success.
Can anyone provide a short example that shows how to upload and link an image from within Ruby?
This is a bit tricky as both attachments and wiki APIs are relatively new, but I have done something similar in the past. Here is a minimal working example using rest-client:
require 'rest_client'
require 'json'
key = '5daf2e447336bad7ed3993a6ebde8310ffa263bf'
upload_url = "http://localhost:3000/uploads.json?key=#{key}"
wiki_url = "http://localhost:3000/projects/some_project/wiki/some_wiki.json?key=#{key}"
img = File.new('/some/image.png')
# First we upload the image to get attachment token
response = RestClient.post(upload_url, img, {
:multipart => true,
:content_type => 'application/octet-stream'
})
token = JSON.parse(response)['upload']['token']
# Redmine will throw validation errors if you do not
# send a wiki content when attaching the image. So
# we just get the current content and send that
wiki_text = JSON.parse(RestClient.get(wiki_url))['wiki_page']['text']
response = RestClient.put(wiki_url, {
:attachments => {
:attachment1 => { # the hash key gets thrown away - name doesn't matter
:token => token,
:filename => 'image.png',
:description => 'Awesome!' # optional
}
},
:wiki_page => {
:text => wiki_text # original wiki text
}
})

Ruby/Mechanize Multipart Form With File Upload to a Mediawiki

I've been trying to write a ruby script using mechanize to batch upload a large number of images to a MediaWiki. The script runs without any errors but I suspect there is something wrong with the way I'm handling multipart forms with mechanize. The result variable at the end of the code gives no indication of success or failure, it just shows the page with all of the values filled in, wpDestFile is DezzImage.png and so on like I specified. end.submit seems to do nothing.
Below is a the complete code for uploading a single file, a few variables need filling in for it to work.
require 'rubygems'
require 'mechanize'
require 'nokogiri'
loginName = ""
loginPassword = ""
wikiUploadPage = "http://en.wikipedia.org/wiki/Special:Upload"
wikiLoginPage = "http://en.wikipedia.org/wiki/Special:UserLogin"
pathToImage = "/home/milo/image.png"
agent = Mechanize.new {|agent| agent.user_agent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4" }
agent.pre_connect_hooks << lambda { |params| params[:request]['Connection'] = 'keep-alive' }
agent.follow_meta_refresh = true
agent.get(wikiLoginPage) do |page|
login_result = page.form_with(:method => /POST/) do |form|
form.wpName = loginName
form.wpPassword = loginPassword
end.submit
end
uploadPage = agent.get(wikiUploadPage)
result = uploadPage.form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = pathToImage
form.wpDestFile = "DezzImage.png"
form.wpUploadDescription = "DezzImage.png"
end.submit
We solved this elsewhere, but the problem seemed to be a misconfiguration in the MediaWiki install. Setting:
form.checkbox_with(:name => "wpIgnoreWarning").check
with the form submission seems to have addressed the issue.
Looks like you're not actually setting the POST parameter that submits the page for uploading. Try something like this:
result = uploadPage.form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = pathToImage
form.wpDestFile = "DezzImage.png"
form.wpUploadDescription = "DezzImage.png"
form.wpUpload = True
end.submit
I have the same problem.
after viewed the source code, I found the solution:
result = uploadPage.form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = pathToImage
form.wpDestFile = "DezzImage.png"
form.wpUploadDescription = "DezzImage.png"
form.checkbox_with(:name => "wpIgnoreWarning").check
end.click_button

Resources