Commit 91ab6ce

mo khan <mo@mokhan.ca>
2015-02-05 04:03:29
create fake agent to watch filesystem for changes and publish to query api.
1 parent 5bb4239
Changed files (3)
lib/tasks/agent.rake
@@ -0,0 +1,8 @@
+namespace :agent do
+  desc "watch all files"
+  task watch: :environment do
+    require 'fake_agent'
+    agent = FakeAgent.new(Agent.first.id, 'http://localhost:3000')
+    agent.run(Dir.pwd)
+  end
+end
lib/tasks/scan.rake
@@ -1,22 +0,0 @@
-namespace :scan do
-  desc "scan all files"
-  task dir: :environment do
-    require 'net/http'
-
-    agent = Agent.first
-    Dir['**/**/*'].each do |file|
-      if File.file?(file)
-        result = `shasum -a 256 #{file}`
-        sha, * = result.split(' ')
-        full_path = File.expand_path(file)
-
-        url = "http://localhost:3000/agents/#{agent.id}/files/#{sha}"
-        Typhoeus.get(url, body: { 
-          payload: {
-            full_path: full_path 
-          }
-        })
-      end
-    end
-  end
-end
lib/fake_agent.rb
@@ -0,0 +1,41 @@
+class FakeAgent
+  attr_reader :id, :endpoint
+
+  def initialize(id, endpoint)
+    @id = id
+    @endpoint = endpoint
+  end
+
+  def run(directory)
+    listener = Listen.to(directory, debug: true) do |modified, added, removed|
+      publish_event(:modified, modified)
+      publish_event(:added, added)
+      publish_event(:removed, removed)
+    end
+
+    listener.start
+    sleep
+  end
+
+  private
+
+  def publish_event(event, files)
+    files.each do |file|
+      fingerprint = fingerprint_for(file)
+      url = "#{endpoint}/agents/#{id}/files/#{fingerprint}"
+      puts url
+      Typhoeus.get(url, body: {
+        payload: {
+          event: event,
+          full_path: file
+        }
+      })
+    end
+  end
+
+  def fingerprint_for(file)
+    result = `shasum -a 256 #{file}`
+    sha, * = result.split(' ')
+    sha
+  end
+end