Skip to content

Instantly share code, notes, and snippets.

@phoenixweiss
Last active November 8, 2016 06:42
Show Gist options
  • Save phoenixweiss/d0ce28e9a16326155bcd1d3d6f70d11f to your computer and use it in GitHub Desktop.
Save phoenixweiss/d0ce28e9a16326155bcd1d3d6f70d11f to your computer and use it in GitHub Desktop.
Sinatra Rack App support for http://clickfrog.ru via module converted from Rails ActionController
require 'sinatra'
# You could move entire module to separate file and include in main app via require_relative
module ClickFrog
def clickfrog_counter
return unless request.host && request.referer
require 'socket'
data = Hash[
'REMOTE_ADDR' => request.env['REMOTE_ADDR'],
'HTTP_USER_AGENT' => request.env['HTTP_USER_AGENT'],
'HTTP_HOST' => request.env['HTTP_HOST'],
'REQUEST_METHOD' => request.env['REQUEST_METHOD'],
'REQUEST_URI' => request.env['REQUEST_URI'],
'HTTP_REFERER' => request.env['HTTP_REFERER'],
'QUERY_STRING' => request.env['QUERY_STRING'],
'HTTP_X_FORWARDED_FOR' => request.ip
].delete_if { |k, v| v.to_s.strip.empty? }
require 'json' # make sure json is accessible
data = JSON.dump(data) # unicode escaping in to_json
data = ERB::Util.url_encode(data) # try url encode method
data.insert(0, 'header=')
m_id = ('%08x' % (Time.now.to_f * 10000))[-8..-1] + ('%08x' % data.hash.abs)[0..7]
data = "CFSTAT##{m_id}[#{data}]END"
sock = UDPSocket.new(Socket::AF_INET)
sock.connect('stat.clickfrog.ru', 83)
5.times do
begin
sock.send(data, 0)
rescue
clickfrog_counter_tcp(data)
end
end
end
def clickfrog_counter_tcp(msg)
require "uri"
require "net/http"
url = URI.parse('http://stat.clickfrog.ru/server_side_action.php')
req = Net::HTTP::Post.new(url.path)
req.body = msg
con = Net::HTTP.new(url.host, url.port)
con.start {|http| http.request(req)}
end
end
# You must include module in the main app body
include ClickFrog
before do
# Invoke 'clickfrog_counter' method before anythimg else
clickfrog_counter
end
get '/' do
# Do not forget to proper set up your main app view
erb :index
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment