lib/gnome-campfire-notifications.rb in gnome-campfire-notifications-0.1.2 vs lib/gnome-campfire-notifications.rb in gnome-campfire-notifications-0.1.3

- old
+ new

@@ -1,51 +1,48 @@ require "twitter/json_stream" -require "json" -require "yaml" require "net/http" +require "json" class GnomeCampfireNotifications HOST = 'streaming.campfirenow.com' + NOTIFICATION_GFX_FILENAME = 'campfire.png' + NOTIFICATION_GFX_SYSPATH = "/usr/share/icons/gnome/32x32/apps" - def self.start - room_name = ENV['GNOME_CAMPFIRE_NOTIFICATIONS_ROOM_NAME'] - room_id = ENV['GNOME_CAMPFIRE_NOTIFICATIONS_ROOM_ID'] - token = ENV['GNOME_CAMPFIRE_NOTIFICATIONS_TOKEN'] + ATTR_MAP = { + room_name: 'GNOME_CAMPFIRE_NOTIFICATIONS_ROOM_NAME', + room_id: 'GNOME_CAMPFIRE_NOTIFICATIONS_ROOM_ID', + token: 'GNOME_CAMPFIRE_NOTIFICATIONS_TOKEN' + } - unless room_name && room_id && token - raise "please set GNOME_CAMPFIRE_NOTIFICATIONS_ROOM_ID and GNOME_CAMPFIRE_NOTIFICATIONS_TOKEN" + def initialize + if (missing = ATTR_MAP.values.select { |env| ENV[env].empty? }).any? + raise "please set environment variable(s) #{missing.join(', ')}" end - new( - path: "/room/#{room_id}/live.json", - host: HOST, - auth: "#{token}:x", - token: token, - room_name: room_name - ) - end - - def initialize(options) - @options = options + @options = ATTR_MAP.map.with_object({}) { |(key, env), opts| opts[key] = ENV[env] } @username_cache = [] - listen + try_icon end - private - - def listen + def start on_message do |item| username = get_username(item["user_id"].to_i) message = "#{item["body"].to_s.gsub(/'/, "\'")}" - system("notify-send --hint=int:transient:1 -u low '#{username}' '#{message}'") + system("notify-send --hint=int:transient:1 -u low#{icon} '#{username}' '#{message}'") end end + private + def on_message EventMachine::run do - stream = Twitter::JSONStream.connect(@options) + stream = Twitter::JSONStream.connect( + host: HOST, + path: "/room/#{room_id}/live.json", + auth: "#{token}:x", + ) stream.each_item do |item| json = JSON::parse(item) if json["type"] == "TextMessage" yield(json) @@ -74,9 +71,36 @@ end @username_cache[id] end + def icon + " -i #{@options[:icon_path]}" + end + + def try_icon + if path = notification_gfx_paths.detect { |p| File.exists?(p) } + @options[:icon_path] = path + end + end + + def notification_gfx_paths + [[NOTIFICATION_GFX_SYSPATH, NOTIFICATION_GFX_FILENAME], + [gem_dir, "assets", NOTIFICATION_GFX_FILENAME]].join('/') + end + + def gem_dir + Gem::Specification.find_by_name("gnome-campfire-notifications").gem_dir + end + def room_url "#{@options[:room_name]}.campfirenow.com" + end + + def room_id + @options[:room_id] + end + + def token + @options[:token] end end