class DistributionWrappers::Backstitch

Public Instance Methods

get_contacts() click to toggle source
# File lib/distribution_wrappers/backstitch/backstitch.rb, line 21
def get_contacts
  channel = DistributionChannelDistro.find @params[:channel_id]
  user = UserDistro.find(channel.owner_id)

  feeds = user.managed_feeds

  csv_string = ""

  feeds.each_with_index do |feed, index|
    csv_string += CSV.generate_line [feed.name, feed.feed_id, '{"url": null}', 'feed', @params[:channel_id]]

    if index % 100 == 0
      @params[:temp_file].write(csv_string)
      csv_string = ""
    end
  end

  @params[:temp_file].write(csv_string)

  return true
end
send_message(recipient) click to toggle source
Calls superclass method DistributionWrappers::Base#send_message
# File lib/distribution_wrappers/backstitch/backstitch.rb, line 4
def send_message(recipient)
  super
  @response = Semantic::OrganizationResults::Article.bulk_store([@message], true, true)
  results = []

  @version_contact.channel_entity_identifier = @message[:reference_id]
  @version_contact.save

  # send push notification if priority alerts is turned on for the selected feed
  feed = FeedDistro.find(recipient['identifier'].to_i)
  if feed.params["priority_alerts"] && @message
    pushwoosh_id = feed.owner.pushwoosh_id if feed.owner_type == "Organization" && feed.owner.pushwoosh_id
    organization_id = feed.owner.id if feed.owner && feed.owner_type == "Organization"
    send_notifications(@message, feed.id, organization_id, pushwoosh_id)
  end
end

Private Instance Methods

build_result(doc, result, identifier) click to toggle source
# File lib/distribution_wrappers/backstitch/backstitch.rb, line 77
def build_result(doc, result, identifier)
  begin
    published_at = Time.now.utc.to_datetime

    created_by = UserDistro.find @params[:post].created_by_id
    result[:published_at] = published_at
    result[:title] = @params[:post].title
    result[:plain_text_title] = TextHelper.clean_text(result[:title])
    result[:author][:name] = @params[:user].display_name
    result[:tracking] = {
      :type => "text",
      :feed_id => identifier.to_i
    }

    result[:origin][:id] = created_by.id
    result[:origin][:name] = created_by.display_name
    result[:origin][:icon][:url] = created_by.avatar_url

    if @params[:post].draft_content.match(/<html>.*<\/html>/).nil?
      result[:full_text] = "<html>#{@params[:post].draft_content}</html>"
    else
      result[:full_text] = @params[:post].draft_content
    end

    result[:images][:full_size][:url] = @params[:post].main_image if @params[:post].main_image

    video_iframes = doc.css('iframe').select{|iframe| URI.unescape(iframe.attr('src')).match(/(?<=youtube\.com\/embed\/)(.+?)(?=\?|$)/)}

    video_iframes.each do |iframe|
      iframe['style'] = "box-sizing: content-box; max-width: 100%; border: 0px;"
      iframe['height'] = '360'
      iframe['width'] = '640'
    end

    if result[:images][:full_size][:url].nil?
      if img = doc.xpath('//iframe').first
        if img.attr('src').match(/youtube/) ||
           img.attr('src').match(/dailymotion/) ||
           img.attr('src').match(/wistia/)
          VideoInfo.provider_api_keys = {youtube: Keys.google.key, vimeo: Keys.vimeo.client_id}
          video = VideoInfo.new(img.attr('src'))
          article[:images][:full_size][:url] = video.thumbnail_large
        end
      end
    end

    base_url = ""
    if ENV['ENVIRONMENT'] == 'production'
      base_url = "http://studio.backstit.ch"
    else
      base_url = "http://localhost:3000"
    end

    new_node = doc.create_element 'div'
    new_node.inner_html =  "<img src='#{base_url}/posts/#{@params[:post].id}/engagement/tracking.gif?contact_id=#{@params[:version_contact_id]}&version_id=#{@params[:version_id]}&organization_id=#{@params[:organization].id}&email=<<email_placeholder>>'/>"
    doc.children[1].add_child(new_node)

    result[:full_text] = doc.to_html

    result[:plain_text] = TextHelper.clean_text(result[:full_text])

    summary = Pismo::Document.new(result[:plain_text])
    result[:description] = summary.lede
    result[:plain_text_description] = TextHelper.clean_text(result[:description])

    base_url = ""
    if ENV['ENVIRONMENT'] == 'production'
      base_url = "http://backstit.ch"
    else
      base_url = "http://localhost:3000"
    end
    result[:origin][:url] = "#{base_url}/feeds/#{result[:tracking][:feed_id]}/results/#{result[:reference_id]}"

    return result
  rescue
  end
end
prepare(identifier=nil) click to toggle source
# File lib/distribution_wrappers/backstitch/backstitch.rb, line 45
def prepare(identifier=nil)
  published_at = Time.now.utc.to_datetime
  doc = Nokogiri::HTML(@params[:post].draft_content)

  doc = append_parameters(doc, true)
  doc = update_feedback_trackers(doc) if doc.css('td[data-cell-identifier="feedback-form-container"]').length > 0

  doc = redirect_links(doc, true)

  if @params[:reference_id]
    result = Semantic::OrganizationResults::Article.find_by_reference_id(@params[:reference_id])
  else
    result = Semantic::OrganizationResults::Article.new("feed-#{identifier}-#{@params[:user].id}-#{published_at.to_i}")
  end

  build_result(doc, result, identifier)
