Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Grabbers::FacebookAttachments
- def initialize(api_client)
- @api_client = api_client
- end
- def grab_for_post(post)
- result = { 'attachment' => { 'media' => [] }}
- begin
- post = @api_client.get_object(post['id'], fields: 'attachments')
- post_attachments(post).each do |subattachment|
- if subattachment['target'].present? && subattachment['target']['id'].present?
- attachment = grab_attachment_by(subattachment['target']['id'])
- if attachment.present?
- attachment['photo']['fbid'] = subattachment['target']['id']
- attachment['href'] = subattachment['target']['url']
- result['attachment']['media'] << attachment
- end
- end
- end
- if result['attachment']['media'].compact.empty?
- result['attachment']['media'] = default_attachments_for(post)
- end
- rescue Exception => error
- ErrorsService.log(error, title: 'Cant grab attachments for post', data: {post: post})
- end
- result
- end
- private
- def grab_attachment_by(object_id)
- begin
- attachment = @api_client.get_object(object_id)
- image = attachment['images'].max_by { |image| [image['width'], image['height']].max }
- {'type' => 'photo', 'src' => image['source'], 'photo' => {'width' => image['width'], 'height' => image['height']} }
- rescue Exception
- return nil
- end
- end
- def default_attachments_for(post)
- post_attachments(post).map do |subattachment|
- {
- 'type' => 'photo',
- 'src' => image_src(subattachment),
- 'href' => image_url(subattachment),
- 'photo' => {
- 'fbid' => image_fbid(subattachment),
- 'width' => subattachment['media']['image']['width'],
- 'height' => subattachment['media']['image']['height']
- }
- }
- end
- end
- def image_url(subattachment)
- subattachment['target'].present? ? subattachment['target']['url'] : subattachment['url']
- end
- def image_src(subattachment)
- begin
- src = subattachment['media']['image']['src']
- return CGI::parse(src)['url'].first if src.include?('safe_image.php')
- src
- rescue Exception => error
- ErrorsService.log(error, title: 'Cant process image src', data: {subattachment: subattachment}, skip_airbrake_notification: true)
- ''
- end
- end
- def image_fbid(subattachment)
- subattachment['target'].present? ? subattachment['target']['id'] : subattachment['id']
- end
- def post_attachments(post)
- return post['attachments']['data'].first['subattachments']['data'] if post['attachments']['data'].first['subattachments'].present?
- return post['attachments']['data'] if post['attachments']['data'].first['media'].present?
- []
- end
- end
Add Comment
Please, Sign In to add comment