Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This worker's purpose is to get a transcoded / minified version of a video
- # from the Filestack API for display on discussion pages
- # See Filestack API docs: https://www.filestack.com/docs/api/processing/#audio-and-video
- module FilestackUploadWorkers
- class VideoTranscodingWorker
- include Sidekiq::Worker
- sidekiq_options unique: :until_timeout, unique_job_expiration: 60 * 60 * 24
- attr_reader :resource_handle,:attachment_id,:attachment_class,:opts
- def perform(attachment_id, attachment_class, resource_handle)
- puts "VideoTranscodingWorker.perform: attachment_id, attachment_class, resource_handle #{attachment_id}, #{attachment_class}, #{resource_handle}"
- @attachment_id = attachment_id
- @attachment_class = attachment_class
- @resource_handle = resource_handle
- # Poll to see if the video transcoding is completed & update the record; otherwise reschedule
- poll_for_complete || reschedule_worker
- end
- # Find the discussion attachment by ID
- def discussion_attachment
- @discussion_attachment ||= attachment_class.find(attachment_id)
- end
- # Poll to Filestack transcoding API and return JSON response
- # TODO: Test me - post resource for transcoding
- def post_to_transcode
- puts "VideoTranscodingWorker.post_to_transcode"
- max_width, max_height = [600, 400]
- base_url = 'https://cdn.filestackcontent.com'
- conversion = "video_convert=width:#{max_width},height:#{max_height}"
- uri = URI.parse([base_url, conversion, resource_handle].join('/'))
- req = Net::HTTP::Get.new(uri)
- res = Net::HTTP.start(uri.hostname, uri.port) {|http| http.request(req) }
- res.body
- end
- # Is the returned JSON "data" field empty?
- def completed?(response)
- puts "VideoTranscodingWorker.completed?"
- JSON.parse(response)["data"].empty? ? false : true
- end
- # Reschedule the worker to poll again in 1 minute
- def reschedule_worker
- puts "VideoTranscodingWorker.reschedule_worker"
- VideoTranscodingWorker.perform_in(1.minute, attachment_class, attachment_id)
- end
- # Test the transcoding is complete. If so, save the new compressed_version_url.
- # Return false if returned JSON data is still empty
- def poll_for_complete
- puts "VideoTranscodingWorker.poll_for_complete"
- res = post_to_transcode
- puts "completed?(res):"
- if completed?(res)
- puts "TRUE"
- update_compressed_url(res)
- return true
- else
- puts "FALSE"
- return false
- end
- end
- # Update the attachment record with the new compressed_version_url
- def update_compressed_url(response)
- puts "VideoTranscodingWorker.update_compressed_url"
- new_url = response['data']['url']
- discussion_attachment.update_attribute(compressed_version_url: new_url)
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement