ActionCable with attachment - ruby-on-rails-5

I want to attach an image with my chat application. I have done with text chat but I am not able to send an attachment with actioncable.
App.global_chat = App.cable.subscriptions.create {
channel: "ChatRoomsChannel"
chat_room_id: messages.data('chat-room-id')
},
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
messages.append data['message']
messages.append data['attachment']
messages_to_bottom()
send_message: (message, chat_room_id, attachment) ->
#perform 'send_message', message: message, chat_room_id: chat_room_id, attachment: attachment
$('#new_message').submit (e) ->
$this = $(this)
textarea = $this.find('#message_body')
attachment = $this.find('#message_attachment')
if $.trim(textarea.val()).length > 1
App.global_chat.send_message textarea.val(), messages.data('chat-room-id'), attachment[0].files[0]
textarea.val('')
attachment.val('')
e.preventDefault()
return false

I cannot comment but I can give you a tips to accomplish it .
As you know rails form_for don't support the ajax upload and it is very hard in rails for ajax upload i had to dig in too deep.
First Install this gem
gem 'remotipart', '~> 1.2'
After adding the gem you can create a form with file input . The best thing is after adding a gem the file get upload automatically.
Be Sure to add remote: true at form_for while creating forms.
I have tried with paperclip gem and it is working perfectly fine . If you problem then ping us

Related

How to update the database when users download an ActiveStorage blob attachment?

