示例#1
0
// 获取当前登录用户信息(常用信息)
func FindCurrentUser(username string) (user map[string]interface{}, err error) {
	userLogin := model.NewUserLogin()
	err = userLogin.Where("username="******"获取用户 %s 信息失败:%s", username, err)
		return
	}
	if userLogin.Uid == 0 {
		logger.Infof("用户 %s 不存在!", username)
		return
	}
	user = map[string]interface{}{
		"uid":      userLogin.Uid,
		"username": userLogin.Username,
		"email":    userLogin.Email,
	}

	// 获取未读消息数
	user["msgnum"] = FindNotReadMsgNum(userLogin.Uid)

	// 获取角色信息
	userRoleList, err := model.NewUserRole().Where("uid=" + strconv.Itoa(userLogin.Uid)).FindAll()
	if err != nil {
		logger.Errorf("获取用户 %s 角色 信息失败:%s", username, err)
		return
	}
	for _, userRole := range userRoleList {
		if userRole.Roleid <= model.AdminMinRoleId {
			// 是管理员
			user["isadmin"] = true
		}
	}
	return
}
示例#2
0
// 通过唯一键(uid或username)获取用户信息
func findUserByUniq(field, val string) *model.User {
	user := model.NewUser()
	err := user.Where(field + "=" + val).Find()
	if err != nil {
		logger.Errorf("获取用户 %s 信息失败:%s", val, err)
		return nil
	}
	if user.Uid == 0 {
		return nil
	}

	// 获取用户角色信息
	userRoleList, err := model.NewUserRole().
		Order("roleid ASC").Where("uid="+strconv.Itoa(user.Uid)).FindAll("uid", "roleid")
	if err != nil {
		logger.Errorf("获取用户 %s 角色 信息失败:%s", val, err)
		return nil
	}

	if roleNum := len(userRoleList); roleNum > 0 {
		user.Roleids = make([]int, roleNum)
		user.Rolenames = make([]string, roleNum)

		for i, userRole := range userRoleList {
			user.Roleids[i] = userRole.Roleid
			user.Rolenames[i] = Roles[userRole.Roleid-1].Name
		}
	}

	return user
}
示例#3
0
// 获取单个用户信息
func FindUserByUsername(username string) *model.User {
	user := model.NewUser()
	err := user.Where("username="******"获取用户 %s 信息失败:%s", username, err)
		return nil
	}
	if user.Uid == 0 {
		return nil
	}

	// 获取角色信息
	userRoleList, err := model.NewUserRole().Where("uid=" + strconv.Itoa(user.Uid)).FindAll()
	if err != nil {
		logger.Errorf("获取用户 %s 角色 信息失败:%s", username, err)
		return nil
	}
	for _, userRole := range userRoleList {
		if len(user.Roleids) == 0 {
			user.Rolenames = []string{model.AllRole[userRole.Roleid].Name}
		} else {
			user.Rolenames = append(user.Rolenames, model.AllRole[userRole.Roleid].Name)
		}
	}
	return user
}
示例#4
0
文件: view.go 项目: kuainiao/btcrobot
// 在逻辑处理完之后,最后展示页面
func (this *ViewFilter) PostFilter(rw http.ResponseWriter, req *http.Request) bool {
	contentHtml := req.FormValue(CONTENT_TPL_KEY)
	if contentHtml == "" {
		return true
	}
	contentHtmls := strings.Split(contentHtml, ",")
	for i, contentHtml := range contentHtmls {
		contentHtmls[i] = config.ROOT + strings.TrimSpace(contentHtml)
	}

	// 为了使用自定义的模板函数,首先New一个以第一个模板文件名为模板名。
	// 这样,在ParseFiles时,新返回的*Template便还是原来的模板实例
	tpl, err := template.New(this.baseTplName).Funcs(funcMap).ParseFiles(append(this.commonHtmlFiles, contentHtmls...)...)
	if err != nil {
		logger.Errorf("解析模板出错(ParseFiles):[%q] %s\n", req.RequestURI, err)
		return false
	}
	// 如果没有定义css和js模板,则定义之
	if jsTpl := tpl.Lookup("js"); jsTpl == nil {
		tpl.Parse(`{{define "js"}}{{end}}`)
	}
	if jsTpl := tpl.Lookup("css"); jsTpl == nil {
		tpl.Parse(`{{define "css"}}{{end}}`)
	}

	data := GetData(req)

	err = tpl.Execute(rw, data)
	if err != nil {
		logger.Errorf("执行模板出错(Execute):[%q] %s\n", req.RequestURI, err)
	}
	return true
}
示例#5
0
func (w *Huobi) getOrderBook(symbol string) (ret bool, hbOrderBook OrderBook) {
	// init to false
	ret = false
	var huobisymbol string
	if symbol == "btc_cny" {
		huobisymbol = "huobibtccny"
	} else {
		huobisymbol = "huobiltccny"
		logger.Fatal("huobi does not support LTC by now, wait for huobi provide it.", huobisymbol)
		return
	}

	rnd := util.RandomString(20)

	now := time.Now().UnixNano() / 1000000

	req, err := http.NewRequest("GET", fmt.Sprintf(Config["hb_trade_detail"], rnd, now, now), nil)
	if err != nil {
		logger.Fatal(err)
		return
	}

	req.Header.Set("Referer", Config["base_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")
	req.Header.Add("Accept-Encoding", "identity")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logger.Traceln(err)
		logger.Traceln(req)
		logger.Traceln(resp)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		logger.Errorf("HTTP returned status %v", resp)
		return
	}

	var body string
	contentEncoding := resp.Header.Get("Content-Encoding")
	logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
	switch contentEncoding {
	case "gzip":
		body = util.DumpGZIP(resp.Body)
	default:
		bodyByte, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Errorln("read the http stream failed")
			return
		} else {
			body = string(bodyByte)
			ioutil.WriteFile("cache/OrderBook.json", bodyByte, 0644)
		}
	}

	return w.analyzeOrderBook(body)
}
示例#6
0
//entry call
func Tick(tradeAPI TradeAPI, records []Record) bool {

	strategyName := Option["strategy"]
	strategy, ok := strategys[strategyName]
	if !ok {
		logger.Errorf("sql: unknown strategy %q (forgotten import? private strategy?)", strategyName)
		return false
	}

	// length := len(records)
	// //
	// if length == 0 {
	// 	logger.Errorln("warning:detect exception data", len(records))
	// 	return false
	// }

	// //check exception data in trade center
	// if checkException(records[length-2], records[length-1]) == false {
	// 	logger.Errorln("detect exception data of trade center",
	// 		records[length-2].Close, records[length-1].Close, records[length-1].Volumn)
	// 	return false
	// }

	gTradeAPI = tradeAPI
	return strategy.Tick(records)
}
示例#7
0
// 登录;成功返回用户登录信息(user_login)
func Login(username, passwd string) (*model.UserLogin, error) {
	userLogin := model.NewUserLogin()
	err := userLogin.Where("username="******" OR email=" + username).Find()
	if err != nil {
		logger.Errorf("用户 %s 登录错误:%s", username, err)
		return nil, errors.New("内部错误,请稍后再试!")
	}
	// 校验用户
	if userLogin.Uid == 0 {
		logger.Infof("用户名 %s 不存在", username)
		return nil, ErrUsername
	}
	passcode := userLogin.GetPasscode()
	md5Passwd := util.Md5(passwd + passcode)
	logger.Debugf("passwd: %s, passcode: %s, md5passwd: %s, dbpasswd: %s", passwd, passcode, md5Passwd, userLogin.Passwd)
	if md5Passwd != userLogin.Passwd {
		logger.Infof("用户名 %s 填写的密码错误", username)
		return nil, ErrPasswd
	}

	// 登录,活跃度+1
	go IncUserWeight("uid="+strconv.Itoa(userLogin.Uid), 1)

	return userLogin, nil
}
示例#8
0
// 记录用户最后登录时间
func RecordLoginTime(username string) error {
	userLogin := model.NewUserLogin()
	err := userLogin.Set("login_time=" + time.Now().Format("2006-01-02 15:04:05")).Where("username="******"记录用户 %s 登录时间错误:%s", username, err)
	}
	return err
}
示例#9
0
// 获取单个 Topic 信息(用于编辑)
func FindTopic(tid string) *model.Topic {
	topic := model.NewTopic()
	err := topic.Where("tid=?", tid).Find()
	if err != nil {
		logger.Errorf("FindTopic [%s] error:%s\n", tid, err)
	}

	return topic
}
示例#10
0
// 获取单个 Resource 信息(用于编辑)
func FindResourceById(id string) *model.Resource {
	resource := model.NewResource()
	err := resource.Where("id=?", id).Find()
	if err != nil {
		logger.Errorf("FindResourceById [%s] error:%s\n", id, err)
	}

	return resource
}
示例#11
0
func main() {
	// Metron is intended to be light-weight so we occupy only one core
	runtime.GOMAXPROCS(1)

	flag.Parse()
	config, err := config.ParseConfig(*configFilePath)
	if err != nil {
		panic(fmt.Errorf("Unable to parse config: %s", err))
	}

	logger := logger.NewLogger(*debug, *logFilePath, "metron", config.Syslog)

	statsStopChan := make(chan struct{})
	batcher, eventWriter := initializeMetrics(config, statsStopChan, logger)

	go func() {
		err := http.ListenAndServe(net.JoinHostPort("localhost", pprofPort), nil)
		if err != nil {
			logger.Errorf("Error starting pprof server: %s", err.Error())
		}
	}()

	logger.Info("Startup: Setting up the Metron agent")
	marshaller, err := initializeDopplerPool(config, batcher, logger)
	if err != nil {
		panic(fmt.Errorf("Could not initialize doppler connection pool: %s", err))
	}

	messageTagger := tagger.New(config.Deployment, config.Job, config.Index, marshaller)
	aggregator := messageaggregator.New(messageTagger, logger)
	eventWriter.SetWriter(aggregator)

	dropsondeUnmarshaller := eventunmarshaller.New(aggregator, batcher, logger)
	metronAddress := fmt.Sprintf("127.0.0.1:%d", config.IncomingUDPPort)
	dropsondeReader, err := networkreader.New(metronAddress, "dropsondeAgentListener", dropsondeUnmarshaller, logger)
	if err != nil {
		panic(fmt.Errorf("Failed to listen on %s: %s", metronAddress, err))
	}

	logger.Info("metron started")
	go dropsondeReader.Start()

	dumpChan := signalmanager.RegisterGoRoutineDumpSignalChannel()
	killChan := signalmanager.RegisterKillSignalChannel()

	for {
		select {
		case <-dumpChan:
			signalmanager.DumpGoRoutine()
		case <-killChan:
			logger.Info("Shutting down")
			close(statsStopChan)
			return
		}
	}
}
示例#12
0
func ModifyComment(cid, content string) (errMsg string, err error) {
	err = model.NewComment().Set("content=?", content).Where("cid=" + cid).Update()
	if err != nil {
		logger.Errorf("更新评论内容 【%s】 失败:%s\n", cid, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}

	return
}
示例#13
0
// UpdateUserStatus 更新用户状态
func UpdateUserStatus(uid, status int) {
	setClause := "status=" + strconv.Itoa(status)
	err := model.NewUser().Set(setClause).Where("uid=?", uid).Update()
	if err != nil {
		logger.Errorf("更新用户 【%s】 状态失败:%s", uid, err)
		return
	}

	return
}
示例#14
0
// 更新用户密码(用户名或email)
func UpdatePasswd(username, passwd string) (string, error) {
	userLogin := model.NewUserLogin()
	passwd = userLogin.GenMd5Passwd(passwd)
	err := userLogin.Set("passwd=" + passwd + ",passcode=" + userLogin.GetPasscode()).Where("username="******" OR email=" + username).Update()
	if err != nil {
		logger.Errorf("用户 %s 更新密码错误:%s", username, err)
		return "对不起,内部服务错误!", err
	}
	return "", nil
}
示例#15
0
func RunCreateVm(ctx context.Context, vmDeviceId uint) error {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	logger, ok := middleware.LoggerFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	vmDevice, err := repo.GetVmDeviceById(vmDeviceId)
	if err != nil {
		return err
	}

	device, err := repo.GetDeviceById(vmDevice.DeviceID)
	if err != nil {
		return err
	}

	var cmdFormat = `LANG=C virt-install --connect qemu+ssh://root@%s/system \
--name=%s \
--os-type=windows \
--vcpus=%d \
--ram=%d \
--hvm \
--boot hd,network,menu=on \
--accelerate \
--graphics vnc,listen=0.0.0.0,port=%s \
--noautoconsole \
--autostart \
--network bridge=br0,model=virtio,mac=%s \
--disk path=/dev/VolGroup0/%s,device=disk,bus=virtio,cache=none,sparse=false,format=raw`
	var cmd = fmt.Sprintf(cmdFormat,
		device.Ip,
		vmDevice.Hostname,
		vmDevice.CpuCoresNumber,
		vmDevice.MemoryCurrent,
		vmDevice.VncPort,
		vmDevice.Mac,
		vmDevice.Hostname)
	logger.Debugf("create vm:%s", cmd)
	var runResult = "执行脚本:\n" + cmd
	bytes, err := util.ExecScript(cmd)
	logger.Debugf("create result:%s", string(bytes))
	runResult += "\n\n" + "执行结果:\n" + string(bytes)
	if err != nil {
		logger.Errorf("create error:%s", err.Error())
		runResult += "\n\n" + "错误信息:\n" + err.Error()
		return errors.New(runResult)
	}
	return nil
}
示例#16
0
// 没有权限时,返回 403
func (this *AdminFilter) PreErrorHandle(rw http.ResponseWriter, req *http.Request) {
	rw.WriteHeader(http.StatusForbidden)

	tpl, err := template.ParseFiles(config.ROOT+"/template/admin/simple_base.html", config.ROOT+"/template/admin/403.html")
	if err != nil {
		logger.Errorf("解析模板出错(ParseFiles):[%q] %s\n", req.RequestURI, err)
		fmt.Fprint(rw, "403 Forbidden<br/>Go "+runtime.Version())
		return
	}

	// 当前用户信息
	me, _ := CurrentUser(req)
	data := map[string]interface{}{"me": me}

	if err = tpl.Execute(rw, data); err != nil {
		logger.Errorf("执行模板出错(Execute):[%q] %s\n", req.RequestURI, err)
		fmt.Fprint(rw, "403 Forbidden<br/>Go "+runtime.Version())
		return
	}
}
示例#17
0
func UpdateUser(form url.Values) (errMsg string, err error) {
	fields := []string{"name", "open", "city", "company", "github", "weibo", "website", "status", "introduce"}
	setClause := GenSetClause(form, fields)
	username := form.Get("username")
	err = model.NewUser().Set(setClause).Where("username="******"更新用户 【%s】 信息失败:%s", username, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}
	return
}
示例#18
0
// 通过UID获取用户名
func FindUsernameByUid(uid int) string {
	user := model.NewUser()
	err := user.Where("uid=" + strconv.Itoa(uid)).Find()
	if err != nil {
		logger.Errorf("获取用户 %s 信息失败:%s", uid, err)
		return ""
	}
	if user.Uid == 0 {
		return ""
	}

	return user.Username
}
示例#19
0
func (w *Okcoin) getOrderBook(symbol string) (ret bool, orderBook OrderBook) {
	//init to false
	ret = false
	req, err := http.NewRequest("GET", fmt.Sprintf(Config["ok_depth_url"], symbol), nil)
	if err != nil {
		logger.Fatal(err)
		return
	}

	req.Header.Set("Referer", Config["ok_base_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")

	logger.Traceln(req)

	c := util.NewTimeoutClient()
	logger.Tracef("HTTP req begin getOrderBook")
	resp, err := c.Do(req)
	logger.Tracef("HTTP req end getOrderBook")
	if err != nil {
		logger.Traceln(err)
		return
	}

	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		logger.Errorf("HTTP returned status %v", resp)
		return
	}

	var body string
	contentEncoding := resp.Header.Get("Content-Encoding")
	logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
	switch contentEncoding {
	case "gzip":
		body = util.DumpGZIP(resp.Body)

	default:
		bodyByte, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Errorln("read the http stream failed")
			return
		} else {
			body = string(bodyByte)

			ioutil.WriteFile("cache/okdepth.json", bodyByte, 0644)
		}
	}

	return w.analyzeOrderBook(body)
}
示例#20
0
func RunCreateVol(ctx context.Context, vmDeviceId uint) error {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	logger, ok := middleware.LoggerFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	conf, ok := middleware.ConfigFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	vmDevice, err := repo.GetVmDeviceById(vmDeviceId)
	if err != nil {
		return err
	}

	device, err := repo.GetDeviceById(vmDevice.DeviceID)
	if err != nil {
		return err
	}

	storage := conf.Vm.Storage
	if storage == "" {
		storage = "guest_images_lvm"
	}

	var cmdFormat = `LANG=C virsh --connect qemu+ssh://root@%s/system vol-create-as %s %s %dG`
	var cmd = fmt.Sprintf(cmdFormat,
		device.Ip,
		storage,
		vmDevice.Hostname,
		vmDevice.DiskSize)
	logger.Debugf("vm create vol:%s", cmd)
	var runResult = "执行脚本:\n" + cmd
	bytes, err := util.ExecScript(cmd)
	logger.Debugf("create result:%s", string(bytes))
	runResult += "\n\n" + "执行结果:\n" + string(bytes)
	if err != nil {
		logger.Errorf("create error:%s", err.Error())
		runResult += "\n\n" + "错误信息:\n" + err.Error()
		return errors.New(runResult)
	}
	return nil
}
示例#21
0
文件: user.go 项目: jackyxie/btcrobot
func UpdateUserReminder(form url.Values) (errMsg string, err error) {
	fields := []string{"lowestPrice", "highestPrice", "Emailnotice"}
	setClause := GenSetClause(form, fields)
	username := form.Get("username")
	err = model.NewUser().Set(setClause).Where("username="******"更新用户 【%s】 reminder信息失败:%s", username, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}

	// 修改用户资料,活跃度+1
	go IncUserWeight("username="+username, 1)

	return
}
示例#22
0
// 修改动态信息
func ModifyDynamic(form url.Values) (errMsg string, err error) {

	fields := []string{
		"content", "url", "seq", "dmtype",
	}
	query, args := updateSetClause(form, fields)

	id := form.Get("id")

	err = model.NewDynamic().Set(query, args...).Where("id=" + id).Update()
	if err != nil {
		logger.Errorf("更新动态 【%s】 信息失败:%s\n", id, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}

	return
}
示例#23
0
// entry call
func Tick(tradeAPI TradeAPI, records []Record) bool {
	strategyName := Option["strategy"]
	strategy, ok := strategys[strategyName]
	if !ok {
		logger.Errorf("sql: unknown strategy %q (forgotten import? private strategy?)", strategyName)
		return false
	}

	logger.Infoln("strategyName", strategyName)

	if strategyName != "OPENORDER" {
		length = len(records)
		if length == 0 {
			logger.Errorln("warning:detect exception data", len(records))
			return false
		}

		fmt.Println(length, records)
		if length < 2 {
			logger.Errorln("warning:detect exception data", len(records))
			return false
		}

		if Option["tick_interval"] != "1" {
			// check exception data in trade center
			if CheckException(records[length-2], records[length-1]) == false {
				logger.Errorln("detect exception data of trade center",
					records[length-2].Close, records[length-1].Close, records[length-1].Volumn)
				return false
			}
		}

		lastPrice = records[length-1].Close
	}

	gTradeAPI = tradeAPI

	return strategy.Tick(records)
}
示例#24
0
// 修改主题
// user 修改人的(有可能是作者或管理员)
func ModifyTopic(user map[string]interface{}, form url.Values) (errMsg string, err error) {
	uid := user["uid"].(int)
	form.Set("editor_uid", strconv.Itoa(uid))

	fields := []string{"title", "content", "nid", "editor_uid"}
	query, args := updateSetClause(form, fields)

	tid := form.Get("tid")

	err = model.NewTopic().Set(query, args...).Where("tid=" + tid).Update()
	if err != nil {
		logger.Errorf("更新主题 【%s】 信息失败:%s\n", tid, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}

	username := user["username"].(string)
	// 修改主题,活跃度+2
	go IncUserWeight("username="+username, 2)

	return
}
示例#25
0
//restart vm
func RunReStartVm(ctx context.Context, vmDeviceId uint) error {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	logger, ok := middleware.LoggerFromContext(ctx)
	if !ok {
		return errors.New("内部服务器错误")
	}

	vmDevice, err := repo.GetVmDeviceById(vmDeviceId)
	if err != nil {
		return err
	}

	device, err := repo.GetDeviceById(vmDevice.DeviceID)
	if err != nil {
		return err
	}

	var cmdFormat = `LANG=C virsh --connect qemu+ssh://root@%s/system 'destroy %s; start %s'`
	var cmd = fmt.Sprintf(cmdFormat,
		device.Ip,
		vmDevice.Hostname,
		vmDevice.Hostname)
	logger.Debugf("restart vm:%s", cmd)
	var runResult = "执行脚本:\n" + cmd
	bytes, err := util.ExecScript(cmd)
	logger.Debugf("restart result:%s", string(bytes))
	runResult += "\n\n" + "执行结果:\n" + string(bytes)
	if err != nil {
		logger.Errorf("restart error:%s", err.Error())
		runResult += "\n\n" + "错误信息:\n" + err.Error()
		return errors.New(runResult)
	}
	return nil
}
示例#26
0
//entry call
func Perform(strageteyName string, tradeAPI TradeAPI, Time []string, Price []float64, Volumn []float64) bool {
	strategy, ok := strategys[strageteyName]
	if !ok {
		logger.Errorf("sql: unknown strategy %q (forgotten import?)", strageteyName)
		return false
	}

	//
	if len(Time) == 0 || len(Price) == 0 || len(Volumn) == 0 {
		logger.Errorln("warning:detect exception data", len(Time), len(Price), len(Volumn))
		return false
	}

	length := len(Price)

	//check exception data in trade center
	if checkException(Price[length-2], Price[length-1], Volumn[length-1]) == false {
		logger.Errorln("detect exception data of trade center", Price[length-2], Price[length-1], Volumn[length-1])
		return false
	}

	return strategy.Perform(tradeAPI, Time, Price, Volumn)
}
示例#27
0
// 修改文章信息
func ModifyArticle(user map[string]interface{}, form url.Values) (errMsg string, err error) {

	username := user["username"].(string)
	form.Set("op_user", username)

	fields := []string{
		"title", "url", "cover", "author", "author_txt",
		"lang", "pub_date", "content",
		"tags", "status", "op_user",
	}
	query, args := updateSetClause(form, fields)

	id := form.Get("id")

	err = model.NewArticle().Set(query, args...).Where("id=" + id).Update()
	if err != nil {
		logger.Errorf("更新文章 【%s】 信息失败:%s\n", id, err)
		errMsg = "对不起,服务器内部错误,请稍后再试!"
		return
	}

	return
}
示例#28
0
// 增加(修改)资源
func PublishResource(user map[string]interface{}, form url.Values) (err error) {
	uid := user["uid"].(int)

	resource := model.NewResource()

	if form.Get("id") != "" {
		err = resource.Where("id=?", form.Get("id")).Find()
		if err != nil {
			logger.Errorln("Publish Resource find error:", err)
			return
		}

		isAdmin := false
		if _, ok := user["isadmin"]; ok {
			isAdmin = user["isadmin"].(bool)
		}
		if resource.Uid != uid && !isAdmin {
			err = NotModifyAuthorityErr
			return
		}

		fields := []string{"title", "catid", "form", "url", "content"}
		if form.Get("form") == model.LinkForm {
			form.Set("content", "")
		} else {
			form.Set("url", "")
		}

		id := form.Get("id")
		query, args := updateSetClause(form, fields)
		err = resource.Set(query, args...).Where("id=?", id).Update()
		if err != nil {
			logger.Errorf("更新資源 【%s】 信息失败:%s\n", id, err)
			return
		}

		// 修改資源,活跃度+2
		go IncUserWeight("uid="+strconv.Itoa(uid), 2)
	} else {

		util.ConvertAssign(resource, form)

		resource.Uid = uid
		resource.Ctime = util.TimeNow()

		var id int64
		id, err = resource.Insert()

		if err != nil {
			logger.Errorln("Publish Resource error:", err)
			return
		}

		// 存扩展信息
		resourceEx := model.NewResourceEx()
		resourceEx.Id = int(id)
		if _, err = resourceEx.Insert(); err != nil {
			logger.Errorln("PublishResource Ex error:", err)
			return
		}

		// 给 被@用户 发系统消息
		/*
			ext := map[string]interface{}{
				"objid":   id,
				"objtype": model.TYPE_RESOURCE,
				"uid":     user["uid"],
				"msgtype": model.MsgtypePublishAtMe,
			}
			go SendSysMsgAtUsernames(form.Get("usernames"), ext)
		*/

		// 发布主题,活跃度+10
		go IncUserWeight("uid="+strconv.Itoa(uid), 10)
	}

	return
}
示例#29
0
func openDB(dbpath string, create bool) (pbdb *LevelDb, err error) {
	var db LevelDb
	var tlDb *leveldb.DB
	var dbversion int32

	defer func() {
		if err == nil {
			db.lDb = tlDb

			pbdb = &db
		}
	}()

	if create == true {
		err = os.Mkdir(dbpath, 0750)
		if err != nil {
			logger.Errorf("mkdir failed %v %v", dbpath, err)
			//return
		}
	} else {
		_, err = os.Stat(dbpath)
		if err != nil {
			err = DbDoesNotExist
			return
		}
	}

	needVersionFile := false
	verfile := dbpath + ".ver"
	fi, ferr := os.Open(verfile)
	if ferr == nil {
		defer fi.Close()

		ferr = binary.Read(fi, binary.LittleEndian, &dbversion)
		if ferr != nil {
			dbversion = ^0
		}
	} else {
		if create == true {
			needVersionFile = true
			dbversion = CurrentDBVersion
		}
	}

	myCache := cache.NewEmptyCache()
	opts := &opt.Options{
		BlockCache:   myCache,
		MaxOpenFiles: 256,
		Compression:  opt.NoCompression,
	}

	switch dbversion {
	case 0:
		opts = &opt.Options{}
	case 1:
		// uses defaults from above
	default:
		err = fmt.Errorf("unsupported db version %v", dbversion)
		return
	}

	tlDb, err = leveldb.OpenFile(dbpath, opts)
	if err != nil {
		return
	}

	// If we opened the database successfully on 'create'
	// update the
	if needVersionFile {
		fo, ferr := os.Create(verfile)
		if ferr != nil {
			// TODO(design) close and delete database?
			//err = ferr
			//return
		}
		defer fo.Close()
		err = binary.Write(fo, binary.LittleEndian, dbversion)
		if err != nil {
			return
		}
	}

	return
}
示例#30
0
func (w *Huobi) TradeDetail() (ret bool) {
	rnd := RandomString(20)

	now := time.Now().UnixNano() / 1000000

	req, err := http.NewRequest("GET", fmt.Sprintf(Config["trade_detail"], rnd, now, now), nil)
	if err != nil {
		logger.Fatal(err)
	}

	req.Header.Set("Referer", Config["base_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")
	req.Header.Add("Accept-Encoding", "identity")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logger.Traceln(err)
		logger.Traceln(req)
		logger.Traceln(resp)
		return false
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		var body string

		contentEncoding := resp.Header.Get("Content-Encoding")
		logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
		switch contentEncoding {
		case "gzip":
			body = DumpGZIP(resp.Body)

		default:
			bodyByte, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				logger.Errorln("read the http stream failed")
				return false
			} else {
				body = string(bodyByte)

				ioutil.WriteFile("cache/TradeDetail.json", bodyByte, os.ModeAppend)
			}
		}

		logger.Traceln(resp.Header.Get("Content-Type"))

		if resp.Header.Get("Content-Type") == "application/json" {
			doc := json.NewDecoder(strings.NewReader(body))

			type Msg struct {
				Code int
				Msg  string
			}

			var m Msg
			if err := doc.Decode(&m); err == io.EOF {
				logger.Traceln(err)
			} else if err != nil {
				logger.Fatal(err)
			}
			logger.Traceln(m)

			if m.Code == 0 {
				return true
			} else {
				logger.Errorln(m)
				return false
			}
		} else {
			ret := strings.Contains(body, "您需要登录才能继续")
			if ret {
				logger.Errorln("您需要登录才能继续")
				logger.Errorln(body)
				return false
			} else {
				return w.TradeDetailAnalyze(body)
			}
		}
	} else {
		logger.Errorf("HTTP returned status %v", resp)
	}

	logger.Errorln("why in here?")
	return false
}