end
send_notifications(result, feed_id, organization_id=nil, pushwoosh_id=nil) click to toggle source
# File lib/distribution_wrappers/backstitch/backstitch.rb, line 155
def send_notifications(result, feed_id, organization_id=nil, pushwoosh_id=nil)
  Pushwoosh.configure do |config|
    config.auth = 'VvFYDCs1zaz5PIy9WgC7KDfSmAD6Sqlykrxw1mxsXnfSgRG07k84wuCD4hBRAt97EyvDJQKl2ewy01h8olzV'
    if pushwoosh_id
      config.application = pushwoosh_id
    else
      config.application = 'FF35B-68BC0'
    end
  end

  topics = TopicDistro.joins(:topic_feeds).where('topic_feeds.feed_id = ?', feed_id)

  body = []
  topics.each do |topic|
    internal_source_count = topic.feeds.where("feeds.owner_id is not null").count
    if topic.alias? && ((topic.promoted_alias? && internal_source_count > 0) || internal_source_count == 0)
      alias_name = "#{topic.alias}"
      alias_name =  "#{alias_name},#{topic.promoted_alias}" if internal_source_count > 0
    elsif topic.serialized_alias? && ((topic.serialized_promoted_alias? && internal_source_count > 0) || internal_source_count == 0)
      indices = topic.serialized_alias["indices"]
      indices.concat(topic.serialized_promoted_alias["indices"]) unless topic.serialized_promoted_alias.nil?

      should = []
      should << {topic.serialized_alias["action"] => topic.serialized_alias["filters"]}
      should << {topic.serialized_promoted_alias["action"] => topic.serialized_promoted_alias["filters"]} unless topic.serialized_promoted_alias.nil?

      alias_name = indices.uniq.join(",")
      filters = {"bool" => {"should" => should}}
    else
      next
    end

    query = {
      :query => {
        :term => {
          :reference_id => result[:reference_id]
        }
      }
    }

    query[:filter] = filters if filters

    body << {:search_type => 'count', :search => query, :index => alias_name, :ignore_indices => "missing", :topic_id => topic.id}
  end

  options = {
    :body => body
  }

  search = ELASTICSEARCH.msearch options

  topic_ids = []

  body.each_with_index do |topic, index|
    if search["responses"][index]["hits"]["total"] > 0
      topic_ids << topic[:topic_id]
    end
  end

  # If a user hasn't signed into the app, send them a priority email instead of a push notification
  users = UserDistro.joins(:topics).joins("left join device_sessions on device_sessions.user_id = users.id")
                    .where("topics.id in (?) AND device_sessions.id is null", topic_ids)
                    .uniq.pluck(:id).compact

  # Pull device sessions for every user that's signed into the app so we can send push notifications
  device_sessions = DeviceSessionDistro.joins(:user => :topics).where("topics.id in (?)", topic_ids)
                                       .uniq.pluck(:device_token).compact.delete_if{|token| token == "" }


  users.each do |user_id|
    # Mailer::PriorityAlertWorker.perform_async(user_id, organization_id, result)
  end

  message = ""

  case result[:type]
  when 'article'
    plain_text = ""
    plain_text = " - #{result[:plain_text][0..140]}" if result[:plain_text]
    message = "#{result[:title]}#{plain_text}"
  when 'status', 'photo'
    message = "#{result[:plain_text_description][0..140]}"
  when 'video'
    message = "#{result[:title]} - #{result[:description][0..140]}"
  when 'email'
    message = "#{result[:subject]} - #{result[:plain_text][0..140]}"
  when "product", "service", "hotel"
    message = "#{result[:title][:long][0..140]}"
  end

  options = {
    "send_date" => "now",
    "ignore_user_timezone" => true,
    "platforms" => [1,3],
    "data" => {
      "ref_id" => result[:reference_id],
      "feed_id" => feed_id.to_s
    }
  }

  #ios options
  options["ios_badges"] = "+1"
  options["apns_trim_content"] = 1

  # android options
  options["android_badges"] = "+1"

  device_sessions.each_slice(1000) do |tokens|
    Pushwoosh.notify_devices(message, tokens, options)
  end
end
update_feedback_trackers(doc) click to toggle source
# File lib/distribution_wrappers/backstitch/backstitch.rb, line 63
def update_feedback_trackers(doc)
  doc.css('td[data-cell-identifier="feedback-form-container"]').each do |feedback|
    identifier = feedback.css('a').attr('data-url-identifier')
    feedback.inner_html = "<textarea id='#{identifier}' style='width:100%;height:100%;outline:none;border:none;resize:none;'></textarea>"
  end

  doc.css('td[data-cell-identifier="feedback-submit-container"]').each do |feedback|
    base_url = feedback.css('a').attr('href')
    feedback.css('a').attr('href').value = base_url.value.gsub('feedback_form', 'record_feedback')
  end

  doc
end