Currently users can download an ActiveStorage blob in my app using the following link:
link_to 'download', rails_blob_path(pj.document.file, disposition: 'attachment')
However, I would like to update an attribute in the database for the associated model to register when the file was first downloaded. This field is called the downloaded_at field.
I have made the following attempt:
Changed the link_to > button_to as I'm updating the model.
Added the appropriate route
Added the following code in the database:
def download
#proofreading_job = ProofreadingJob.find(params[:id])
#proofreading_job.update(downloaded_at: Time.current) if current_user == #proofreading_job.proofreader.user
response.headers["Content-Type"] = #proofreading_job.document.file.content_type
response.headers["Content-Disposition"] = "attachment; #{#proofreading_job.document.file.filename.parameters}"
#proofreading_job.document.file.download do |chunk|
response.stream.write(chunk)
end
ensure
response.stream.close
end
However, this does not do anything except redirect to the #proofreading_job page which is not what I want.
Has anyone done this before and if so how can I accomplish this task.
I think you can also try using your action controller as a proxy, the concept is this:
download the file in your action
check if it is downloaded successfully and other validations
perform clean up operations (in your case the added code in your #3)
send the file back to user using the send_data/send_file rendering method
E.g. in your controller:
def download
file = open(params[:uri])
validate!
cleanup!
send_file file.path
end
Then in your view:
link_to 'download', your_controller_path
Above is just concept and I apologize for only providing pseudo code in advance.
In the end I just used some javascript to capture the click of the button as follows:
td = link_to rails_blob_path(pj.document.file, disposition: 'attachment'),
id: pj.document.id,
download: pj.document.file_name,
class: "btn btn-outline-secondary btn-sm btn-download" do
=pj.document.file_name
i.fa.fa-download.ml-3 aria-hidden="true"
coffee script:
$('.btn-download').on 'click', (e) ->
id = $(this).attr('id')
$.ajax {url: Routes.document_path(id), type: 'PUT'}
routes.rb
resources :documents, only: [:show, :update]
documents_controller.rb:
def update
document = Document.find(params[:id])
authorize([:proofreaders, document])
document.update(downloaded_at: Time.current) if document.downloaded_at.nil?
head :ok
end
This seems to work very well. It updates the database and the user gets the file downloaded to their computer.

Paperclip not displaying image (rails api)

I have a user module and I have generated paperclip attachment: profile_pic
user.rb:
has_attached_file :profile_pic,
style: { :medium => "300x300>", thumb: "100x100>" },
default_url: "/images/:style/missing.png"
controller:
image_base = params[:manager][:profile_pic]
if image_base != nil
image = Paperclip.io_adapters.for(image_base)
image.original_filename = params[:manager][:file_name]
current_user.profile_pic = image
current_user.errors.delete(:profile_pic)
current_user.save
end
config/initializers/paperclip.rb:
Paperclip::DataUriAdapter.register
It's not showing any errors but If I am trying to display the image, it gives me following error:
ActionController::RoutingError (No route matches [GET] "/system/managers/profile_pics/000/000/008/original/icon_new.png"):
When I am trying in console like:
user.profile_pic.display
/system/managers/profile_pics/000/000/008/original/icon_new.png?
1556082410 => nil
Picture was saved in public folder
The default folder is the following, so Paperclip uploaded to the right place:
:rails_root/public/system/:class/:attachment/:id_partition/:style/:filename
But it looks like you are having troubles accessing the right location. Have you tried user.profile_pic.url? I tried on my working example, both .display and .url are the same but I use an AWS S3 bucket.
user.profile_pic.url should be where to find the file on the web.
user.profile_pic.path should be where to find the file on the file system.
The problem is with production mode and Solved this by adding the following line in production.rb
config.public_file_server.enabled = true

Force Swagger UI To Load https path when hosted on Heroku

I have a rails 4 app with a Grape API and Swagger through the gem grape-swagger and grape-swagger-ui gems.
In dev everything works well, I load http://localhost:3000/api/swagger and the swagger header's text input along the top loads the expected url, http://localhost:3000/api/swagger_doc. This points properly to the file it seeks, swagger_doc.json.
I've pushed this app to heroku, which forces https connections. Unfortunately, when loading https://my-app.herokuapp.com/api/swagger the swagger header's text input along the top loads http://my-app.herokuapp.com/api/swagger_doc instead of loading https://my-app.herokuapp.com/api/swagger_doc (http vs https).
I've tried coming at this from the heroku side with things like:
routes.rb
unless Rails.env.development?
get "*path" => redirect("https://my-app.herokuapp.com%{path}"), :constraints => { :protocol => "http://" }
post "*path" => redirect("https://my-app.herokuapp.com%{path}"), :constraints => { :protocol => "http://" }
end
config/environments/production
config.force_ssl = false
config/environments/production
#config.force_ssl = false
And I've come at it with trying to set or manipulate the base_path attribute of add_swagger_documentation.
app/controllers/api/base.rb
base_path: "my-app.herokuapp.com",
app/controllers/api/base.rb
base_path: "http://my-app.herokuapp.com",
app/controllers/api/base.rb
base_path: = lambda do |request|
return "http://my-app.herokuapp.com"
end
app/controllers/api/base.rb
base_path: lambda { |request| "http://#{request.host}:#{request.port}" }
I recently clicked "view raw" on one of my resources and noticed that it was picking up my changes to base_path but that base_path isn't even used to populate the url in the text input in the swagger header. It seems to be generated from a js file. I'm unable to edit it and would happily accept a hack to do so as a solution. Here's that raw output:
https://gist.github.com/johnnygoodman/5fd246765dc5236fb8c4
The line of interest is:
"basePath":"http://localhost:3000/my-app.herokuapp.com"
Which would break the app if it was being populated and used, but it is not. I don't see an option in the grape-swagger gem that I can use to pass in this variable and change the path to https.
In conclusion:
I'd like the swagger text input box to load https://my-app.herokuapp.com/api/swagger_doc when I visit https://my-app.herokuapp.com/api/swagger.
Anyone know a hack to accomplish this on heroku?
I was able to work around this. I suggest:
Do not use + uninstall #gem 'grape-swagger-ui'
Use and install gem 'grape-swagger-rails' and follow the docs here: https://github.com/ruby-grape/grape-swagger-rails

How to get contact list from yahoo in rails using OAuth

I can successfully get the contacts from google using OAuth gem in rails. my gmail configuration is :
:google=>{
:key=>"***",
:secret=>"***",
:expose => true,
:scope=>"https://www.google.com/m8/feeds/"
}
now i want to get contact from yahoo and hot mail. How to get that contact I have given following configuration in my oauth_consumer.rb file
:yahoo=>{
:client=>:oauth_gem,
:expose => true,
:allow_login => true,
:key=>"**",
:secret=>"**",
:scope=>"https://me.yahoo.com"
}
:hotmail=>{
:client=>:oauth_gem,
:expose => true,
:allow_login => true,
:key=>"**",
:secret=>"**"
}
when i am trying to do same like what is done in google it gives error like undefined methoddowncase' for nil:NilClass`
I have also tried contacts gem but fail to load contacts.
Please try to use OmniContacts https://github.com/Diego81/omnicontacts this will help you alot.
In your gemfile
gem "omnicontacts"
Create config/initializers/omnicontacts.rb
require "omnicontacts"
Rails.application.middleware.use OmniContacts::Builder do
importer :gmail, "client_id", "client_secret", {:redirect_path => "/oauth2callback", :ssl_ca_file => "/etc/ssl/certs/curl-ca-bundle.crt"}
importer :yahoo, "consumer_id", "consumer_secret", {:callback_path => '/callback'}
importer :hotmail, "client_id", "client_secret"
importer :facebook, "client_id", "client_secret"
end
Create an app to yahoo https://developer.apps.yahoo.com/projects
This will ask to verify your domain. So, just change your domain of localhost:3000 to local.appname.com:3000 or prefer your live server... (change host in local --- sudo gedit /etc/hosts)
in your controller
#contacts = request.env['omnicontacts.contacts']
#user = request.env['omnicontacts.user']
puts "List of contacts of #{user[:name]} obtained from #{params[:importer]}:"
#contacts.each do |contact|
puts "Contact found: name => #{contact[:name]}, email => #{contact[:email]}"
end

rails aws-s3 delete file throws AWS::S3::PermanentRedirect error - EU bucket problem?

I'm building a rails3 app on heroku, and I'm using aws-s3 gem to manipulate files stored in an Amazon S3 eu bucket.
When I try to perform a AWS::S3::S3Object.delete filename, 'mybucketname' command, I get the following error:
AWS::S3::PermanentRedirect (The bucket you are attempting to access
must be addressed using the specified endpoint. Please send all future
requests to this endpoint.):
I have added the following to my application.rb file:
AWS::S3::Base.establish_connection!(
:access_key_id => "myAccessKey",
:secret_access_key => "mySecretAccessKey"
)
and the following code to my controller:
def destroy
song = tape.songs.find(params[:id])
AWS::S3::S3Object.delete song.filename, 'mybucket'
song.destroy
respond_to do |format|
format.js { render :nothing => true }
end end
I found a proposed solution somewhere to add AWS_CALLING_FORMAT: SUBDOMAIN to my amazon_s3.yml file, as supposedly, aws-s3 should handle differently eu buckets than us.
However, this did not work, same error is received.
Could you please provide any assistance?
Thank you very much for your help.
the problem is you need to type SUBDOMAIN as uppercase string in config, try this out
You can specify custom endpoint at connection initialization point:
AWS::S3::Base.establish_connection!(
:access_key_id => 'myAccessKey',
:secret_access_key => 'mySecretAccessKey',
:server => 's3-website-us-west-1.amazonaws.com'
)
you can find actual endpoint through the AWS console:
full list of valid options - here https://github.com/marcel/aws-s3/blob/master/lib/aws/s3/connection.rb#L252
VALID_OPTIONS = [:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy].freeze
My solution is to set the constant to the actual service link at initialization time.
in config/initializers/aws_s3.rb
AWS::S3::DEFAULT_HOST = "s3-ap-northeast-1.amazonaws.com"
AWS::S3::Base.establish_connection!(
:access_key_id => 'access_key_id',
:secret_access_key => 'secret_access_key'
)