示例#1
0
// 获得资源详细信息
func FindResource(id string) (resourceMap map[string]interface{}, comments []map[string]interface{}) {
	condition := "id=" + id
	resource := model.NewResource()
	err := resource.Where(condition).Find()
	if err != nil {
		logger.Errorln("resource service FindResource error:", err)
		return
	}
	resourceMap = make(map[string]interface{})
	util.Struct2Map(resourceMap, resource)
	resourceMap["catname"] = GetCategoryName(resource.Catid)
	// 链接的host
	if resource.Form == model.LinkForm {
		urlObj, err := url.Parse(resource.Url)
		if err == nil {
			resourceMap["host"] = urlObj.Host
		}
	} else {
		resourceMap["url"] = "/resources/" + strconv.Itoa(resource.Id)
	}
	resourceEx := model.NewResourceEx()
	err = resourceEx.Where(condition).Find()
	if err != nil {
		logger.Errorln("resource service FindResource Error:", err)
		return
	}
	util.Struct2Map(resourceMap, resourceEx)
	// 评论信息
	comments, ownerUser, _ := FindObjComments(id, strconv.Itoa(model.TYPE_RESOURCE), resource.Uid, 0)
	resourceMap["user"] = ownerUser
	return
}
示例#2
0
// 获取抓取的文章列表(分页)
func FindArticles(lastId, limit string) []*model.Article {
	article := model.NewArticle()

	cond := "status IN(0,1)"
	if lastId != "0" {
		cond += " AND id<" + lastId
	}

	articleList, err := article.Where(cond).Order("id DESC").Limit(limit).
		FindAll()
	if err != nil {
		logger.Errorln("article service FindArticles Error:", err)
		return nil
	}

	topArticles, err := article.Where("top=?", 1).Order("id DESC").FindAll()
	if err != nil {
		logger.Errorln("article service Find Top Articles Error:", err)
		return nil
	}
	if len(topArticles) > 0 {
		articleList = append(topArticles, articleList...)
	}

	return articleList
}
示例#3
0
文件: strategy.go 项目: 9cat/btcrobot
//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
	}

	if strategyName != "OPENORDER" {
		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
		}

		lastPrice = records[length-1].Close
	}

	gTradeAPI = tradeAPI

	return strategy.Tick(records)
}
示例#4
0
func SaveRule(form url.Values, opUser string) (errMsg string, err error) {
	rule := model.NewCrawlRule()
	err = util.ConvertAssign(rule, form)
	if err != nil {
		logger.Errorln("rule ConvertAssign error", err)
		errMsg = err.Error()
		return
	}

	rule.OpUser = opUser

	if rule.Id != 0 {
		err = rule.Persist(rule)
	} else {
		_, err = rule.Insert()
	}

	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln("rule save:", errMsg, ":", err)
		return
	}

	return
}
示例#5
0
// 获得帖子详细信息(包括详细回复)
// 为了避免转换,tid传string类型
func FindTopicByTid(tid string) (topicMap map[string]interface{}, replies []map[string]interface{}, err error) {
	condition := "tid=" + tid
	// 帖子信息
	topic := model.NewTopic()
	err = topic.Where(condition).Find()
	if err != nil {
		logger.Errorln("topic service FindTopicByTid Error:", err)
		return
	}
	// 帖子不存在
	if topic.Tid == 0 {
		return
	}
	topicMap = make(map[string]interface{})
	util.Struct2Map(topicMap, topic)
	topicEx := model.NewTopicEx()
	err = topicEx.Where(condition).Find()
	if err != nil {
		logger.Errorln("topic service FindTopicByTid Error:", err)
		return
	}
	if topicEx.Tid == 0 {
		return
	}
	util.Struct2Map(topicMap, topicEx)
	// 节点名字
	topicMap["node"] = model.GetNodeName(topic.Nid)

	// 回复信息(评论)
	replyList, err := model.NewComment().Where("objid=" + tid + " and objtype=" + strconv.Itoa(model.TYPE_TOPIC)).FindAll()
	if err != nil {
		logger.Errorln("topic service FindTopicByTid Error:", err)
		return
	}

	replyNum := len(replyList)
	uids := make(map[int]int, replyNum+1)
	uids[topic.Uid] = topic.Uid
	for _, reply := range replyList {
		uids[reply.Uid] = reply.Uid
	}

	// 获得用户信息
	userMap := getUserInfos(uids)
	topicMap["user"] = userMap[topic.Uid]

	// 有人回复
	if topic.Lastreplyuid != 0 {
		topicMap["lastreplyusername"] = userMap[topicMap["lastreplyuid"].(int)].Username
	}

	replies = make([]map[string]interface{}, 0, replyNum)
	for _, reply := range replyList {
		tmpMap := make(map[string]interface{})
		util.Struct2Map(tmpMap, reply)
		tmpMap["user"] = userMap[reply.Uid]
		replies = append(replies, tmpMap)
	}
	return
}
示例#6
0
// 保存晨读
func SaveReading(form url.Values, username string) (errMsg string, err error) {
	reading := model.NewMorningReading()
	err = util.ConvertAssign(reading, form)
	if err != nil {
		logger.Errorln("reading SaveReading error", err)
		errMsg = err.Error()
		return
	}

	reading.Moreurls = strings.TrimSpace(reading.Moreurls)
	if strings.Contains(reading.Moreurls, "\n") {
		reading.Moreurls = strings.Join(strings.Split(reading.Moreurls, "\n"), ",")
	}

	reading.Username = username

	logger.Infoln(reading.Rtype, "id=", reading.Id)
	if reading.Id != 0 {
		err = reading.Persist(reading)
	} else {
		_, err = reading.Insert()
	}

	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln("reading save:", errMsg, ":", err)
		return
	}

	return
}
示例#7
0
func SaveAuthority(form url.Values, opUser string) (errMsg string, err error) {
	authority := model.NewAuthority()
	err = util.ConvertAssign(authority, form)
	if err != nil {
		logger.Errorln("authority ConvertAssign error", err)
		errMsg = err.Error()
		return
	}

	authority.OpUser = opUser

	if authority.Aid != 0 {
		err = authority.Persist(authority)
	} else {
		authority.Ctime = util.TimeNow()

		_, err = authority.Insert()
	}

	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	global.AuthorityChan <- struct{}{}

	return
}
示例#8
0
// 将所有 角色 加载到内存中;后台修改角色时,重新加载一次
func LoadRoles() error {
	roles, err := model.NewRole().FindAll()
	if err != nil {
		logger.Errorln("LoadRoles role read fail:", err)
		return err
	}

	if len(roles) == 0 {
		logger.Errorln("LoadRoles role read fail: num is 0")
		return errors.New("no role")
	}

	roleLocker.Lock()
	defer roleLocker.Unlock()

	maxRoleid := roles[len(roles)-1].Roleid
	Roles = make([]*model.Role, maxRoleid)

	// 由于角色不多,而且一般角色id是连续自增的,因此这里以角色id当slice的index
	for _, role := range roles {
		Roles[role.Roleid-1] = role
	}

	logger.Infoln("LoadRoles successfully!")

	return nil
}
示例#9
0
func FindUsers() (map[int]*model.User, error) {
	userList, err := model.NewUser().FindAll()
	if err != nil {
		logger.Errorln("user service FindUsers Error:", err)
		return nil, err
	}
	userCount := len(userList)
	userMap := make(map[int]*model.User, userCount)
	uids := make([]int, userCount)
	for i, user := range userList {
		userMap[user.Uid] = user
		uids[i] = user.Uid
	}
	// 获得角色信息
	userRoleList, err := model.NewUserRole().Where("uid in (" + util.Join(uids, ",") + ")").FindAll()
	if err != nil {
		logger.Errorln("user service FindUsers Error:", err)
		return nil, err
	}
	for _, userRole := range userRoleList {
		user := userMap[userRole.Uid]
		if len(user.Roleids) == 0 {
			user.Roleids = []int{userRole.Roleid}
			user.Rolenames = []string{model.AllRole[userRole.Roleid].Name}
		} else {
			user.Roleids = append(user.Roleids, userRole.Roleid)
			user.Rolenames = append(user.Rolenames, model.AllRole[userRole.Roleid].Name)
		}
	}
	return userMap, nil
}
示例#10
0
func (this *UserRole) FindAll(selectCol ...string) ([]*UserRole, error) {
	if len(selectCol) == 0 {
		selectCol = util.MapKeys(this.colFieldMap())
	}
	rows, err := this.Dao.FindAll(selectCol...)
	if err != nil {
		logger.Errorln("[UserRole.FindAll] error:", err)
		return nil, err
	}
	// TODO:
	userRoleList := make([]*UserRole, 0, 10)
	colNum := len(selectCol)
	for rows.Next() {
		userRole := NewUserRole()
		colFieldMap := userRole.colFieldMap()
		scanInterface := make([]interface{}, 0, colNum)
		for _, column := range selectCol {
			scanInterface = append(scanInterface, colFieldMap[column])
		}
		err = rows.Scan(scanInterface...)
		if err != nil {
			logger.Errorln("[UserRole.FindAll Rows] error:", err)
		}
		userRoleList = append(userRoleList, userRole)
	}
	return userRoleList, nil
}
示例#11
0
// 增加资源
func PublishResource(uid int, form url.Values) bool {
	resource := model.NewResource()
	err := util.ConvertAssign(resource, form)
	if err != nil {
		logger.Errorln("user ConvertAssign error", err)
		return false
	}
	resource.Ctime = time.Now().Format("2006-01-02 15:04:05")
	resource.Uid = uid
	id, err := resource.Insert()
	if err != nil {
		logger.Errorln("PublishResource error:", err)
		return false
	}

	// 发布资源,活跃度+10
	go IncUserWeight("uid="+strconv.Itoa(uid), 10)

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

	return true
}
示例#12
0
// 在逻辑处理完之后,最后展示页面
func (this *ViewFilter) PostFilter(rw http.ResponseWriter, req *http.Request) bool {
	contentHtml := req.FormValue(CONTENT_TPL_KEY)
	if contentHtml == "" {
		return true
	}
	// 为了使用自定义的模板函数,首先New一个以第一个模板文件名为模板名。
	// 这样,在ParseFiles时,新返回的*Template便还是原来的模板实例
	tpl, err := template.New(this.baseTplName).Funcs(funcMap).ParseFiles(append(this.commonHtmlFiles, config.ROOT+contentHtml)...)
	if err != nil {
		logger.Errorln("解析模板出错(ParseFiles):", 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)
	// 当前用户信息
	me, _ := CurrentUser(req)
	data["me"] = me
	err = tpl.Execute(rw, data)
	if err != nil {
		logger.Errorln("执行模板出错(Execute):", err)
	}
	return true
}
示例#13
0
func (w *OkcoinTrade) Get_order(symbol, order_id string) (ret bool, m OKOrderTable) {
	pParams := make(map[string]string)
	pParams["partner"] = w.partner
	pParams["symbol"] = symbol
	pParams["order_id"] = order_id

	ret = true

	body, err := w.httpRequest(Config["ok_api_getorder"], pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

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

	return
}
示例#14
0
// 发表评论。入topics_reply库,更新topics和topics_ex库
// objname 注册的评论对象名
func PostComment(objid, objtype, uid int, content string, objname string) error {
	comment := model.NewComment()
	comment.Objid = objid
	comment.Objtype = objtype
	comment.Uid = uid
	comment.Content = content

	// TODO:评论楼层怎么处理,避免冲突?最后的楼层信息保存在内存中?

	// 暂时只是从数据库中取出最后的评论楼层
	stringBuilder := util.NewBuffer()
	stringBuilder.Append("objid=").AppendInt(objid).Append(" AND objtype=").AppendInt(objtype)
	tmpCmt, err := model.NewComment().Where(stringBuilder.String()).Order("ctime DESC").Find()
	if err != nil {
		logger.Errorln("post comment service error:", err)
		return err
	} else {
		comment.Floor = tmpCmt.Floor + 1
	}
	// 入评论库
	cid, err := comment.Insert()
	if err != nil {
		logger.Errorln("post comment service error:", err)
		return err
	}
	// 回调,不关心处理结果(有些对象可能不需要回调)
	if commenter, ok := commenters[objname]; ok {
		logger.Debugf("评论[objid:%d] [objtype:%d] [uid:%d] 成功,通知被评论者更新", objid, objtype, uid)
		go commenter.UpdateComment(cid, objid, uid, time.Now().Format("2006-01-02 15:04:05"))
	}

	return nil
}
示例#15
0
func (w *Huobi) TradeKLinePeroid(peroid int) (ret bool) {
	req, err := http.NewRequest("GET", fmt.Sprintf(Config["trade_kline_url"], peroid, rand.Float64()), nil)
	if err != nil {
		logger.Fatal(err)
		return false
	}

	req.Header.Set("Referer", Config["trade_flash_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)

	if w.client == nil {
		w.client = &http.Client{nil, nil, nil}
	}
	resp, err := w.client.Do(req)
	if err != nil {
		logger.Errorln(err)
		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(fmt.Sprintf("cache/TradeKLine_%03d.data", peroid), bodyByte, os.ModeAppend)
			}
		}

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

		ret := strings.Contains(body, "您需要登录才能继续")
		if ret {
			logger.Traceln("您需要登录才能继续")
			return false
		} else {
			return w.AnalyzePeroidLine(fmt.Sprintf("cache/TradeKLine_%03d.data", peroid), body)
		}

	} else {
		logger.Tracef("HTTP returned status %v", resp)
	}

	return false
}
示例#16
0
文件: btcweb.go 项目: kalllx/btcrobot
func EngineHandler(rw http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)

	msgtype := vars["msgtype"]

	if req.Method != "POST" && msgtype == "" {
		// 获取用户信息
		err := config.LoadOption()
		if err != nil {
			logger.Errorln(err)
			fmt.Fprint(rw, `{"errno": 1, "msg":"`, "读取引擎配置数据失败", `"}`)
			return
		}
		// 设置模板数据
		filter.SetData(req, map[string]interface{}{"config": config.Option})
		req.Form.Set(filter.CONTENT_TPL_KEY, "/template/trade/engine.html")
		return
	} else if req.Method != "POST" && msgtype == "ajax" {
		Option_json, err := json.Marshal(config.Option)
		if err != nil {
			logger.Errorln(err)
			fmt.Fprint(rw, `{"errno": 1, "msg":"`, "读取引擎配置数据失败", `"}`)
		} else {
			fmt.Fprint(rw, string(Option_json))
		}
		return
	} else {
		logger.Debugln("===[", req.FormValue("disable_trading"), "]")
		if req.FormValue("disable_trading") == "on" {
			config.Option["disable_trading"] = "1"
		} else {
			config.Option["disable_trading"] = "0"
		}

		logger.Debugln("===[", req.FormValue("disable_backtesting"), "]")
		if req.FormValue("disable_backtesting") == "on" {
			config.Option["disable_backtesting"] = "1"
		} else {
			config.Option["disable_backtesting"] = "0"
		}

		config.Option["tick_interval"] = req.FormValue("tick_interval")
		config.Option["shortEMA"] = req.FormValue("shortEMA")
		config.Option["longEMA"] = req.FormValue("longEMA")

		config.Option["tradeAmount"] = req.FormValue("tradeAmount")

		config.Option["totalHour"] = req.FormValue("totalHour")

		// 更新个人信息
		err := config.SaveOption()
		if err != nil {
			fmt.Fprint(rw, `{"errno": 1, "msg":"`, "写入引擎配置数据失败", `"}`)
			return
		}

		fmt.Fprint(rw, `{"errno": 0, "msg":"更新引擎配置成功!"}`)
	}
}
示例#17
0
文件: macd.go 项目: cnspot/btcrobot
// MACD strategy
func (macdStrategy *MACDStrategy) Tick(records []Record) bool {
	// read config
	shortEMA, _ := strconv.Atoi(Option["shortEMA"])
	longEMA, _ := strconv.Atoi(Option["longEMA"])

	signalPeriod, _ := strconv.Atoi(Option["signalPeriod"])
	/*
		MACDMinThreshold, err := strconv.ParseFloat(Option["MACDMinThreshold"], 64)
		if err != nil {
			logger.Debugln("config item MACDMinThreshold is not float")
			return false
		}
	*/

	MACDbuyThreshold, err := strconv.ParseFloat(Option["MACDbuyThreshold"], 64)
	if err != nil {
		logger.Errorln("config item MACDbuyThreshold is not float")
		return false
	}

	MACDsellThreshold, err := strconv.ParseFloat(Option["MACDsellThreshold"], 64)
	if err != nil {
		logger.Errorln("config item MACDsellThreshold is not float")
		return false
	}

	var Price []float64
	for _, v := range records {
		Price = append(Price, v.Close)
	}

	// compute the indictor
	emaShort := EMA(Price, shortEMA)
	emaLong := EMA(Price, longEMA)
	MACDdif := getMACDdif(emaShort, emaLong)
	MACDSignal := getMACDSignal(MACDdif, signalPeriod)
	MACDHistogram := getMACDHistogram(MACDdif, MACDSignal)

	if MACDdif[length-1] != macdStrategy.PrevMACDdif {
		macdStrategy.PrevMACDdif = MACDdif[length-1]
		logger.Infof("MACD:d%5.03f\ts%5.03f\tph%5.03f\th%5.03f\tPrice:%5.02f\n", MACDdif[length-1], MACDSignal[length-1], MACDHistogram[length-2], MACDHistogram[length-1], Price[length-1])
	}

	// macd cross
	if (MACDHistogram[length-2] < -0.000001 && MACDHistogram[length-1] > MACDbuyThreshold) ||
		(PrevTrade == "sell" && MACDHistogram[length-2] > 0.000001 && MACDHistogram[length-1] > MACDbuyThreshold) {
		Buy()
	} else if (MACDHistogram[length-2] > 0.000001 && MACDHistogram[length-1] < MACDsellThreshold) ||
		(PrevTrade == "buy" && MACDHistogram[length-2] < -0.000001 && MACDHistogram[length-1] < MACDsellThreshold) {
		Sell()
	}

	// do sell when price is below stoploss point
	processStoploss(lastPrice)
	processTimeout()

	return true
}
示例#18
0
// 索引帖子
func IndexingTopic(isAll bool) {
	solrClient := NewSolrClient()

	topicObj := model.NewTopic()
	topicExObj := model.NewTopicEx()

	limit := strconv.Itoa(MaxRows)
	if isAll {
		id := 0
		for {
			topicList, err := topicObj.Where("tid>?", id).Limit(limit).FindAll()
			if err != nil {
				logger.Errorln("IndexingTopic error:", err)
				break
			}

			if len(topicList) == 0 {
				break
			}

			tids := util.Models2Intslice(topicList, "Tid")

			tmpStr := strings.Repeat("?,", len(tids))
			query := "tid in(" + tmpStr[:len(tmpStr)-1] + ")"
			args := make([]interface{}, len(tids))
			for i, tid := range tids {
				args[i] = tid
			}

			topicExList, err := topicExObj.Where(query, args...).FindAll()
			if err != nil {
				logger.Errorln("IndexingTopic error:", err)
				break
			}

			topicExMap := make(map[int]*model.TopicEx, len(topicExList))
			for _, topicEx := range topicExList {
				topicExMap[topicEx.Tid] = topicEx
			}

			for _, topic := range topicList {
				if id < topic.Tid {
					id = topic.Tid
				}

				topicEx, _ := topicExMap[topic.Tid]

				document := model.NewDocument(topic, topicEx)
				addCommand := model.NewDefaultArgsAddCommand(document)

				solrClient.Push(addCommand)
			}

			solrClient.Post()
		}
	}
}
示例#19
0
// 索引资源
func IndexingResource(isAll bool) {
	solrClient := NewSolrClient()

	resourceObj := model.NewResource()
	resourceExObj := model.NewResourceEx()

	limit := strconv.Itoa(MaxRows)
	if isAll {
		id := 0
		for {
			resourceList, err := resourceObj.Where("id>?", id).Limit(limit).FindAll()
			if err != nil {
				logger.Errorln("IndexingResource error:", err)
				break
			}

			if len(resourceList) == 0 {
				break
			}

			ids := util.Models2Intslice(resourceList, "Id")

			tmpStr := strings.Repeat("?,", len(ids))
			query := "id in(" + tmpStr[:len(tmpStr)-1] + ")"
			args := make([]interface{}, len(ids))
			for i, rid := range ids {
				args[i] = rid
			}

			resourceExList, err := resourceExObj.Where(query, args...).FindAll()
			if err != nil {
				logger.Errorln("IndexingResource error:", err)
				break
			}

			resourceExMap := make(map[int]*model.ResourceEx, len(resourceExList))
			for _, resourceEx := range resourceExList {
				resourceExMap[resourceEx.Id] = resourceEx
			}

			for _, resource := range resourceList {
				if id < resource.Id {
					id = resource.Id
				}

				resourceEx, _ := resourceExMap[resource.Id]

				document := model.NewDocument(resource, resourceEx)
				addCommand := model.NewDefaultArgsAddCommand(document)

				solrClient.Push(addCommand)
			}

			solrClient.Post()
		}
	}
}
示例#20
0
// 注册评论对象,使得某种类型(帖子、博客等)可以被评论
func RegisterCommentObject(objname string, commenter Commenter) {
	if commenter == nil {
		logger.Errorln("service: Register commenter is nil")
	}
	if _, dup := commenters[objname]; dup {
		logger.Errorln("service: Register called twice for commenter " + objname)
	}
	commenters[objname] = commenter
}
示例#21
0
func FindTopicsByWhere(where, order, limit string) (topics []map[string]interface{}, total int) {
	topicObj := model.NewTopic()
	if where != "" {
		topicObj.Where(where)
	}
	if order != "" {
		topicObj.Order(order)
	}
	if limit != "" {
		topicObj.Limit(limit)
	}
	topicList, err := topicObj.FindAll()
	if err != nil {
		logger.Errorln("topic service topicObj.FindAll Error:", err)
		return
	}
	// 获得总帖子数
	total, err = topicObj.Count()
	if err != nil {
		logger.Errorln("topic service topicObj.Count Error:", err)
		return
	}
	count := len(topicList)
	tids := make([]int, count)
	uids := make(map[int]int)
	nids := make([]int, count)
	for i, topic := range topicList {
		tids[i] = topic.Tid
		uids[topic.Uid] = topic.Uid
		if topic.Lastreplyuid != 0 {
			uids[topic.Lastreplyuid] = topic.Lastreplyuid
		}
		nids[i] = topic.Nid
	}

	userMap := getUserInfos(uids)

	// 获取节点信息
	nodes := model.GetNodesName(nids)

	topics = make([]map[string]interface{}, count)
	for i, topic := range topicList {
		tmpMap := make(map[string]interface{})
		util.Struct2Map(tmpMap, topic)
		tmpMap["user"] = userMap[topic.Uid]
		// 有人回复
		if tmpMap["lastreplyuid"].(int) != 0 {
			tmpMap["lastreplyusername"] = userMap[tmpMap["lastreplyuid"].(int)].Username
		}
		tmpMap["node"] = nodes[tmpMap["nid"].(int)]
		topics[i] = tmpMap
	}
	return
}
示例#22
0
// 发表评论(或回复)。
// objid 注册的评论对象
// uid 评论人
func PostComment(uid, objid int, form url.Values) (*model.Comment, error) {
	comment := model.NewComment()
	comment.Objid = objid
	objtype := util.MustInt(form.Get("objtype"))
	comment.Objtype = objtype
	comment.Uid = uid
	comment.Content = form.Get("content")

	// TODO:评论楼层怎么处理,避免冲突?最后的楼层信息保存在内存中?

	// 暂时只是从数据库中取出最后的评论楼层
	stringBuilder := util.NewBuffer()
	stringBuilder.Append("objid=").AppendInt(objid).Append(" AND objtype=").AppendInt(objtype)
	tmpCmt, err := model.NewComment().Where(stringBuilder.String()).Order("ctime DESC").Find()
	if err != nil {
		logger.Errorln("post comment service error:", err)
		return nil, err
	} else {
		comment.Floor = tmpCmt.Floor + 1
	}
	// 入评论库
	cid, err := comment.Insert()
	if err != nil {
		logger.Errorln("post comment service error:", err)
		return nil, err
	}
	comment.Cid = cid
	comment.Ctime = util.TimeNow()
	decodeCmtContent(comment)

	// 回调,不关心处理结果(有些对象可能不需要回调)
	if commenter, ok := commenters[objtype]; ok {
		logger.Debugf("评论[objid:%d] [objtype:%d] [uid:%d] 成功,通知被评论者更新", objid, objtype, uid)
		go commenter.UpdateComment(cid, objid, uid, time.Now().Format("2006-01-02 15:04:05"))
	}

	// 发评论,活跃度+5
	go IncUserWeight("uid="+strconv.Itoa(uid), 5)

	// 给被评论对象所有者发系统消息
	ext := map[string]interface{}{
		"objid":   objid,
		"objtype": objtype,
		"cid":     cid,
		"uid":     uid,
	}
	go SendSystemMsgTo(0, objtype, ext)

	// @某人 发系统消息
	go SendSysMsgAtUids(form.Get("uid"), ext)
	go SendSysMsgAtUsernames(form.Get("usernames"), ext)

	return comment, nil
}
示例#23
0
// 获得某个用户未读消息数(系统消息和短消息)
func FindNotReadMsgNum(uid int) int {
	condition := "to=" + strconv.Itoa(uid) + " AND hasread=" + model.NotRead
	sysMsgNum, err := model.NewSystemMessage().Where(condition).Count()
	if err != nil {
		logger.Errorln("SystemMessage service FindNotReadMsgNum Error:", err)
	}
	msgNum, err := model.NewMessage().Where(condition).Count()
	if err != nil {
		logger.Errorln("Message service FindNotReadMsgNum Error:", err)
	}
	return sysMsgNum + msgNum
}
示例#24
0
func SaveRole(form url.Values, opUser string) (errMsg string, err error) {

	role := model.NewRole()
	role.Name = form.Get("name")
	role.OpUser = opUser

	roleid := form.Get("roleid")
	isNew := roleid == ""
	if isNew {
		role.Ctime = util.TimeNow()

		_, err = role.Insert()
	} else {
		role.Roleid, err = strconv.Atoi(roleid)
		if err != nil {
			errMsg = "roleid invalid"
			logger.Errorln(errMsg, ":", err)
			return
		}
		err = role.Persist(role)
	}

	if err != nil {
		errMsg = "内部服务器错误"
		logger.Errorln(errMsg, ":", err)
		return
	}

	roleAuth := model.NewRoleAuthority()
	if !isNew {
		// 如果是更新角色,将之前的角色权限都删除
		roleAuth.Where("roleid=" + strconv.Itoa(role.Roleid)).Delete()
	}

	roleAuth.Roleid = role.Roleid
	roleAuth.OpUser = opUser

	// 增加角色拥有的权限
	for _, aid := range form["authorities[]"] {
		aid, err := strconv.Atoi(aid)
		if err != nil {
			continue
		}
		roleAuth.Aid = aid

		roleAuth.Insert()
	}

	global.RoleChan <- struct{}{}
	global.RoleAuthChan <- struct{}{}

	return
}
示例#25
0
func NotFoundHandler(rw http.ResponseWriter, req *http.Request) {
	t, err := template.ParseFiles(utils.BaseHtmlTplFile, utils.Error404HtmlTplFile)
	if nil != err {
		logger.Errorln(err)
		return
	}
	err = t.Execute(rw, nil)
	if nil != err {
		logger.Errorln(err)
		return
	}
}
示例#26
0
// 包装链接
func WRHandler(rw http.ResponseWriter, req *http.Request) {
	tUrl := req.FormValue("u")
	if tUrl == "" {
		util.Redirect(rw, req, "/")
		return
	}

	if pUrl, err := url.Parse(tUrl); err != nil {
		util.Redirect(rw, req, tUrl)
		return
	} else {
		if !pUrl.IsAbs() {
			util.Redirect(rw, req, tUrl)
			return
		}

		// 本站
		if strings.Contains(pUrl.Host, config.Config["domain"]) {
			util.Redirect(rw, req, tUrl)
			return
		}

		// 检测是否禁止了 iframe 加载
		// 看是否在黑名单中
		for _, denyHost := range strings.Split(config.Config["iframe_deny"], ",") {
			if strings.Contains(pUrl.Host, denyHost) {
				util.Redirect(rw, req, tUrl)
				return
			}
		}

		// 检测会比较慢,进行异步检测,记录下来,以后分析再加黑名单
		go func() {
			resp, err := http.Head(tUrl)
			if err != nil {
				logger.Errorln("[iframe] head url:", tUrl, "error:", err)
				return
			}
			defer resp.Body.Close()
			if resp.Header.Get("X-Frame-Options") != "" {
				logger.Errorln("[iframe] deny:", tUrl)
				return
			}
		}()
	}

	// 设置内容模板
	req.Form.Set(filter.CONTENT_TPL_KEY, "/template/wr.html")
	// 设置模板数据
	filter.SetData(req, map[string]interface{}{"url": tUrl})
}
示例#27
0
// 更新该帖子的回复信息
// cid:评论id;objid:被评论对象id;uid:评论者;cmttime:评论时间
func (self TopicComment) UpdateComment(cid, objid, uid int, cmttime string) {
	tid := strconv.Itoa(objid)
	// 更新最后回复信息
	stringBuilder := util.NewBuffer().Append("lastreplyuid=").AppendInt(uid).Append(",lastreplytime=").Append(cmttime)
	err := model.NewTopic().Set(stringBuilder.String()).Where("tid=" + tid).Update()
	if err != nil {
		logger.Errorln("更新帖子最后回复人信息失败:", err)
	}
	// 更新回复数(TODO:暂时每次都更新表)
	err = model.NewTopicEx().Where("tid="+tid).Increment("reply", 1)
	if err != nil {
		logger.Errorln("更新帖子回复数失败:", err)
	}
}
示例#28
0
func GetAvailable_ltc() float64 {
	account, ret := GetAccount()
	if !ret {
		logger.Errorln("GetAccount failed")
		return -1
	}

	numAvailable_ltc, err := strconv.ParseFloat(account.Available_ltc, 64)
	if err != nil {
		logger.Errorln("Available_ltc is not float")
		return -1
	}
	return numAvailable_ltc
}
示例#29
0
func output(filename string, data map[string]interface{}) (err error) {
	var file *os.File
	file, err = os.Create(sitemapPath + filename)
	if err != nil {
		logger.Errorln("open file error:", err)
		return
	}
	defer file.Close()
	if err = sitemapTpl.Execute(file, data); err != nil {
		logger.Errorln("execute template error:", err)
	}

	return
}
示例#30
0
func GetAvailable_cny() float64 {
	account, ret := GetAccount()
	if !ret {
		logger.Errorln("GetAccount failed")
		return -1
	}

	numAvailable_cny, err := strconv.ParseFloat(account.Available_cny, 64)
	if err != nil {
		logger.Errorln("tradeAmount is not float")
		return -1
	}
	//balance > 0
	return numAvailable_cny
}