# $Id: traffic.py,v 2.3 2015/10/28 07:42:30 slobin Exp $

import ast, os, re, time, urllib2

def write_log_file(*args):
    print >> logfile, time.ctime(), " ".join(args)

os.chdir(os.path.expanduser("~/public_html/traffic"))
logfile = open(time.strftime("%Y-%m.txt"), "a")

try:
    link = urllib2.urlopen("http://jgo.maps.yandex.net/trf/stat.js")
    page = link.read()
    t1 = re.search(r'(\{.*\})\)\;$', page).group(1)
    t2 = re.sub(r'([{,])(\w+)(\:)', r'\1"\2"\3', t1)
    data = ast.literal_eval(t2)
    hash = dict((x["regionId"], x) for x in data["regions"])
    item = hash["213"] # MOSCOW
    write_log_file(item["level"], item["localTime"])
except Exception, err:
    write_log_file("ERR:", str(err))
