Ruby/Mechanize Multipart Form With File Upload to a Mediawiki - ruby

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

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

Fedex Ruby Mechanize: Unable to log in

I'm trying to automate my fedex processing via Ruby gem Mechanize.
I've set up the initial script similar to what has worked for me on the Amazon Seller Central page. However, I seem to be unable to fully log in to the fedex website and I appear to just be "staying" on the login page.
If you have any idea what my code is missing, it would be appreciated!
CODE
Dir.chdir 'C:\Ruby22\bin'
require "rubygems"
require "mechanize"
require "certified"
require "logger"
#Initialize and set agent settings:
agent = Mechanize.new
agent.user_agent_alias = 'Windows Chrome'
agent.follow_meta_refresh = true
agent.redirect_ok = true
#Log in to fedex
login_url = "https://www.fedex.com/dk/"
page_login = agent.get(login_url)
puts "Login Page: " + page_login.title.to_s
form = page_login.form_with(:name => "logonForm")
#form.fields.each { |f| puts f.name }
form.username = "************"
form['ap_signin_existing_radio'] = "1"
form.password = "*********"
agent.submit(form)
page_home = agent.get(login_url)
puts "Fedex Dashboard Page: " + page_home.title

Images not loading in emails with CDN Hosts url rails

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.

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

Rally authentication failure while using with rally_api gem

I am trying to connect to rally using rally_api gem but it gives me error like,
Error 401 The username or password you entered is incorrect.
but when i tries to login directly through website it logs in me.
#config = {}
#config[:base_url] = "https://trial.rallydev.com/slm" # This is the default setting.
#config[:username] = "my_username"
#config[:password] = "my_pass"
#config[:workspace] = "workspace name"
#config[:project] = "project name"
Is your intent to connect to trial or production (trail.rallydev.com or rally1.rallydev.com) ?
A code making connection to Rally shown here.
#Setting custom headers
headers = RallyAPI::CustomHttpHeader.new()
headers.name = "My Utility"
headers.vendor = "MyCompany"
headers.version = "1.0"
#or one line custom header
headers = RallyAPI::CustomHttpHeader.new({:vendor => "Vendor", :name => "Custom Name", :version => "1.0"})
config = {:base_url => "https://rally1.rallydev.com/slm"}
config[:username] = "user#company.com"
config[:password] = "password"
config[:workspace] = "Workspace Name"
config[:project] = "Project Name"
config[:headers] = headers #from RallyAPI::CustomHttpHeader.new()
#rally = RallyAPI::RallyRestJson.new(config)
Do you have non-alpha numeric characters in the password? (Exclamation point certainly works,but there can be characters that problematic).
Also , to set the WS API version use:
config[:version] = "v2.0"

Resources