Class: Lita::Handlers::AlexaNewsPublisher

Inherits:
Handler
  • Object
show all
Defined in:
lib/lita/handlers/alexa_news_publisher.rb

Constant Summary collapse

STORE_KEY =
'alexa_newsfeed'
MAX_MESSAGE_COUNT =
100

Instance Method Summary collapse

Instance Method Details

#alexify(message) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/lita/handlers/alexa_news_publisher.rb', line 24

def alexify(message)
  main_text = message.fetch(:message)

  {
    "uid": message.fetch(:uuid),
    "updateDate": message.fetch(:timestamp),
    "titleText": "Lita update",
    "mainText": main_text,
    "redirectionUrl": "https://github.com/dpritchett/lita-alexa-news-publisher"
   }
end

#prune_message_list!Object

only store the latest N messages in redis at a time



78
79
80
81
82
# File 'lib/lita/handlers/alexa_news_publisher.rb', line 78

def prune_message_list!
  while Lita.redis.llen(STORE_KEY) > MAX_MESSAGE_COUNT do
    Lita.redis.lpop(STORE_KEY)
  end
end

#publish_to_newsfeed(response) ⇒ Object



69
70
71
72
73
74
75
# File 'lib/lita/handlers/alexa_news_publisher.rb', line 69

def publish_to_newsfeed(response)
  # TODO: cleanup match parsing
  msg = response.matches.last.last
  save_message(username: response.user.name, message: msg)

  response.reply("Saved message for Alexa: [#{msg}]")
end

#save_message(username:, message:) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/lita/handlers/alexa_news_publisher.rb', line 40

def save_message(username:, message:)
  payload = {
    username: username,
    message: message,
    uuid: SecureRandom.uuid,  # e.g. 752fc85e-61b1-429f-8a69-cf6e6489c8c1
    timestamp: Time.now.utc.iso8601 # e.g. 2017-08-18T12:59:51Z
  }

  begin
    Lita.redis.rpush(STORE_KEY, JSON.dump(payload))

    prune_message_list!
    payload
  rescue Redis::CommandError
    @retries ||= 0
    @retries += 1

    Lita.redis.del(STORE_KEY)

    if @retries < 5
      retry
    else
      # handle failure
    end
  end
end

#user_newsfeed(request, response) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/lita/handlers/alexa_news_publisher.rb', line 13

def user_newsfeed(request, response)
  username = request.env["router.params"][:username]

  messages = Lita.redis.lrange(STORE_KEY, 0, MAX_MESSAGE_COUNT)

  formatted_messages = messages.map { |m| alexify JSON.parse(m, symbolize_names: true) }

  response.headers["Content-Type"] = "application/json"
  response.write(MultiJson.dump(formatted_messages))
end