Rubyでカウンタ

カウンタです、Rubyで書きました。

You are # visitor to this Site.

アクセス解析機能もつけよう思ったが、まだ未実装。コードは"続き"にのっけとくね。
18:00現在、少し変えてみました。次はmod_rubyに対応させようかと…
21:00現在、mod_rubyをONにしました。特にコードを変えるところはなかった…
しまった…、クッキーから番号読むようにしないと駄目だ…(現在の使用だと最新のカウンタ番号しか表示されない=セッション機能がぱー)
23:00、なおしました。でも操作の過程で、今までのデータけしちゃったよー

#!/usr/local/bin/ruby

#written by fenrir

require "cgi"
require "pstore"
require "singleton"

#File Setting
LOCK_FILE = "lockfile"
DB_FILE = "access.db"

#Cookie Setting
KEY_ANALYZER = "analyzerN"
DOMAIN = "fenrir.naruoka.org"
PATH = "/"
INTERVAL = 30 * 60            #sec
EXPIRE = 365 * 24 * 60 * 60    #sec

#Log Setting
FNAME_COUNT = "COUNT"
TODAY = "TODAY"
THIS_MONTH = "THIS_MONTH"
TOTAL = "TOTAL"

def lock
    begin
        begin
            f = File.open(LOCK_FILE, "r+")
        rescue
            f = File.open(LOCK_FILE, "w+")
        end
        f.flock(File::LOCK_EX)
        yield
    ensure
        f.flock(File::LOCK_UN)
        f.close
    end
end

def bakeCookie values
    return CGI::Cookie.new(getRawCookie(values).values.first)
end

def getRawCookie values
    return {KEY_ANALYZER => {"name"    => KEY_ANALYZER,
                             "value"    => values,
                             "domain"    => DOMAIN,
                             "path"    => PATH
                             }}
end

def to_t time
    if time.kind_of? Time
        return time
    else
        /(.*?)\s(.*?)\s(.*?)\s(.*?):(.*?):(.*?)\s(.*?)\+?.*?\s(.*)/ =~ time
        return Time.local($8, $2, $3, $4, $5, $6)
    end
end


lock{

    db = PStore.new DB_FILE
    now = Time.now

case ARGV.shift
when "test"
    class CGI
        CGI_PARAMS = {'form'=>['value']}
        CGI_COOKIES = {KEY_ANALYZER => bakeCookie([(Time.now - 40 * 60).to_s, "0", "0"])}
    end
when "log"
    db.transaction{
        p db[FNAME_COUNT]
    }
    exit
end
    
    db.transaction{
        count = (((count = db[FNAME_COUNT]) ? count : 0) rescue 0)
    
        #Count
        cgi = CGI.new
        if cgi.cookies == nil or (cookie = cgi.cookies[KEY_ANALYZER]) == []
            db[FNAME_COUNT] = (count = count + 1)
            cookie = bakeCookie([now.to_s, "1", count.to_s])
        else
            if now - to_t(cookie[0]) > INTERVAL
                db[FNAME_COUNT] = (count = count + 1)
                cookie[1] = (cookie[1].to_i + 1).to_s
                cookie[2] = count.to_s
            else
                count = cookie[2].to_i
            end
            cookie[0] = now.to_s
        end
        cookie.expires = now + 365 * 24 * 60 * 60
    
        #Output
        cgi.out({"cookie" => cookie, "type" => "text/javascript"}){
            "function getCount(){return " + count.to_s + ";}\n"
        }
        
        #Analyze
        #TRAGET = ["REMOTE_ADDR", "REMOTE_HOST", "HTTP_ACCEPT_CHARSET", "HTTP_ACCEPT_ENCODING", "HTTP_ACCEPT_LANGUAGE", "HTTP_FROM","HTTP_HOST", "HTTP_REFERER","HTTP_USER_AGENT"]
    }
}

September 30, 2003 15:26 fenrir が投稿 : 固定リンク | | このエントリーを含むはてなブックマーク

コメント

コメントする