How do i upload image from Rhomobile - rhomobile

I need to upload user profile image to server, i have it stored it on the app's base path.
settings = { :camera_type => #params['camera_type'],
:color_model => #params['color_model'],
:enable_editing => en_ed,
:desired_width => width,
:desired_height => height,
:flash_mode => 'auto',
:saveToDeviceGallery => 'true'}
Camera::take_picture(url_for(:action => :camera_callback), settings)
Then on callback,
Image.create({:id => generateId(), :image_uri => #params['image_uri']})
file_testname = File.join(Rho::RhoApplication::get_blob_path(#params['image_uri']))
test_content = File.binread(file_testname)
new_file_name = File.join(Rho::RhoApplication::get_base_app_path(), #params['image_uri'].to_s().split("/")[2])
f = File.new(new_file_name, "wb")
f.write(test_content)
f.close
How can i upload that image to server?

You can use the upload_file API
new_file_name = File.join(Rho::RhoApplication::get_base_app_path(), image.filename)
if File.exist?(new_file_name)
# Upload the file
result = Rho::AsyncHttp.upload_file(
:url => "#{##url}/image/upload",
:filename => new_file_name,
:headers => {},
:body => ""
)
if result["status"].upcase == "OK"
Alert.show_popup "Success"
end
end
You need to replace image.filename with your path.

Related

How to use aws_account_utils to create an AWS account ? Getting error : cannot load such file -- aws_account_utils

I want to use AWSAccountUtils in my project to create AWS account. I have installed gem aws_account_utils too. What more do I need to do or what is that I am missing ? In my controller I have defined following function and code is :
def create_aws_account
require 'aws_account_utils'
#account_details = []
#account_values = {}
aws_utils = AwsAccountUtils::AwsAccountUtils.new()
details = { 'fullName' => 'Devanshu Kumar',
'company' => 'ABC',
'addressLine1' => 'CP, Bund Garden Road',
'city' => 'Pune',
'state' => 'Maharastra',
'postalCode' => '411007',
'phoneNumber' => '1234567890',
'guess' => 'Test Account Dev' }
resp = aws_utils.create_account(account_name: 'My Test Account Devanshu Kumar',
account_email: 'devanshu.kumar#abc.com',
account_password: 'password',
account_details: details)
#account_values = {:account_number => data_disk.resp}
#account_details.push #account_values
render :json => { created_aws_account: account_details }
end
AWS Account Details Error Image

From ActiveRecord to S3

I am new to S3 and Rails so got stuck. I am wondering if I can directly pass object to S3.
My controller:
def start_upload
#forecasts = Forecast.all
Forecast.export_to_s3(#forecasts)
end
Model:
def self.export_to_s3(data)
---AWS configs ---
Aws.config = { :access_key_id => aws_access_key, :secret_access_key => aws_secret_access_key, :region => aws_region }
s3 = Aws::S3::Client.new(region:aws_region)
resp = s3.put_object(
:bucket => aws_bucket,
:key => aws_bucket_key_forcast,
:body => IO.read(data)
)
end
What are you trying to do? What is you goal?
You should try to serialize your object before you push it to your bucket.
def start_upload
#forecasts = Forecast.all
Forecast.export_to_s3(#forecasts.to_json)
end
def self.export_to_s3(data)
# ---AWS configs ---
Aws.config = { :access_key_id => aws_access_key, :secret_access_key => aws_secret_access_key, :region => aws_region }
tmpfile = Tempfile.new('forecast')
tmpfile.write(data)
tmpfile.close
s3 = Aws::S3::Client.new(region:aws_region)
resp = s3.put_object(
:bucket => aws_bucket,
:key => aws_bucket_key_forcast,
:body => IO.read(tmpfile)
)
tmpfile.unlink
end

Ruby Google Custom Seach API get results from next page

the code below is only getting the results from the first page of the google pagination... how to get more results?
require 'google/api_client'
# autenticação
client = Google::APIClient.new(:application_name => 'Ruby Drive sample',
:application_version => '1.0.0',
:client_id => 'xxxxxxxxxxxxxxxx',
:client_secret => 'xxxxxxxxxxxxxx',
:authorization => nil)
search = client.discovered_api('customsearch')
# chama a API
response = client.execute(
:api_method => search.cse.list,
:parameters => {
'q' => 'cafe',
'key' => 'xxxxxxxxxxxx',
'cx' => 'xxxxxxxxxxxxxxxx'
}
)
# recebe a resposta em json
body = JSON.parse(response.body)
items = body['items']
# printa algumas informações...
items.each do |item|
puts "#{item['formattedUrl']}"
end
Simply use the nextPageToken as a parameter in the next request until you get back a result without a nextPageToken key
next_page_token = body['nextPageToken']
response_page2 = client.execute(
:api_method => search.cse.list,
:parameters => {
'nextPageToken' => next_page_token,
'key' => 'xxxxxxxxxxxx',
'cx' => 'xxxxxxxxxxxxxxxx'
}
)

How to use Rhodes without Rhosync or RhoConnect?

I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.

generating email address images or something which can't be easily scraped

I'm looking for a better Text-to-image solution for my Rails project to replace my current method which is generating a png using ImageMagick every time a new record is created or updated.
I want to prevent a mass scraping of data and abuse of email addresses provided. I'm wondering if there is an API to generate the text or use of javascript, or SVG, etc. Anything short of Flash.
I'm looking for a better solution than my current method:
def create_new_email_image
if email_changed?
path_to_images = '/images/emails'
puts "Connecting to AWS..."
config = YAML.load(File.open("#{RAILS_ROOT}/config/s3_credentials.yml"))[RAILS_ENV]
AWS::S3::Base.establish_connection!(
:access_key_id => config['access_key_id'],
:secret_access_key => config['secret_access_key']
)
puts "Finding S3 bucket..."
begin
bucket = AWS::S3::Bucket.find config['bucket_name']
rescue AWS::S3::NoSuchBucket
AWS::S3::Bucket.create config['bucket_name']
bucket = AWS::S3::Bucket.find config['bucket_name']
end
images_path = "#{RAILS_ROOT}/tmp/"
file_name = "#{id}.png"
#file_name = "5056.png"
file_path = images_path + "/"+ file_name
File.delete file_path if File.exists? file_path
img = Magick::Image.new(400, 22) { self.background_color = 'transparent' }
img.format = 'PNG'
text = Magick::Draw.new
text.annotate(img, 0, 0, 1, 0, "#{email}") {
self.gravity = Magick::WestGravity
self.pointsize = 18
self.fill = '#000000'
self.kerning = -1
self.font_weight = Magick::BoldWeight
}
img.write file_path
if AWS::S3::S3Object.exists? file_name, bucket.name + path_to_images
puts "file exists (deleting)"
AWS::S3::S3Object.delete file_name, bucket.name + path_to_images, :force => true
end
AWS::S3::S3Object.store file_name,
File.open(file_path),
bucket.name + path_to_images,
:content_type => 'image/png',
:access => :public_read,
:reload => true
`rm #{file_path}`
end
end
Rails provides a mail_to helper.
mail_to "me#domain.com"
# => me#domain.com
mail_to "me#domain.com", "My email", :encode => "javascript"
# => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
mail_to "me#domain.com", "My email", :encode => "hex"
# => My email
mail_to "me#domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
# => me_at_domain_dot_com
mail_to "me#domain.com", "My email", :cc => "ccaddress#domain.com",
:subject => "This is an example email"
# => My email
The :encode => "hex" or :encode => "javascript" options are what you are looking for.
I've had the same problem. Here is my solution:
def text_to_image(text,options={})
return if text.blank?
filename=get_text_file_path(text)
unless File.exists?(filename)
gc = Magick::Draw.new
gc.fill = options[:color] unless options[:color].blank?
gc.pointsize options[:size] unless options[:size].blank?
gc.font=options[:font] unless options[:font].blank?
gc.gravity = Magick::CenterGravity
gc.text(0,0, text)
metrics=gc.get_type_metrics(text)
image = Magick::Image.new(metrics.width, metrics.height){
self.background_color = 'transparent'
}
gc.draw(image)
image.write(filename)
end
end
I use after_save callback to update graphic cache of email attribute.

Resources