Ejemplo n.º 1
0
func (self *Indexer) decodeNode(schema *superSchema, blobref string) (result interface{}, err os.Error) {
	if schema.Signer == "" {
		return nil, os.NewError("Missing signer")
	}
	var tstruct *time.Time
	tstruct, err = time.Parse(time.RFC3339, schema.Time)
	if err != nil || tstruct == nil {
		return
	}
	t := tstruct.Seconds()
	switch schema.Type {
	case "keep":
		n := &keepNode{blobref: blobref, node: node{time: t, signer: schema.Signer, parent: schema.PermaNode}, dependencies: schema.Dependencies, permission: schema.Permission}
		return n, nil
	case "permanode":
		n := &PermaNode{blobref: blobref, node: node{time: t, signer: schema.Signer, parent: schema.PermaNode}, keeps: make(map[string]string), pendingInvitations: make(map[string]string)}
		return n, nil
	case "mutation":
		if schema.Operation == nil {
			err = os.NewError("mutation is lacking an operation")
			return
		}
		if schema.Site == "" {
			err = os.NewError("mutation is lacking a site identifier")
		}
		n := &mutationNode{node: node{time: t, signer: schema.Signer, parent: schema.PermaNode}}
		n.mutation.Operation = *schema.Operation
		n.mutation.ID = blobref
		n.mutation.Site = schema.Site
		n.mutation.Dependencies = schema.Dependencies
		return n, nil
	case "permission":
		if schema.User == "" {
			err = os.NewError("permission is lacking a target user")
			return
		}
		n := &permissionNode{node: node{time: t, signer: schema.Signer, parent: schema.PermaNode}}
		n.permission.ID = blobref
		n.permission.Dependencies = schema.Dependencies
		n.permission.User = schema.User
		n.permission.Allow = schema.Allow
		n.permission.Deny = schema.Deny
		switch schema.Action {
		case "invite":
			n.action = PermAction_Invite
		case "expel":
			n.action = PermAction_Expel
		case "change":
			n.action = PermAction_Change
		default:
			err = os.NewError("Unknown action type in permission blob")
			return
		}
		return n, nil
	default:
		log.Printf("Unknown schema type")
	}
	return nil, os.NewError("Unknown schema type")
}
Ejemplo n.º 2
0
func serveFile(c *ServiceContext, file string) bool {
	var err os.Error
	var f *os.File
	var t *time.Time
	var modified int64

	file = path.Clean(file)
	if f, err = os.Open(file, os.O_RDONLY, 0); err != nil {
		c.Status(404)
		return false
	}

	defer f.Close()

	stat, _ := f.Stat()
	modified = stat.Mtime_ns / 1e9

	if v, ok := c.Req.Header["If_Modified_Since"]; ok {
		v = v[0:len(v)-3] + "UTC"

		if t, err = time.Parse(v, time.RFC1123); err != nil {
			fmt.Fprintf(os.Stderr, "Unrecognized time format in If_Modified_Since header: %s", v)
			return false
		}

		if modified > t.Seconds() {
			c.Status(200)
		} else {
			c.Status(304)
		}

		return true
	}

	if ctype := mime.TypeByExtension(path.Ext(file)); ctype != "" {
		c.SetHeaders(200, 2592000, ctype, modified)
	} else {
		var data []byte
		var num int64

		buf := bytes.NewBuffer(data)
		if num, err = io.Copyn(buf, f, 1024); err != nil {
			c.Status(500)
			return false
		}

		data = buf.Bytes()
		if isText(data[0:num]) {
			c.SetHeaders(200, 2592000, "text/plain; charset=utf-8", modified)
		} else {
			c.SetHeaders(200, 2592000, "application/octet-stream", modified)
		}
	}

	_, err = c.SendReadWriter(f)
	return err == nil
}
Ejemplo n.º 3
0
//returns posts for a certain date
func (md *MongoDB) GetPostsForDate(date time.Time) (posts []BlogPost, err os.Error) {
	date.Hour = 0
	date.Minute = 0
	date.Second = 0

	start := date.Seconds()
	end := start + (24 * 60 * 60)

	return md.GetPostsForTimespan(start, end, -1)
}
Ejemplo n.º 4
0
// Set Value From HTMLForm Values
func (t *Tasks) SetValue(Id string, r *http.Request) os.Error {

	var err os.Error

	t.UserId = Id
	t.KeyID, err = strconv.Atoi64(r.FormValue(FORM_KEY))
	if err != nil {
		t.KeyID = 0
	}
	t.Status, err = strconv.Atoi(r.FormValue(FORM_STATUS))
	if err != nil {
		log.Println(err)
		return err
	}

	log.Println("Status")

	t.Context = html.EscapeString(r.FormValue(FORM_CONTEXT))
	t.IsUseLimit, err = strconv.Atob(r.FormValue(FORM_LIMIT))
	if err != nil {
		log.Println(err)
		return err
	}

	log.Println("IsUseLimit")

	t.IsComplete = (t.Status == 2)
	t.IsCanceld = (t.Status == 9)

	log.Println("Set Bool Value")

	if t.IsUseLimit {

		log.Println(r.FormValue(FORM_DATE))
		log.Println(time.RFC3339)
		var limit *time.Time
		limit, err = time.Parse("2006-01-02 15:04:05", r.FormValue(FORM_DATE))
		if err == nil {
			t.PlanDate = datastore.SecondsToTime(limit.Seconds())
		} else {
			log.Println(err)
			return err
		}
	}

	log.Println("PostDate")
	t.PostDate = datastore.SecondsToTime(time.Seconds())
	if t.IsComplete {
		t.CompleteDate = datastore.SecondsToTime(time.Seconds())
	}

	return nil

}
Ejemplo n.º 5
0
func solve(birthday time.Time, today time.Time, lifetime int64) (hour, minute, second int) {
	death := time.Time{Year: birthday.Year + lifetime, Month: birthday.Month, Day: birthday.Day}
	total := death.Seconds() - birthday.Seconds()
	cur := today.Seconds() - birthday.Seconds()
	result_s := 3600 * 24 * cur / total
	return int(result_s / 3600), int((result_s / 60) % 60), int(result_s % 60)
}
Ejemplo n.º 6
0
func gdate() string {
	now := time.LocalTime()
	now.Hour = 24
	now.Minute = 60
	now.Second = 60
	var ny time.Time
	ny.Year = now.Year
	ny.Month = 1
	ny.Day = 1
	ny.Hour = 0
	ny.Minute = 0
	ny.Second = 0
	ny.Zone = "CST"
	day := (now.Seconds() - ny.Seconds()) / 86400
	return strconv.Itoa64(day) + ", " + strconv.Itoa64(now.Year)
}
Ejemplo n.º 7
0
// Last-Modified > I-M-S?
func (p *wmDecisionCore) doV3l17() WMDecision {
	t := p.modifiedSince
	var lastModified *time.Time
	var httpCode int
	var httpError os.Error
	lastModified, p.req, p.cxt, httpCode, httpError = p.handler.LastModified(p.req, p.cxt)
	if httpCode > 0 {
		p.writeHaltOrError(httpCode, httpError)
		return wmResponded
	}
	if lastModified == nil || t == nil || lastModified.Seconds() > t.Seconds() {
		return v3m16
	}
	p.resp.WriteHeader(304)
	return wmResponded
}
Ejemplo n.º 8
0
func gtime() string {
	now := time.LocalTime()
	var tsec int64
	{
		var t time.Time = *now
		t.Hour = 0
		t.Minute = 0
		t.Second = 0
		tsec = (now.Seconds() - t.Seconds()) * 1000
	}
	ms := int64(86400 * 1000)
	hour := int64((float64(tsec) / float64(ms)) * 10)
	tsec -= int64((ms / 10) * hour)
	minute := int64((float64(tsec) / (float64(ms) / 10)) * 100)
	tsec -= int64((ms / 1000) * minute)
	second := int64((float64(tsec) / (float64(ms) / 100)) * 10000)
	return strconv.Itoa64(hour) + ":" + strconv.Itoa64(minute) + ":" + strconv.Itoa64(second)
}
Ejemplo n.º 9
0
//returns posts for a certain month
func (md *MongoDB) GetPostsForMonth(date time.Time) (posts []BlogPost, err os.Error) {
	date.Hour = 0
	date.Minute = 0
	date.Second = 0
	date.Day = 1

	next_month := date
	next_month.Month++
	if next_month.Month > 12 {
		next_month.Month = 1
		next_month.Year++
	}

	start := date.Seconds()
	end := next_month.Seconds()

	return md.GetPostsForTimespan(start, end, -1)
}
Ejemplo n.º 10
0
// Last-Modified > I-UM-S?
func (p *wmDecisionCore) doV3h12() WMDecision {
	var lastModified *time.Time
	var httpCode int
	var httpError os.Error
	lastModified, p.req, p.cxt, httpCode, httpError = p.handler.LastModified(p.req, p.cxt)
	if httpCode > 0 {
		p.writeHaltOrError(httpCode, httpError)
		return wmResponded
	}
	t := p.unmodifiedSince
	if t != nil && lastModified != nil {
		log.Print("[WMC]: comparing Last-Modified internal: ", t.Seconds(), " vs. received from client ", lastModified.Seconds())
	}
	if t != lastModified && t != nil && lastModified != nil && lastModified.Seconds() > t.Seconds() {
		p.resp.WriteHeader(412)
		return wmResponded
	}
	return v3i12
}
Ejemplo n.º 11
0
func DisableLoginAt(ds DataStore, userId string, at *time.Time) os.Error {
	user, err := ds.RetrieveUserAccountById(userId)
	if user == nil || err != nil {
		return err
	}
	if user.AllowLogin {
		now := time.UTC().Seconds()
		if user.DisableLoginAt == 0 || user.DisableLoginAt < now || (at != nil && at.Seconds() < now) {
			user.AllowLogin = false
			user.DisableLoginAt = 0
		} else if at == nil {
			user.DisableLoginAt = 0
		} else {
			user.DisableLoginAt = at.Seconds()
		}
		_, err = ds.UpdateUserAccount(user)
	}
	return err
}
Ejemplo n.º 12
0
func (mi *Indexer) PathLookup(signer, base *blobref.BlobRef, suffix string, at *time.Time) (*search.Path, os.Error) {
	// TODO: pass along the at time to a new helper function to
	// filter? maybe not worth it, since this list should be
	// small.
	paths, err := mi.PathsLookup(signer, base, suffix)
	if err != nil {
		return nil, err
	}
	var (
		newest    = int64(0)
		atSeconds = int64(0)
		best      *search.Path
	)
	if at != nil {
		atSeconds = at.Seconds()
	}
	for _, path := range paths {
		t, err := time.Parse(time.RFC3339, trimRFC3339Subseconds(path.ClaimDate))
		if err != nil {
			continue
		}
		secs := t.Seconds()
		if atSeconds != 0 && secs > atSeconds {
			// Too new
			continue
		}
		if newest > secs {
			// Too old
			continue
		}
		// Just right
		newest, best = secs, path
	}
	if best == nil {
		return nil, os.ENOENT
	}
	return best, nil
}
Ejemplo n.º 13
0
//
// See also FreeBSD inetd implementation:
// http://www.freebsd.org/cgi/cvsweb.cgi/src/usr.sbin/inetd/builtins.c?rev=1.45.14.1;content-type=text%2Fplain
// machtime()
//
func RFC868Time(tm time.Time) uint32 {
	tm64 := tm.Seconds()
	// fmt.Println(tm64)
	return uint32((tm64 + TIME_OFFSET) & 0xFFFFFFFF)
}
Ejemplo n.º 14
0
func (rs *ResultSet) timeSeconds(ord int) (value int64, isNull bool) {
	if rs.conn.LogLevel >= LogVerbose {
		defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.timeSeconds"))
	}

	isNull = rs.isNull(ord)
	if isNull {
		return
	}

	val := rs.values[ord]

	var t *time.Time

	switch rs.fields[ord].format {
	case textFormat:
		var format string
		switch rs.fields[ord].typeOID {
		case _DATEOID:
			format = rs.conn.dateFormat

		case _TIMEOID, _TIMETZOID:
			format = rs.conn.timeFormat

		case _TIMESTAMPOID, _TIMESTAMPTZOID:
			format = rs.conn.timestampFormat
		}

		switch rs.fields[ord].typeOID {
		case _TIMETZOID:
			format += "-07"

		case _TIMESTAMPTZOID:
			format += rs.conn.timestampTimezoneFormat
		}

		s := string(val)

		if rs.fields[ord].typeOID != _DATEOID {
			// The resolution of time.Time is seconds, so we will have to drop
			// fractions, if present.
			lastSemicolon := strings.LastIndex(s, ":")
			lastDot := strings.LastIndex(s, ".")
			if lastSemicolon < lastDot {
				// There are fractions
				plusOrMinus := strings.IndexAny(s[lastDot:], "+-")
				if -1 < plusOrMinus {
					// There is a time zone
					s = s[:lastDot] + s[lastDot+plusOrMinus:]
				} else {
					s = s[:lastDot]
				}
			}
		}

		var err os.Error
		t, err = time.Parse(format, s)
		panicIfErr(err)

	case binaryFormat:
		panicNotImplemented()
	}

	value = t.Seconds()

	return
}
Ejemplo n.º 15
0
func getCal(args []string) (result string) {
	var start, end *time.Time

	if args == nil {
		start = time.LocalTime()

		end = time.LocalTime()
		end.Month += scheduleHorizon
		if end.Month > 12 {
			end.Month %= 12
			end.Year++
		}
	} else if len(args) == 1 {
		start = parseTime(args[0])

		if start == nil {
			return fmt.Sprintf("Couldn't parse '%s' as a date, expected format %s", args[0], timeFormatHelp)
		}

		end = new(time.Time)
		*end = *start
		end.Hour = 23
		end.Minute = 59
	} else {
		start = parseTime(args[0])

		if start == nil {
			return fmt.Sprintf("Couldn't parse '%s' as a date, expected format %s", args[0], timeFormatHelp)
		}

		end = parseTime(args[1])

		if end == nil {
			return fmt.Sprintf("Couldn't parse '%s' as a date, expected format %s", args[1], timeFormatHelp)
		}

		end.Hour = 23
		end.Minute = 59

		if start.Seconds() > end.Seconds() {
			result = "StartDate > EndDate, swapping.\n"
			start, end = end, start
		}

	}

	response, _, err := http.Get(fmt.Sprintf("http://www.google.com/calendar/feeds/psuacm%%40cs.pdx.edu/public/basic?start-min=%s&start-max=%s&prettyprint=true&fields=openSearch:totalResults,entry(title,content)&orderby=starttime",
		start.Format(time.RFC3339), end.Format(time.RFC3339)))

	if err != nil {
		errors.Printf("Error retrieving calendar: %v\n", err)
		return "Error retrieving calendar from teh google"
	}

	defer response.Body.Close()

	f := &calFeed{}
	err = xml.Unmarshal(response.Body, f)

	if err != nil {
		errors.Printf("Error parsing calendar xml: %v\n", err)
		return "XML Fail:  Go yell at cbeck for not using json."
	}

	for _, event := range f.Entry {
		result = fmt.Sprintf("%s: %s\n", event.Content[6:strings.Index(event.Content, " to")], event.Title) + result
	}

	if f.TotalResults == 0 {
		if start.Day == end.Day && start.Month == end.Month && start.Year == end.Year {
			result += fmt.Sprintf("Nothing scheduled on %s", start.Format(timeFormat))
		} else {
			result += fmt.Sprintf("Nothing scheduled in range %s - %s", start.Format(timeFormat), end.Format(timeFormat))
		}
	}

	return
}
Ejemplo n.º 16
0
func EncodeTime(buf *bytes.Buffer, val time.Time) {
	w64 := make([]byte, _WORD64)
	mtime := val.Seconds() * 1000
	pack.PutUint64(w64, uint64(mtime))
	buf.Write(w64)
}