package front
import (
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"jfw/config"
"jfw/tools"
"jfw/wx"
"log"
"math/rand"
"qfw/util"
"qfw/util/elastic"
"qfw/util/redis"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/go-xweb/xweb"
. "github.com/thinxer/go-word2vec"
"gopkg.in/mgo.v2/bson"
)
const (
bidSearch_pageSize = 50 //招标搜索分页--每页显示数量
bidSearch_maxPageSize = 10 //招标搜索分页--最大页数
wx_maxPageNum = 20
wx_pageSize = 50
bidSearch_field_1 = `"_id","title","publishtime","toptype","subtype","type","area","href","bidopentime","winner","agency","bidamount","budget","biddingcontent","projectname"`
bidSearch_field = bidSearch_field_1 + `,"detail"`
bidSearch_sort = `{"publishtime":-1}`
)
var M *Model
var recomKWChan chan bool = make(chan bool, 1)
var listlock = &sync.Mutex{}
var clearHtml *regexp.Regexp
func init() {
M, _ = Load("./zb.bin")
clearHtml, _ = regexp.Compile("<[^>]*>")
}
//剑鱼推送三级页点赞暂弃 改成剑鱼实验室点赞功能
func (m *Front) Praise() error {
defer util.Catch()
var flag = "F"
var praiseflag = true
thistype := m.GetString("type")
uod := m.GetString("uod")
util.Try(func() {
pdata, _ := mongodb.FindOneByField("praise", `{"s_type":"`+thistype+`"}`, `{"s_no":1}`)
if len(*pdata) != 0 {
if uod == "U" {
praiseflag = mongodb.Update("praise", `{"s_type":"`+thistype+`"}`, `{ "$inc" : { "s_no" : 1 }}`, false, false)
} else {
praiseflag = mongodb.Update("praise", `{"s_type":"`+thistype+`"}`, `{ "$inc" : { "s_no" : -1 }}`, false, false)
}
if praiseflag {
flag = "T"
}
}
}, func(e interface{}) {
log.Println("剑鱼实验室点赞出错", e)
})
m.ServeJson(map[string]interface{}{
"flag": flag,
})
return nil
}
func (m *Front) Getpraise() error {
defer util.Catch()
thistype := m.GetString("type")
praiseno := 125
switchstatus := 0
if m.Session().Get("s_m_openid") == nil {
return m.Redirect("/swordfish/about")
}
util.Try(func() {
data := make(map[string]interface{})
pdata, _ := mongodb.FindOneByField("praise", `{"s_type":"`+thistype+`"}`, `{"s_no":1}`)
myopenid := m.Session().Get("s_m_openid")
tmp, _ := mongodb.FindOneByField("user", `{"s_m_openid":"`+myopenid.(string)+`"}`, `{"i_smartset":1,"i_dataexport":1,"i_supersearch":1,"i_entsesearch":1,"i_followent":1,"i_smartsetiknow":1,"i_dataexportiknow":1,"i_supersearchiknow":1,"i_entsesearchiknow":1,"i_followentiknow":1}`)
if thistype == "zndy" {
data["s_name"] = "剑鱼实验室-智能订阅"
switchstatus = util.IntAll((*tmp)["i_smartset"])
} else if thistype == "sjdc" {
data["s_name"] = "剑鱼实验室-数据导出"
switchstatus = util.IntAll((*tmp)["i_dataexport"])
} else if thistype == "cjss" {
data["s_name"] = "剑鱼实验室-超级搜索"
switchstatus = util.IntAll((*tmp)["i_supersearch"])
} else if thistype == "zbqy" {
data["s_name"] = "剑鱼实验室-中标企业"
switchstatus = util.IntAll((*tmp)["i_entsesearch"])
} else if thistype == "gzqy" {
data["s_name"] = "剑鱼实验室-关注企业"
switchstatus = util.IntAll((*tmp)["i_followent"])
}
if len(*pdata) == 0 {
data["s_type"] = thistype
data["s_no"] = 125
data["l_date"] = time.Now().Unix()
mongodb.Save("praise", data)
} else {
praiseno = util.IntAll((*pdata)["s_no"])
}
}, func(e interface{}) {
log.Println("剑鱼实验室取赞出错", e)
})
m.ServeJson(map[string]interface{}{
"praiseno": praiseno,
"switchstatus": switchstatus,
})
return nil
}
//剑鱼pc首页
func (m *Front) NewSordfish() error {
ispc, _ := m.GetInteger("ispc")
var shareid = m.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jysy"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
} else {
redis.Del("other", "jypcindex")
}
m.T["logid"] = config.Seoconfig["jysy"].(string)
m.T["shareid"] = se.EncodeString(shareid)
regex, _ := regexp.Compile("(Android|Mobile)")
if ispc == 0 && len(regex.FindAllString(m.Header("User-Agent"), -1)) > 0 {
return m.Render("/pc/mobileindex.html", &m.T)
} else {
if ret := redis.Get("other", "jypcindex"); ret != nil {
return m.SetBody([]byte(ret.(string)))
} else {
m.DisableHttpCache()
lastBids := elastic.GetPage("bidding", "bidding", "{}", bidSearch_sort, `"_id","title","publishtime","toptype","subtype","type","area","href","biddingcontent"`, 0, 18)
if lastBids != nil && len(*lastBids) > 0 {
bidListConvert("", lastBids)
lbnHtml, olHtml := structureLastBidsHtml(lastBids)
m.T["lbnHtml"] = lbnHtml
m.T["olHtml"] = olHtml
}
content, _ := m.Render4Cache("/pc/index.html", &m.T)
redis.Put("other", "jypcindex", string(content), 60*60*2)
return m.SetBody(content)
}
}
return m.Render("/pc/index.html", &m.T)
}
func structureLastBidsHtml(lastBidNews *[]map[string]interface{}) (string, string) {
var tmp int = 0
var olCount int = 0
var lbnHtml string = ""
var olHtml string = `
`
for i := 0; i < len(*lastBidNews); i++ {
lastBidNew := (*lastBidNews)[i]
if tmp == 0 {
olHtml += ``
olCount++
}
tmp++
if tmp == 1 {
lbnHtml += ``
}
lbnHtml += ``
area, _ := lastBidNew["area"].(string)
area = strings.TrimSpace(area)
finalType, _ := lastBidNew["subtype"].(string)
if finalType == "" {
finalType = util.ObjToString(lastBidNew["toptype"])
}
if finalType == "" {
finalType = util.ObjToString(lastBidNew["type"])
if finalType == "bid" {
finalType = "中标"
} else if finalType == "tender" {
finalType = "招标"
} else {
finalType = ""
}
}
stpadd, areaadd := classify(finalType, area)
if area != "" && area != "A" {
lbnHtml += `
` + area + ``
}
if finalType != "" {
lbnHtml += `
` + finalType + ``
}
publishtime, _ := lastBidNew["publishtime"].(float64)
if publishtime != 0 {
diff := util.TimeDiff(time.Unix(util.Int64All(publishtime), 0))
if diff != "" {
lbnHtml += `
` + diff + ``
}
}
lbnHtml += `
`
if tmp == 6 || i == len(*lastBidNews)-1 {
tmp = 0
lbnHtml += `
`
}
}
if olCount > 1 {
olHtml += `
`
}
return lbnHtml, olHtml
}
func detailLikeRpc(Interest []string, res *[]map[string]interface{}, flag bool) (mcontent map[string]interface{}) {
//defer util.Catch()
str := fmt.Sprintf("根据您设置的关键词(%s),给您推送以下招标信息:
", strings.Join(Interest, ";"))
//发送内容组合
i := 0
o_pushinfo := map[string]interface{}{}
var details []string
v := *res
bmatch := false
for _, k2 := range v {
title := strings.Replace(k2["title"].(string), "\n", "", -1)
province := util.ObjToString(k2["area"])
if province != "" && province != "A" {
title = `[` + province + `]` + title
}
i++
str += ""
o_pushinfo[strconv.Itoa(i)] = map[string]interface{}{
"publishtime": k2["publishtime"],
"stype": k2["type"],
"topstype": k2["toptype"],
"substype": k2["subtype"],
}
if flag {
highlight, _ := k2["highlight"].(map[string][]string)
detail := ""
if len(highlight["detail"]) > 0 {
detail = highlight["detail"][0]
}
details = append(details, detail)
}
}
mcontent = map[string]interface{}{}
if len(o_pushinfo) > 0 {
bmatch = true
mcontent["o_pushinfo"] = o_pushinfo
mcontent["s_content"] = str
mcontent["s_words"] = Interest
}
mcontent["bmatch"] = bmatch
if flag {
mcontent["details"] = details
}
return
}
//跳转到pc查询剑鱼信息列表
func (m *Front) Searchinfolist(p string) error {
defer util.Catch()
var shareid = m.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jysslby"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
}
m.T["logid"] = config.Seoconfig["jysslby"].(string)
m.T["shareid"] = se.EncodeString(shareid)
keywords := m.GetString("keywords")
searchvalue := m.GetString("searchvalue")
area := m.GetString("area")
publishtime := m.GetString("publishtime")
toptype := m.GetString("toptype")
subtype := m.GetString("subtype")
industry := m.GetString("industry")
selectType := m.GetString("selectType")
selectTypesess := m.GetSession("selectType")
if selectTypesess != nil && selectTypesess != "" {
selectType = selectTypesess.(string)
}
if selectType == "" {
selectType = "all"
}
var status = 1
var count int64
var list *[]map[string]interface{}
pages := make([]interface{}, 0)
if len(searchvalue) > 0 {
count, list = getBidSearchData(searchvalue, area, publishtime, subtype, industry, 0, true, selectType)
} else if m.Method() == "POST" {
status = 2
count, list = getLastNewsData(searchvalue, area, publishtime, subtype, industry, 0, true)
} else {
status = 2
if redis.Get("other", "index_list") == nil {
intns := make([]int, 0)
for i := 0; i < 10; i++ {
if len(intns) == 0 {
intns = append(intns, rand.Intn(100))
} else {
for {
v := rand.Intn(intns[(i-1)] + 100)
if v-intns[(i-1)] >= 30 {
intns = append(intns, v)
break
}
}
}
}
for i := 0; i < 10; i++ {
count, list = getLastNewsData(searchvalue, area, publishtime, subtype, industry, intns[i], true)
for k, v := range *list {
v["k"] = (k + 1) + i*50
t := time.Unix(util.Int64All(v["publishtime"]), 0)
v["timetemp"] = fmt.Sprint(util.Int64All(v["publishtime"]))
v["_id"] = util.EncodeArticleId2ByCheck(v["_id"].(string))
v["time"] = util.TimeDiff(t)
var stp = ""
if v["subtype"] != nil {
stp, _ = v["subtype"].(string)
} else {
stp = ""
}
if stp == "" && v["toptype"] != nil {
stp, _ = v["toptype"].(string)
}
area, _ := v["area"].(string)
v["stypeadd"], v["areaadd"] = classify(stp, area)
}
pages = append(pages, list)
}
m.DisableHttpCache()
redis.Put("other", "index_list", pages, 60*60*2)
}
}
if status == 2 && m.Method() == "GET" {
pages := redis.Get("other", "index_list").([]interface{})
p := util.IntAll(p)
if p <= 0 || p > 10 {
p = 1
}
if p-1 <= 0 {
m.T["prev"] = 1
} else {
m.T["prev"] = p - 1
}
if p+1 >= 11 {
m.T["next"] = 10
} else {
m.T["next"] = p + 1
}
m.T["cur"] = p
m.T["list"] = pages[p-1]
return m.Render("/pc/bidsearch_static.html", &m.T)
} else {
if list != nil {
for _, v := range *list {
v["_id"] = util.EncodeArticleId2ByCheck(v["_id"].(string))
stp, _ := v["subtype"].(string)
if stp == "" {
stp, _ = v["toptype"].(string)
}
area, _ := v["area"].(string)
v["stypeadd"], v["areaadd"] = classify(stp, area)
//正文匹配检索关键词
highlight, _ := v["highlight"].(map[string][]string)
detail := ""
for _, val := range highlight["detail"] {
detail += clearHtml.ReplaceAllString(val, "")
}
v["detail"] = detail
}
}
m.T["list"] = list
isopen, _ := m.GetInteger("isopen")
m.T["isopen"] = isopen
m.T["area"] = area
m.T["publishtime"] = publishtime
m.T["timeslot"] = m.GetString("timeslot")
m.T["toptype"] = toptype
m.T["subtype"] = subtype
m.T["count"] = count
m.T["status"] = status
m.T["keywords"] = keywords
m.T["searchvalue"] = searchvalue
m.T["selectType"] = selectType
m.T["login"] = m.Session().Get("user")
m.SetSession("paramkey", keywords)
if publishtime == "lately-7" {
m.SetSession("parampublishtime", "最近7天")
} else if publishtime == "lately-30" {
m.SetSession("parampublishtime", "最近30天")
} else if publishtime == "thisyear" {
m.SetSession("parampublishtime", "去年")
} else {
m.SetSession("parampublishtime", publishtime)
}
m.SetSession("paramarea", area)
if subtype != "" {
m.SetSession("paraminfotype", subtype)
} else {
m.SetSession("paraminfotype", toptype)
}
return m.Render("/pc/bidsearch.html", &m.T)
}
}
//ajax分页请求
func (m *Front) PcAjaxReq() {
reqType := m.GetString("reqType")
//获取最新招标信息
if reqType == "lastBids" {
ls := elastic.GetPage(INDEX, TYPE, "{}", bidSearch_sort, bidSearch_field_1, 0, 18)
bidListConvert("", ls)
m.ServeJson(map[string]interface{}{
"list": ls,
})
return
} else if reqType == "rewardText" {
rewardText, _ := getRewardText()
m.Write(rewardText)
return
}
currentPage, _ := m.GetInteger("pageNumber")
if currentPage > bidSearch_maxPageSize {
currentPage = bidSearch_maxPageSize
}
start := (currentPage - 1) * bidSearch_pageSize
area := m.GetString("area")
subtype := m.GetString("subtype")
searchvalue := m.GetString("searchvalue")
publishtime := m.GetString("publishtime")
selectType := m.GetString("selectType")
industry := m.GetString("industry")
m.SetSession("selectType", selectType)
fmt.Println(selectType)
var list *[]map[string]interface{}
var count int64
status, _ := m.GetInteger("status")
if reqType == "filter" {
if status == 1 {
count, list = getBidSearchData(searchvalue, area, publishtime, subtype, industry, 0, true, selectType)
} else if status == 2 {
count, list = getLastNewsData(searchvalue, area, publishtime, subtype, industry, 0, true)
}
} else if reqType == "bidSearch" {
_, list = getBidSearchData(searchvalue, area, publishtime, subtype, industry, start, false, selectType)
} else if reqType == "lastNews" {
_, list = getLastNewsData(searchvalue, area, publishtime, subtype, industry, start, false)
}
if list != nil && len(*list) > 0 {
for _, v := range *list {
if v["_id"] != nil {
v["_id"] = util.EncodeArticleId2ByCheck(v["_id"].(string))
}
stp, ok := v["subtype"].(string)
if ok && stp == "" {
stp = v["toptype"].(string)
}
area, ok := v["area"].(string)
v["stypeadd"], v["areaadd"] = classify(stp, area)
//正文匹配检索关键词
highlight, _ := v["highlight"].(map[string][]string)
detail := ""
for _, val := range highlight["detail"] {
detail += clearHtml.ReplaceAllString(val, "")
}
v["detail"] = detail
}
}
m.ServeJson(map[string]interface{}{
"list": list,
"count": count,
})
}
/**
**页面搜索
**/
func getBidSearchData(searchvalue, area, publishtime, subtype, industry string, start int, isGetCount bool, selectType string) (count int64, list *[]map[string]interface{}) {
query := getBidSearchQuery(area, publishtime, subtype, industry)
//selectType:全文搜索(all)、标题搜索(title)
var qstr string
qstr = elastic.GetNgramQuery(searchvalue, query, `"title","detail"` /*FINDF*/)
if isGetCount && qstr != "" {
count = elastic.Count(INDEX, TYPE, qstr)
}
if !isGetCount || count > 0 {
var repl *[]map[string]interface{}
if selectType == "all" {
//全文搜索
repl = elastic.GetByNgramOther(INDEX, TYPE, searchvalue, query, `"title","detail"` /*FINDF*/, bidSearch_sort, bidSearch_field, start, bidSearch_pageSize, true, false, 115)
} else {
//标题搜索
repl = elastic.GetByNgram(INDEX, TYPE, searchvalue, query, `"title"` /*FINDF*/, bidSearch_sort, bidSearch_field, start, bidSearch_pageSize)
}
if repl != nil && *repl != nil && len(*repl) > 0 {
bidListConvert(industry, repl)
list = repl
}
}
limitCount := int64(bidSearch_pageSize * bidSearch_maxPageSize)
if count > limitCount {
count = limitCount
}
return
}
func getLastNewsData(searchvalue, area, publishtime, subtype, industry string, start int, isGetCount bool) (count int64, list *[]map[string]interface{}) {
//最新招标信息
query := getBidSearchQuery(area, publishtime, subtype, industry)
strquery := `{"query":{"bool":{"must":[` + query + `],"must_not":[],"should":[],"minimum_should_match" : 1}}}`
if isGetCount {
count = elastic.Count(INDEX, TYPE, strquery)
//count = elastic.Count(INDEX, TYPE, elastic.MakeQuery(query, "", "", -1, -1))
}
if !isGetCount || count > 0 {
//repl := elastic.GetPage(INDEX, TYPE, query, bidSearch_sort, bidSearch_field, start, bidSearch_pageSize)
if query == "{}" {
query = ""
}
repl := elastic.GetByNgramOther(INDEX, TYPE, searchvalue, query, `"title","detail"` /*FINDF*/, bidSearch_sort, bidSearch_field, start, bidSearch_pageSize, true, false, 115)
if repl != nil && *repl != nil && len(*repl) > 0 {
bidListConvert(industry, repl)
list = repl
}
}
limitCount := int64(bidSearch_pageSize * bidSearch_maxPageSize)
if count > limitCount {
count = limitCount
}
return
}
func getBidSearchQuery(area, publishtime, subtype, industry string) string {
query := ``
if area != "" {
query += `{"terms":{"area":[`
for k, v := range strings.Split(area, ",") {
if k > 0 {
query += `,`
}
query += `"` + v + `"`
}
query += `]}}`
}
if publishtime != "" {
if len(query) > 0 {
query += ","
}
starttime, endtime := "", ""
now := time.Now()
if publishtime == "lately-7" { //最近7天
starttime = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-7, 0, 0, 0, 0, time.Local).Unix())
} else if publishtime == "lately-30" { //最近30天
starttime = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-30, 0, 0, 0, 0, time.Local).Unix())
} else if publishtime == "thisyear" { //去年
starttime = fmt.Sprint(time.Date(now.Year()-1, 1, 1, 0, 0, 0, 0, time.Local).Unix())
endtime = fmt.Sprint(time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.Local).Unix())
} else {
starttime = strings.Split(publishtime, "_")[0]
endtime = strings.Split(publishtime, "_")[1]
etTime := time.Now()
if endtime != "" {
et, _ := strconv.ParseInt(endtime, 0, 64)
etTime = time.Unix(et, 0)
}
endtime = fmt.Sprint(time.Date(etTime.Year(), etTime.Month(), etTime.Day()+1, 0, 0, 0, 0, time.Local).Unix())
}
query += `{"range":{"publishtime":{`
if starttime != "" {
query += `"gte":` + starttime
}
if starttime != "" && endtime != "" {
query += `,`
}
if endtime != "" {
query += `"lt":` + endtime
}
query += `}}}`
}
if subtype != "" {
if len(query) > 0 {
query += ","
}
query += `{"terms":{"subtype":[`
for k, v := range strings.Split(subtype, ",") {
if k > 0 {
query += `,`
}
query += `"` + v + `"`
}
query += `]}}`
}
if industry != "" {
if len(query) > 0 {
query += ","
}
query += `{"regexp":{"industry":".*(`
for k, v := range strings.Split(industry, ",") {
if k > 0 {
query += `|`
}
query += "," + v + ","
}
query += `).*"}}`
}
return query
}
func getLastNewsQuery(area, publishtime, subtype string) string {
query := ``
if area != "" {
query += `"area":{"$in":[`
for k, v := range strings.Split(area, ",") {
if k > 0 {
query += `,`
}
query += `"` + v + `"`
}
query += `]}`
}
if publishtime != "" {
if len(query) > 0 {
query += ","
}
starttime, endtime := "", ""
now := time.Now()
if publishtime == "lately-7" { //最近7天
starttime = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-7, 0, 0, 0, 0, time.Local).Unix())
} else if publishtime == "lately-30" { //最近30天
starttime = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-30, 0, 0, 0, 0, time.Local).Unix())
} else if publishtime == "thisyear" { //去年
starttime = fmt.Sprint(time.Date(now.Year()-1, 1, 1, 0, 0, 0, 0, time.Local).Unix())
endtime = fmt.Sprint(time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.Local).Unix())
} else {
starttime = strings.Split(publishtime, "_")[0]
endtime = strings.Split(publishtime, "_")[1]
et, _ := strconv.ParseInt(endtime, 0, 64)
etTime := time.Unix(et, 0)
endtime = fmt.Sprint(time.Date(etTime.Year(), etTime.Month(), etTime.Day()+1, 0, 0, 0, 0, time.Local).Unix())
}
if starttime != "" && endtime != "" {
query += `"$and":[{"publishtime":{"$gte":` + starttime + `}},{"publishtime":{"$lt":` + endtime + `}}]`
} else if starttime != "" && endtime == "" {
query += `"publishtime":{"$gte":` + starttime + `}`
} else if starttime == "" && endtime != "" {
query += `"publishtime":{"$lt":` + endtime + `}`
}
}
if subtype != "" {
if len(query) > 0 {
query += ","
}
query += `"subtype":{"$in":[`
for k, v := range strings.Split(subtype, ",") {
if k > 0 {
query += `,`
}
query += `"` + v + `"`
}
query += `]}`
}
query = `{` + query + `}`
return query
}
//进入订阅页面
func (m *Front) Wxrssset() error {
myopenid, _ := m.Session().Get("s_m_openid").(string)
if isInTSguide(myopenid) {
return m.Redirect("/front/tenderSubscribe/guide")
}
m.T["openid"] = se.EncodeString(myopenid)
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
return m.Render("/weixin/wxrssset.html", &m.T)
}
//进入订阅页面
func (m *Front) Getpage() error {
defer util.Catch()
s_type := ""
openid := m.Session().Get("s_m_openid")
var msgset map[string]interface{}
if openid != nil {
one, _ := mongodb.FindOneByField("user", `{"s_m_openid":"`+openid.(string)+`"}`, `{"o_jy":1}`)
msg := (*one)["o_jy"]
if msg != "" && msg != nil {
msgset = msg.(map[string]interface{})
}
s_type = "tender"
}
m.ServeJson(map[string]interface{}{
"msgset": msgset,
"s_type": s_type,
})
return nil
}
//微信搜索界面
func (m *Front) Wxsearch() error {
defer util.Catch()
shname := m.GetSession("shname")
toptype := m.GetSession("toptype")
subtype := m.GetSession("subtype")
scope := m.GetSession("scope")
publishtime := m.GetSession("publishtime")
industry := m.GetSession("industry")
if shname != "" && shname != nil {
m.T["shname"] = shname
}
m.T["toptype"] = toptype
m.T["subtype"] = subtype
m.T["scope"] = scope
m.T["publishtime"] = publishtime
m.T["industry"] = industry
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
myopenid, _ := m.Session().Get("s_m_openid").(string)
m.T["openid"] = se.EncodeString(myopenid)
if userId := m.GetSession("userId"); userId != nil {
one, _ := mongodb.FindOneByField("user", bson.M{"_id": bson.ObjectIdHex(userId.(string))}, `{"o_jy":1}`)
history := redis.GetStr("other", "s_"+userId.(string))
arrs := strings.Split(history, ",")
if history == "" {
arrs = make([]string, 0)
}
l := len(arrs) - 1
for i := 0; i < len(arrs)/2; i++ {
tmp := arrs[l-i]
arrs[l-i] = arrs[i]
arrs[i] = tmp
}
m.T["history"] = arrs
if one != nil && len(*one) > 0 {
o_jy, _ := (*one)["o_jy"].(map[string]interface{})
a_key, _ := o_jy["a_key"].([]interface{})
var keys []interface{}
for _, v := range a_key {
keyMap, _ := v.(map[string]interface{})
key, _ := keyMap["key"].([]interface{})
keys = append(keys, key)
}
m.T["msgset"] = keys
}
}
return m.Render("/weixin/wxsearch.html", &m.T)
}
//剑鱼微信查询结果页面
func (m *Front) Wxsearchlist() error {
defer util.Catch()
keywords := m.GetString("searchname")
searchvalue := m.GetString("searchvalue")
toptype := m.GetString("toptype")
subtype := m.GetString("subtype")
industry := m.GetString("industry")
scope := m.GetString("scope")
publishtime := m.GetString("publishtime")
selectType := m.GetString("selectType")
m.SetSession("shname", keywords)
m.SetSession("toptype", toptype)
m.SetSession("subtype", subtype)
m.SetSession("industry", industry)
m.SetSession("scope", scope)
m.SetSession("publishtime", publishtime)
var list *[]map[string]interface{}
if userid := m.GetSession("userId"); userid != nil {
if len(keywords) > 0 {
if selectType == "" { //默认设置为全文搜索
selectType = "all"
}
list = getWxsearchlistData(keywords, searchvalue, scope, publishtime, subtype, industry, 1, selectType)
r := redis.GetStr("other", "s_"+userid.(string))
arrs := strings.Split(r, ",")
if r == "" {
arrs = make([]string, 0)
}
var historyFlag = 0
for _, v := range arrs {
if v == strings.Trim(keywords, " ") {
historyFlag = 1
break
}
}
if historyFlag != 1 {
arrs = append(arrs, keywords)
if len(arrs) > 5 {
arrs = arrs[1:6]
}
redis.Del("other", "s_"+userid.(string))
redis.Put("other", "s_"+userid.(string), strings.Join(arrs, ","), -1)
}
}
}
m.T["list"] = list
m.T["pageSize"] = wx_pageSize
m.T["keywords"] = keywords
m.T["searchvalue"] = searchvalue
m.T["toptype"] = toptype
m.T["subtype"] = subtype
m.T["scope"] = scope
m.T["publishtime"] = publishtime
//搜索列表增加分享
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
myopenid, _ := m.Session().Get("s_m_openid").(string)
m.T["openid"] = se.EncodeString(myopenid)
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
return m.Render("/weixin/wxsearchlist.html", &m.T)
}
//搜索结果,ajax分页请求
func (m *Front) WxsearchlistPaging() {
defer util.Catch()
userid := m.GetSession("userId")
var list *[]map[string]interface{}
pageNum, _ := m.GetInteger("pageNum")
if userid != nil && pageNum <= wx_maxPageNum {
keywords := strings.Trim(m.GetString("searchname"), " ")
searchvalue := m.GetString("searchvalue")
subtype := m.GetString("subtype")
scope := m.GetString("scope")
publishtime := m.GetString("publishtime")
selectType := m.GetString("selectType")
industry := m.GetString("industry")
list = getWxsearchlistData(keywords, searchvalue, scope, publishtime, subtype, industry, pageNum, selectType)
}
m.ServeJson(map[string]interface{}{
"list": list,
"hasNextPage": list != nil && len(*list) == wx_pageSize && pageNum < wx_maxPageNum,
})
}
//微信端删除历史搜索
func (m *Front) DelWxHistorySearch() {
defer util.Catch()
//定义一个无用参数作为返回值
var rt string = "rt"
userId := m.GetSession("userId")
history := redis.GetStr("other", "s_"+userId.(string))
if len(history) > 0 || history != "" {
redis.Del("other", "s_"+userId.(string))
}
m.ServeJson(map[string]interface{}{
"rt": rt,
})
}
//微信端搜索
func getWxsearchlistData(keywords, searchvalue, scope, publishtime, subtype, industry string, pageNum int, selectType string) (list *[]map[string]interface{}) {
query := getBidSearchQuery(scope, publishtime, subtype, industry) //scope是地区对应传进的areas, stype是类型对应scope
if len(keywords) > 0 {
if selectType == "all" { //全文搜索
list = elastic.GetByNgramOther(INDEX, TYPE, searchvalue, query, `"title","detail"`, bidSearch_sort, bidSearch_field_1, (pageNum-1)*wx_pageSize, wx_pageSize, true, false, 100)
} else { //标题搜索
list = elastic.GetByNgram(INDEX, TYPE, searchvalue, query, `"title"` /*FINDF*/, bidSearch_sort, bidSearch_field_1, (pageNum-1)*wx_pageSize, wx_pageSize)
}
if list != nil {
bidListConvert("", list)
for _, v := range *list {
v["_id"] = util.EncodeArticleId2ByCheck(util.ObjToString(v["_id"]))
}
}
}
return list
}
//查看原文跳转
func (m *Front) VisitRedirect() {
fmt.Sprintln("^6^^^^^")
defer util.Catch()
sid := m.GetString("id")
// regex, _ := regexp.Compile("(Android|Mobile)")
// if len(regex.FindAllString(m.Header("User-Agent"), -1)) <= 0 {
// m.Redirect("/article/p/" + sid + ".html")
// }
surl := m.GetString("url")
sds := m.GetString("keywords")
m.T["keywords"] = sds
shareopenid := m.GetString("openid")
if shareopenid != "" {
m.T["shareopenid"] = shareopenid
}
myopenid, _ := m.Session().Get("s_m_openid").(string)
if myopenid == "" {
myopenid = shareopenid
m.T["openid"] = myopenid //"-1"
} else {
m.T["openid"] = se.EncodeString(myopenid) //"-1"
}
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
userId, _ := m.GetSession("userId").(string)
var obj map[string]interface{}
obj = wxvisitD(sid, surl, userId)
if len(obj) > 0 {
//获取打赏文案
m.T["rewardText"], m.T["advertText"] = getRewardText()
m.T["obj"] = obj
m.Render("/weixin/wxinfocontent.html", &m.T)
return
}
if surl != "" {
m.Redirect(surl)
}
}
func wxvisitD(sid, surl, userId string) (objdata map[string]interface{}) {
defer util.Catch()
var obj map[string]interface{}
if len(sid) > 5 {
aobj, ok := mongodb.FindById("bidding", sid, nil)
if ok && (aobj == nil || *aobj == nil || len(*aobj) == 0) {
aobj, ok = mongodb.FindById("bidding_back", sid, nil)
}
obj = *aobj
if ok && obj != nil && len(obj) >= 3 {
obj["_id"] = util.EncodeArticleId2ByCheck(sid)
obj["url"] = surl
pt := obj["publishtime"]
obj["l_publishtime"] = pt
obj["publishtime"] = util.FormatDateWithObj(&pt, util.Date_Full_Layout)
//查询是否关注
obj["followFlag"] = false
obj["hasSession"] = false
var infoformat = obj["infoformat"]
if infoformat != nil && infoformat != "" {
obj["infoformat"] = util.IntAll(infoformat)
}
if userId != "" {
pcode, _ := obj["projectcode"].(string)
pname, _ := obj["projectname"].(string)
titleTmp, _ := obj["title"].(string)
obj["followFlag"], obj["followId"] = MFollow(userId, pname, pcode, titleTmp)
obj["hasSession"] = true
}
if strings.Trim(util.ObjToString(obj["detail"]), " ") == "" {
obj["detail"] = ""
}
}
}
return obj
}
func MFollow(userId string, pname string, pcode string, title string) (bool, string) {
defer util.Catch()
var followId string
followFlag := false
follows, ok := mongodb.Find("follow_project", `{"s_userid":"`+userId+`"}`, `{"_id":1,"s_projectname":1,"s_projectcode":1}`, nil, false, -1, -1)
if ok && follows != nil && len(*follows) > 0 {
for _, v := range *follows {
pc, _ := v["s_projectcode"].(string)
if pc != "" && pc == pcode {
followFlag = true
} else {
pn, _ := v["s_projectname"].(string)
if pn != "" && pn == pname {
followFlag = true
}
}
if followFlag {
followId = util.EncodeArticleId2ByCheck(util.BsonIdToSId(v["_id"]))
break
}
}
}
return followFlag, followId
}
//查看原文跳转
//增加查询备份库数据、增加关键词、描述逻辑处理
func (m *Front) PcVisitRedirect(sid string) {
defer util.Catch()
kds := m.GetString("kds")
m.T["keywords"] = kds
sid = strings.Split(sid, "_")[0]
//sid = util.DecodeArticleId(sid)[0]
var shareid = m.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jysskzy"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
}
m.T["logid"] = config.Seoconfig["jysskzy"].(string)
m.T["shareid"] = se.EncodeString(shareid)
if ret := redis.Get("other", "jypcdetail_"+sid+kds); ret != nil {
m.SetBody([]byte(ret.(string)))
return
} else {
m.DisableHttpCache()
data := elastic.GetByIdField("bidding", "bidding", sid, `"href"`)
if data == nil || len(*data) == 0 {
m.Render("/_error.html")
return
}
href, _ := (*data)["href"].(string)
href = strings.Replace(href, "\n", "", -1)
if href != "" && !strings.HasPrefix(href, "http") {
href = "http://" + href
}
po, bo, wo, obj := pcVRT(sid)
if obj != nil && len(obj) > 0 {
if len(po) > 0 {
m.T["projectOther"] = po
}
if len(bo) > 0 {
m.T["buyerOther"] = bo
}
if len(wo) > 0 {
m.T["winnerOther"] = wo
}
obj["url"] = href
m.T["obj"] = obj
content, _ := m.Render4Cache("/pc/biddetail.html", &m.T)
redis.Put("other", "jypcdetail_"+sid+kds, string(content), 60*60*24)
m.SetBody(content)
return
}
if href != "" {
m.Redirect(href)
}
}
}
//pc三级页跳转
func pcVRT(sid string) (po, bo, wo []map[string]interface{}, objdata map[string]interface{}) {
defer util.Catch()
var projectOther, buyerOther, winnerOther []map[string]interface{}
if len(sid) > 5 {
coll := "bidding"
obj, ok := mongodb.FindById(coll, sid, nil)
if ok && (obj == nil || *obj == nil || len(*obj) == 0) {
coll = "bidding_back"
obj, ok = mongodb.FindById(coll, sid, nil)
}
if ok && obj != nil && len(*obj) > 0 {
//DealInfo(obj, coll)
(*obj)["_id"] = util.EncodeArticleId2ByCheck(sid)
var infoformat = (*obj)["infoformat"]
if infoformat != nil && infoformat != "" {
(*obj)["infoformat"] = util.IntAll(infoformat)
}
if strings.Trim(util.ObjToString((*obj)["detail"]), " ") == "" {
(*obj)["detail"] = ""
}
area := (*obj)["area"].(string)
finalType, _ := (*obj)["subtype"].(string)
if finalType == "" {
finalType = util.ObjToString((*obj)["toptype"])
}
if finalType == "" {
finalType = util.ObjToString((*obj)["type"])
if finalType == "bid" {
finalType = "中标"
} else if finalType == "tender" {
finalType = "招标"
} else {
finalType = ""
}
}
(*obj)["stypeadd"], (*obj)["areaadd"] = classify(finalType, area)
//增加处理信息逻辑
objdata = *obj
queryStr := ""
commonQuery := func(mustquery string) *[]map[string]interface{} {
return elastic.GetPage("bidding", "bidding", queryStr, bidSearch_sort, `"_id","title","publishtime","toptype","subtype","type","area","href"`, 0, 11)
}
//同一个项目的其他招标信息
projectName, _ := (*obj)["projectname"].(string)
projectCode, _ := (*obj)["projectcode"].(string)
if projectName != "" || projectCode != "" {
if projectName != "" && projectCode != "" {
queryStr = `{"$or":[{"TERM_projectname":"` + projectName + `"},{"TERM_projectcode":"` + projectCode + `"}]}`
} else if projectName != "" && projectCode == "" {
queryStr = `{"TERM_projectname":"` + projectName + `"}`
} else if projectName == "" && projectCode != "" {
queryStr = `{"TERM_projectcode":"` + projectCode + `"}`
}
projectOther = bidDataConvert(sid, commonQuery(queryStr))
}
//同一个业主最近的其他招标信息
buyer, _ := (*obj)["buyer"].(string) //采购单位
if buyer != "" {
queryStr = `{"TERM_buyer":"` + buyer + `"}`
buyerOther = bidDataConvert(sid, commonQuery(queryStr))
}
//同一中标人最近中标的其他信息
subtype, _ := (*obj)["subtype"].(string) //信息类型
winner, _ := (*obj)["winner"].(string) //中标人
if winner != "" && subtype == "中标" {
queryStr = `{"TERM_winner":"` + winner + `"}`
winnerOther = bidDataConvert(sid, commonQuery(queryStr))
}
}
}
return projectOther, buyerOther, winnerOther, objdata
}
//数据转换
func bidDataConvert(id string, datas *[]map[string]interface{}) (array []map[string]interface{}) {
if datas == nil || len(*datas) == 0 {
return array
}
index := 0
for _, v := range *datas {
if len(array) >= 10 {
break
}
_id, _ := v["_id"].(string)
if _id == id {
continue
}
v["_id"] = util.EncodeArticleId2ByCheck(_id)
area, _ := v["area"].(string)
if area == "A" {
v["area"] = ""
}
tp, _ := v["subtype"].(string)
if tp == "" {
tp, _ = v["toptype"].(string)
}
if tp == "" {
tp, _ = v["type"].(string)
if tp == "bid" {
tp = "中标"
} else if tp == "tender" {
tp = "招标"
} else {
tp = ""
}
}
v["stypeadd"], v["areaadd"] = classify(tp, area)
v["type"] = tp
diff := ""
publishtime, _ := v["publishtime"].(float64)
if publishtime != 0 {
diff = util.TimeDiff(time.Unix(util.Int64All(publishtime), 0))
v["pbtime"] = util.Int64All(publishtime)
}
v["publishtime"] = diff
index++
v["index"] = index
array = append(array, v)
}
return array
}
//剑鱼保存
func (m *Front) AjaxReq() error {
defer util.Catch()
reqType := m.GetString("reqType")
var flag = "n"
switch reqType {
case "feedback": //意见反馈
data := make(map[string]interface{})
userId, ok := m.GetSession("userId").(string)
if !ok || userId == "" {
break
}
userInfo, ok := mongodb.FindById("user", userId, nil)
if !ok {
break
}
data["i_type"] = 8
data["s_fromName"] = m.GetString("fromName")
value := m.GetString("value")
if len([]rune(value)) > 200 {
value = util.SubString(value, 0, 200)
}
data["s_remark"] = value
if (*userInfo)["s_name"] != nil {
data["s_submitname"] = (*userInfo)["s_name"].(string)
}
data["s_submitid"] = userId
data["s_title"] = m.GetString("title")
data["i_status"] = 0
if (*userInfo)["s_nickname"] != nil { //昵称
data["s_username"] = (*userInfo)["s_nickname"].(string)
} else if (*userInfo)["s_name"] != nil { //s_name
data["s_username"] = (*userInfo)["s_name"].(string)
}
data["l_submitdate"] = time.Now().Unix()
data["s_source"] = m.GetString("source")
data["s_fkid"] = m.GetString("fkid")
id := mongodb.Save("interaction", data)
if len(id) > 0 {
flag = "y"
}
break
case "subscribe": //直接订阅
if openid := m.GetSession("s_m_openid"); openid != nil {
r, _ := mongodb.FindOneByField("user", bson.M{"s_m_openid": openid.(string)}, `{"o_jy":1}`)
o_jy, _ := (*r)["o_jy"].(map[string]interface{})
a_key, _ := o_jy["a_key"].([]interface{})
keysArray := processKeyword(m.GetString("keys"))
if keysArray == nil {
break
}
var isExists bool
for _, v := range a_key {
count := 0
for _, kay := range keysArray {
keyMap, _ := v.(map[string]interface{})
key, _ := keyMap["key"].([]interface{})
for _, ky := range key {
if kay == ky {
count++
break
}
}
}
if count == len(keysArray) {
isExists = true
flag = "y"
break
}
}
//如果不存在
if !isExists {
if len(a_key) >= 10 {
flag = "o"
} else {
if mongodb.Update("user", bson.M{"s_m_openid": openid.(string)},
bson.M{
"$push": bson.M{"o_jy.a_key": bson.M{"key": keysArray}},
"$set": bson.M{"o_jy.l_modifydate": time.Now().Unix()},
}, false, false) {
flag = "y"
}
}
}
}
break
default:
if openid := m.GetSession("s_m_openid"); openid != nil {
keys := m.GetSlice("keys")
scopes := m.GetString("scope")
email := m.GetString("s_email")
mode, _ := m.GetInteger("mode")
set := make(map[string]interface{})
set["o_jy.a_key"] = keys
set["o_jy.s_scope"] = scopes
set["o_jy.s_email"] = email
if mode == 0 {
mode = 1
}
set["o_jy.i_mode"] = mode
set["o_jy.l_modifydate"] = time.Now().Unix()
if mongodb.Update("user", `{"s_m_openid":"`+openid.(string)+`"}`, &map[string]interface{}{"$set": set}, false, false) {
flag = "y"
}
}
break
}
m.ServeJson(map[string]interface{}{
"flag": flag,
})
return nil
}
const (
INDEX = "bidding"
TYPE = "bidding"
FINDF = `"title"`
)
//预览结果
func (m *Front) WxpushView() error {
defer util.Catch()
myopenid, _ := m.Session().Get("s_m_openid").(string)
if myopenid == "" {
return m.Redirect("/swordfish/share/-1")
}
a_key, list := getWxpushViewData(myopenid, 1)
m.T["firstPage"] = list
m.T["hasNextPage"] = list != nil && len(*list) == wx_pageSize
m.T["pageSize"] = wx_pageSize
m.T["a_key"] = a_key
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
m.T["openid"] = se.EncodeString(myopenid)
return m.Render("/weixin/resultpreview.html", &m.T)
}
func (m *Front) WxpushViewPaging() {
defer util.Catch()
var list *[]map[string]interface{}
pageNum, _ := m.GetInteger("pageNum")
if myopenid := m.Session().Get("s_m_openid"); myopenid != nil && pageNum <= wx_maxPageNum {
_, list = getWxpushViewData(myopenid.(string), pageNum)
}
m.ServeJson(map[string]interface{}{
"list": list,
"hasNextPage": list != nil && len(*list) == wx_pageSize && pageNum < wx_maxPageNum,
})
}
func getWxpushViewData(myopenid string, pageNum int) (keys []interface{}, list *[]map[string]interface{}) {
if myopenid == "" {
return
}
tmp, ok := mongodb.FindOneByField("user", `{"s_m_openid":"`+myopenid+`"}`, `{"_id":1,"o_jy":1}`)
if !ok || tmp == nil || len(*tmp) == 0 {
return
}
o_jy := (*tmp)["o_jy"].(map[string]interface{})
a_key, _ := o_jy["a_key"].([]interface{})
if len(a_key) == 0 {
return
}
for _, v := range a_key {
keyMap, _ := v.(map[string]interface{})
key, _ := keyMap["key"].([]interface{})
keys = append(keys, key)
}
field := `"_id","title","publishtime","toptype","subtype","type","area","href","areaval"`
var allkeys []elastic.KeyConfig //用户配置
_bs, err := json.Marshal(a_key)
if err == nil {
json.Unmarshal(_bs, &allkeys)
}
list = elastic.GetResForJY(INDEX, TYPE, allkeys, "", `"title"`, `{"publishtime":"desc"}`, field, (pageNum-1)*wx_pageSize, wx_pageSize)
if list != nil {
for _, v := range *list {
v["_id"] = util.EncodeArticleId2ByCheck(util.ObjToString(v["_id"]))
}
}
return
}
func (m *Front) Guide(sign string) error {
defer util.Catch()
if m.Session().Get("s_m_openid") == nil {
return m.Redirect("/swordfish/share/-1")
}
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
myopenid, _ := m.Session().Get("s_m_openid").(string)
m.T["openid"] = se.EncodeString(myopenid)
m.T["sign"] = sign
if sign == "other" {
userInfo, ok := mongodb.FindById("user", m.GetSession("userId").(string), `{"o_jy_msgset":1}`)
if ok {
m.T["msgset"] = (*userInfo)["o_jy_msgset"]
}
}
if sign == "share" {
return m.Render("/weixin/wxshareguide.html", &m.T)
} else {
return m.Render("/weixin/wxindex.html", &m.T)
}
}
func (m *Front) Share(openids string) error {
defer util.Catch()
var openid = ""
var jy_code = ""
if openids != "-1" {
wxid_code := strings.Split(openids, "__")
if len(wxid_code) > 0 {
openid = wxid_code[0]
jy_code = wxid_code[1]
}
}
m.T["openid"] = openid
m.T["jy_code"] = jy_code
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
return m.Render("/weixin/wxshare.html", &m.T)
}
func (m *Front) WxpushAjaxReq() error {
defer util.Catch()
index, _ := m.GetInteger("index")
mongodb.Update("wxpush", `{"_id":"`+m.GetString("_id")+`"}`, map[string]interface{}{
"$addToSet": map[string]interface{}{"a_visitedindex": index},
}, false, false)
return nil
}
//
func (m *Front) About() error {
defer util.Catch()
myopenid, _ := m.Session().Get("s_m_openid").(string)
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
if myopenid != "" {
m.T["A"] = "A"
}
m.T["openid"] = se.EncodeString(myopenid)
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
m.Render("/weixin/about.html")
return nil
}
//
func (m *Front) Shareabout(openids string) error {
defer util.Catch()
var openid = ""
if openids != "-1" {
wxid_code := strings.Split(openids, "__")
if len(wxid_code) > 0 {
openid = wxid_code[0]
}
}
myopenid, _ := m.Session().Get("s_m_openid").(string)
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
if openid == "" {
m.T["openid"] = se.EncodeString(myopenid)
} else {
m.T["A"] = "A"
m.T["openid"] = openid
}
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
m.Render("/weixin/about.html")
return nil
}
//
func (m *Front) Aboutsearch() error {
myopenid, _ := m.Session().Get("s_m_openid").(string)
m.T["openid"] = se.EncodeString(myopenid)
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
m.Render("/weixin/aboutsearch.html", &m.T)
return nil
}
//剑鱼微信查询保存网站
func (m *Front) AboutSR() error {
defer util.Catch()
var flag = "N"
var sn = m.GetString("searchname")
var tp = m.GetString("tp")
if len(sn) > 0 {
switch tp {
case "S": //用户查询网站是否被收录
userId, ok := m.GetSession("userId").(string)
if !ok || userId == "" {
break
}
res, err := mongodb.FindOne("bidurlinfo", bson.M{"$or": []bson.M{bson.M{"s_name": sn}, bson.M{"s_url": sn}}})
if err {
if len(*res) > 0 {
flag = "T"
}
}
break
case "I": //用户提交数据
data := make(map[string]interface{})
userId, ok := m.GetSession("userId").(string)
if !ok || userId == "" {
break
}
userInfo, ok := mongodb.FindById("user", userId, nil)
if !ok {
break
}
data["i_type"] = 8
data["s_remark"] = sn
if (*userInfo)["s_name"] != nil {
data["s_submitname"] = (*userInfo)["s_name"].(string)
}
data["s_submitid"] = userId
data["s_title"] = m.GetString("title")
data["i_status"] = 0
if (*userInfo)["s_nickname"] != nil { //昵称
data["s_username"] = (*userInfo)["s_nickname"].(string)
} else if (*userInfo)["s_name"] != nil { //s_name
data["s_username"] = (*userInfo)["s_name"].(string)
}
data["l_submitdate"] = time.Now().Unix()
data["s_source"] = m.GetString("source")
id := mongodb.Save("interaction", data)
if len(id) > 0 && len(sn) > 0 {
flag = "T"
}
break
}
}
m.ServeJson(map[string]interface{}{
"flag": flag,
})
return nil
}
//手动删除30天无更新数据
func (m *Front) DelOL() error {
defer util.Catch()
var ids []bson.ObjectId
var flag = "F"
var arrid = strings.Split(m.GetString("arrid"), ",")
if len(arrid) > 0 {
for _, chid := range arrid {
ids = append(ids, bson.ObjectIdHex(util.DecodeArticleId2ByCheck(chid)[0]))
}
}
userId, ok := m.GetSession("userId").(string)
if !ok || userId == "" || len(ids) < 1 {
m.ServeJson(map[string]interface{}{
"flag": flag,
})
return nil
}
if datas, ok := mongodb.Find("follow_project", bson.M{"_id": bson.M{"$in": ids}, "s_userid": userId}, nil, nil, false, -1, -1); ok && datas != nil {
for _, v := range *datas {
delete(v, "_id")
v["i_status"] = 2
mongodb.Save("follow_project_back", v)
go delRelRedis(v["s_openid"], v["a_relationinfo"])
}
}
if mongodb.Del("follow_project", bson.M{"_id": bson.M{"$in": ids}, "s_userid": userId}) {
flag = "T"
}
m.ServeJson(map[string]interface{}{
"flag": flag,
})
return nil
}
//获取我的反馈列表
func (f *Front) MyFeedbacks() error {
userId, _ := f.GetSession("userId").(string)
if userId == "" {
return f.Render("/_error.html")
}
list, ok := mongodb.Find("interaction", bson.M{"s_submitid": userId}, `{"l_submitdate":-1}`, `{"s_remark":1,"l_submitdate":1,"s_opinion":1,"i_status":1}`, false, 0, 200)
if !ok {
return nil
}
if f.Method() == "GET" {
f.T["list"] = list
f.T["flag"] = true
return f.Render("/weixin/feedback.html")
}
f.ServeJson(map[string]interface{}{
"list": list,
})
return nil
}
func (f *Front) GetRecomKWs() {
recomKWChan <- true
defer func() {
<-recomKWChan
}()
value := f.GetString("value")
count, _ := f.GetInteger("count")
ves := strings.Split(value, " ")
var pairs []map[string]interface{}
for _, v := range ves {
Pw, _ := M.MostSimilar(strings.Split(v, "+"), []string{}, count)
for _, p := range Pw {
sim := p.Sim
word := p.Word
if sim < float32(config.Sysconfig["recommendThreshold"].(float64)) {
continue
}
if strings.HasSuffix(word, "路") || tools.DealString(word) {
continue
}
pairs = append(pairs, map[string]interface{}{
"sim": sim,
"word": word,
})
}
}
f.ServeJson(pairs)
}
//记录用户行为--推荐关键词
func (f *Front) BehaviorRecord() {
flag := saveBehaviorRecord(f.Action,
bson.M{
"s_word": f.GetString("value"),
"s_type": f.GetString("type"),
"s_source": f.GetString("source"),
})
f.ServeJson(bson.M{"flag": flag})
}
//记录用户行为
func saveBehaviorRecord(action *xweb.Action, data bson.M) bool {
openId, _ := action.GetSession("s_m_openid").(string)
//if openId == "" {
// return false
//}
nickName, _ := action.GetSession("s_nickname").(string)
data["s_openid"] = openId
data["s_nickname"] = nickName
data["l_createtime"] = time.Now().Unix()
return len(mongodb.Save("behavior", data)) > 0
}
//取得剑鱼博客的信息列表
func (f *Front) Jyblog(param /*参数*/ string) error {
querymap := map[string]string{}
if len(param) == 0 {
querymap = map[string]string{
"perPage": f.GetString("perPage"),
"currentPage": f.GetString("currentPage"),
"contentType": "jybk",
"query": f.GetString("query"),
}
} else {
//反转生成map
paramstr := param[1:]
bs, _ := base64.StdEncoding.DecodeString(paramstr)
json.Unmarshal(bs, &querymap)
}
var shareid = f.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jybky"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
}
f.T["logid"] = config.Seoconfig["jybky"].(string)
f.DisableHttpCache()
shareid = se.EncodeString(shareid)
data, pagination := searhWebContentblog(querymap)
f.Render("/pc/jyblog.html", &xweb.T{"querymap": querymap, "data": data, "pagination": pagination, "shareid": shareid})
return nil
}
//实际的查询剑鱼博客
func searhWebContentblog(querymap map[string]string) (*[]map[string]interface{}, *[]interface{}) {
perPage, _ := strconv.Atoi(querymap["perPage"])
currentPage, _ := strconv.Atoi(querymap["currentPage"])
//修复
if perPage == 0 {
perPage = 5
}
if currentPage < 1 {
currentPage = 1
}
contentType := querymap["contentType"]
queryStr := querymap["query"]
str := ``
if queryStr != "" {
str = `{
"match": {
"s_title": {
"query":"` + queryStr + `",
"operator": "and"
}
}
},{
"match": {
"s_content": {
"query":"` + queryStr + `"
}
}
}`
}
var tempQuery = `{"query": {
"bool": {
"must":[{"term":{"s_contenttype":"` + contentType + `"}}],
"should": [` + str + `],
"minimum_should_match": 1
}
}}`
var query = tempQuery[:len(tempQuery)-1] +
`,"highlight":{
"pre_tags":[""],
"post_tags":[""],
"fields":{
"s_title":{"force_source": true}
,"s_content":{"force_source": true}
}
},"_source":["s_title","s_date","s_contenttype","s_content","releasetime","s_description","praise","s_source","s_pic","s_pic1","l_createdate","s_code","_id","s_author"]
,"from":` + fmt.Sprintf("%v", ((currentPage-1)*perPage)) + `,
"size":` + fmt.Sprintf("%v", perPage) +
`,"sort":[{"releasetime":{"order":"desc"}}] }`
total := elastic.Count("content", "content", tempQuery)
//查询列表数据
client := elastic.GetEsConn()
defer elastic.DestoryEsConn(client)
if client == nil {
return nil, nil
}
searchResult, err := client.Search().Index("content").Type("content").Source(query).Do()
if err != nil {
return nil, nil
}
var res []map[string]interface{}
if searchResult.Hits != nil {
resNum := len(searchResult.Hits.Hits)
res = make([]map[string]interface{}, resNum)
for i, hit := range searchResult.Hits.Hits {
json.Unmarshal(*hit.Source, &res[i])
//查询结果数据加工处理
for k, v := range hit.Highlight {
res[i][k] = v[0]
}
s_content, _ := res[i]["s_content"].(string)
if len(s_content) > 500 {
res[i]["s_content"] = ""
} else {
con, _ := regexp.Compile("^[^<]*?>")
content := con.ReplaceAllString(s_content, "")
con1, _ := regexp.Compile("<[^>]*$")
res[i]["s_content"] = template.HTML(con1.ReplaceAllString(content, ""))
}
s_title, _ := res[i]["s_title"].(string)
res[i]["s_title"] = template.HTML(s_title)
tmpdate, _ := res[i]["l_createdate"]
res[i]["l_createdate"] = util.TimeDiff(time.Unix(util.Int64All(tmpdate.(float64)), 0))
tmpdate1, _ := res[i]["releasetime"]
res[i]["releasetime"] = util.TimeDiff(time.Unix(util.Int64All(tmpdate1.(float64)), 0))
res[i]["_id"] = se.EncodeString(res[i]["_id"].(string))
res[i]["s_pic"] = config.Seoconfig["jyadd"].(string) + res[i]["s_pic"].(string)
res[i]["s_pic1"] = config.Seoconfig["jyadd"].(string) + res[i]["s_pic1"].(string)
}
}
//生成分页
pagination := MakePagination(perPage, currentPage, int(total), querymap, "/jyblog/index_%s.html")
return &res, &pagination
}
//计算分页,分页显示规则
func MakePagination(perPage, currentPage, total int, param map[string]string, urltpl string) []interface{} {
var totalPages int //总页数
if total == 0 {
totalPages = 1
} else {
totalPages = (total - 1 + perPage) / perPage //总页数
}
ret := make([]interface{}, 3)
index := 0
prePage, nextPage := currentPage-1, currentPage+1
if prePage < 1 {
prePage = 1
}
if nextPage > totalPages {
nextPage = totalPages
}
param["currentPage"] = strconv.Itoa(prePage)
bs, _ := json.Marshal(param)
paramstr := base64.StdEncoding.EncodeToString(bs)
url := fmt.Sprintf(urltpl, paramstr)
iscurrent := currentPage == 1
ret[index] = map[string]interface{}{"page": "< 上一页", "url": url, "iscurrent": iscurrent}
index = index + 1
param["currentPage"] = strconv.Itoa(currentPage)
bs, _ = json.Marshal(param)
paramstr = base64.StdEncoding.EncodeToString(bs)
url = fmt.Sprintf(urltpl, paramstr)
iscurrent = currentPage == currentPage
ret[index] = map[string]interface{}{"page": currentPage, "url": url, "iscurrent": iscurrent}
index = index + 1
param["currentPage"] = strconv.Itoa(nextPage)
bs, _ = json.Marshal(param)
paramstr = base64.StdEncoding.EncodeToString(bs)
url = fmt.Sprintf(urltpl, paramstr)
iscurrent = currentPage == totalPages
ret[index] = map[string]interface{}{"page": "下一页 >", "url": url, "iscurrent": iscurrent}
return ret
}
//博客三级页
func (f *Front) Jybdetail(_id string) error {
var shareid = f.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jybky"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
}
f.T["logid"] = config.Seoconfig["jybky"].(string)
shareid = se.EncodeString(shareid)
if ret := redis.Get("other", "jyblog_"+_id); ret != nil {
var retlist *map[string]interface{}
b, _ := json.Marshal(ret)
json.Unmarshal(b, &retlist)
(*retlist)["s_content"] = template.HTML((*retlist)["s_content"].(string))
(*retlist)["_id"] = (*retlist)["_id"].(string)
f.T["data"] = retlist
} else {
id := se.DecodeString(_id)
r := elastic.GetByIdField("content", "content", id, `"_id","s_title","l_createdate","s_pic","s_author","s_editorname","s_contenttype","praise","releasetime","s_subcontent","s_url","s_content","s_source","s_keywords","s_description","s_contenttype"`)
if r != nil {
tmpdate1, _ := (*r)["l_createdate"]
(*r)["l_createdate"] = util.TimeDiff(time.Unix(util.Int64All(tmpdate1.(float64)), 0))
tmpdate2, _ := (*r)["releasetime"]
(*r)["releasetime"] = util.TimeDiff(time.Unix(util.Int64All(tmpdate2.(float64)), 0))
(*r)["s_content"] = template.HTML((*r)["s_content"].(string))
(*r)["_id"] = se.EncodeString((*r)["_id"].(string))
(*r)["s_pic"] = (*r)["s_pic"].(string)
}
f.DisableHttpCache()
redis.Put("other", "jyblog_"+_id, r, 2*60*60)
f.T["data"] = r
}
f.T["shareid"] = shareid
return f.Render("/pc/jyblogdetail.html", &f.T)
}
//
func (f *Front) Blogpraise() error {
defer util.Catch()
id := se.DecodeString(f.GetString("id"))
stype := f.GetString("type")
flag := "F"
var blogflag = true
util.Try(func() {
if id != "" {
if stype == "up" {
blogflag = mongodb.Update("content", `{"_id":"`+id+`"}`, `{ "$inc" : { "praise" : 1 }}`, false, false)
} else if stype == "down" {
blogflag = mongodb.Update("content", `{"_id":"`+id+`"}`, `{ "$inc" : { "praise" : -1 }}`, false, false)
}
if blogflag {
flag = "T"
r, _ := mongodb.FindById("content", id, "")
elastic.UpdateNewDoc("content", "content", r)
redis.Del("other", "jyblog_"+f.GetString("id"))
}
}
}, func(e interface{}) {
log.Println("文章点赞出错", e)
})
f.ServeJson(map[string]interface{}{
"flag": flag,
})
return nil
}
//
func getRewardText() (string, string) {
rewardText, _ := config.Sysconfig["rewardText"].([]interface{})
advertText, _ := config.Sysconfig["advertText"].([]interface{})
randVal := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(rewardText))
if len(advertText) != 0 {
advVal := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(advertText))
return util.ObjToString(rewardText[randVal]), util.ObjToString(advertText[advVal])
} else {
return util.ObjToString(rewardText[randVal]), ""
}
}
//
func searchresulthtml(list *[]map[string]interface{}) string {
var listhtml = ""
var j = 1
for i := 0; i < len(*list); i++ {
listdata := (*list)[i]
j = i + 1
listhtml += `` + strconv.Itoa(j) + `.
`
if listdata["title"] != "" {
listhtml += ``
}
area, _ := listdata["area"].(string)
area = strings.TrimSpace(area)
finalType, _ := listdata["subtype"].(string)
if finalType == "" {
finalType = util.ObjToString(listdata["toptype"])
}
if finalType == "" {
finalType = util.ObjToString(listdata["type"])
if finalType == "bid" {
finalType = "中标"
} else if finalType == "tender" {
finalType = "招标"
} else {
finalType = ""
}
}
stpadd, areaadd := classify(finalType, area)
if area != "" && area != "A" {
listhtml += `
` + area + ``
}
if finalType != "" {
listhtml += `
` + finalType + ``
}
publishtime, _ := listdata["publishtime"].(float64)
if publishtime != 0 {
diff := util.TimeDiff(time.Unix(util.Int64All(publishtime), 0))
if diff != "" {
listhtml += `
` + diff + ``
}
}
listhtml += `
`
}
return listhtml
}
//标签查询
func (f *Front) SearchResult(at, name string) error {
defer util.Catch()
var no = 5
var area = ""
var stype = ""
var startPage, currentPage, limitcount int
limitcount = util.IntAll(config.Seoconfig["limitcount"])
var res = ""
var seotitle = ""
var seokeywords = ""
var seodescription = ""
var shareid = f.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jybqy"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
}
f.T["logid"] = config.Seoconfig["jybqy"].(string)
if at == "area" {
areamp, _ := config.Seoconfig["area"].(map[string]interface{})
if areamp != nil {
areamp1 := areamp[name].(map[string]interface{})
if areamp1 != nil {
area = areamp1["NAME"].(string)
seotitle = areamp1["TITLE"].(string)
seokeywords = areamp1["KEYWORDS"].(string)
seodescription = areamp1["DESCRIPTION"].(string)
}
}
} else if at == "stype" {
stypemp, _ := config.Seoconfig["stype"].(map[string]interface{})
if stypemp != nil {
stypemp1 := stypemp[name].(map[string]interface{})
if stypemp1 != nil {
stype = stypemp1["NAME"].(string)
seotitle = stypemp1["TITLE"].(string)
seokeywords = stypemp1["KEYWORDS"].(string)
seodescription = stypemp1["DESCRIPTION"].(string)
}
}
}
f.T["seoarea"] = area
f.T["seostype"] = stype
f.T["seotitle"] = seotitle
f.T["seokeywords"] = seokeywords
f.T["seodption"] = seodescription
if area == "全国" {
return f.Redirect("/swordfish/searchinfolist.html")
}
if area != "" || stype != "" {
list := redis.Get("other", "classify_"+name)
query1 := `{"query": {"bool": {"must":[`
if area != "" {
query1 += `{"term":{"area":"` + area + `"}}`
} else if stype != "" {
query1 += `{"term":{"subtype":"` + stype + `"}}`
}
query1 += `],"should": [],"minimum_should_match": 1}}}`
query := getLastNewsQuery(area, "", stype)
var datas *[]map[string]interface{}
if list == nil {
count := elastic.Count(INDEX, TYPE, query1)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
currentPage = no
startPage = r.Intn(currentPage * limitcount)
count1 := util.IntAll(count)
if count1 < startPage || startPage < 0 {
startPage = 0
}
datas = elastic.GetPage(INDEX, TYPE, query, bidSearch_sort, `"_id","title","publishtime","toptype","subtype","type","area","href"`, startPage, limitcount)
redis.Put("other", "classify_"+name, datas, 2*60*60)
} else {
b, _ := json.Marshal(list)
json.Unmarshal(b, &datas)
}
res = searchresulthtml(datas)
f.T["res"] = res
f.T["area"] = area
f.T["stype"] = stype
f.SetSession("paramarea", area)
f.SetSession("paraminfotype", stype)
f.T["shareid"] = se.EncodeString(shareid)
}
return f.Render("/pc/classifylist.html", &f.T)
}
//
func classify(stp, area string) (string, string) {
var areas, _ = config.Seoconfig["area"].(map[string]interface{})
var stypes, _ = config.Seoconfig["stype"].(map[string]interface{})
var tpadd = ""
var areaadd = ""
if area != "" && area != "A" {
for k, v := range areas {
if area == v.(map[string]interface{})["NAME"] {
areaadd = k
}
}
}
if stp != "" {
for k, v := range stypes {
if stp == v.(map[string]interface{})["NAME"] {
tpadd = k
}
}
}
return tpadd, areaadd
}
//历史推送
func (f *Front) Historypush() error {
userId, _ := f.GetSession("userId").(string)
if userId == "" {
return f.Redirect("/swordfish/share/-1")
}
myopenid, _ := f.GetSession("s_m_openid").(string)
mynickname, _ := f.Session().Get("s_nickname").(string)
myavatar, _ := f.Session().Get("s_avatar").(string)
var thistime int64
var list *[]map[string]interface{}
var success bool
if userId != "" {
lasttime := time.Now().Local().Unix()
thistime, list = getHistorypush(lasttime, userId, nil, 0)
if list != nil && len(*list) > 0 {
success = true
}
}
f.T["data"] = list
f.T["thistime"] = thistime
f.T["success"] = success
f.T["nickname"] = mynickname
f.T["avatar"] = myavatar
f.T["signature"] = wx.SignJSSDK(f.Site() + f.Url())
f.T["openid"] = se.EncodeString(myopenid)
return f.Render("/weixin/historypush.html")
}
func (f *Front) HistorypushPaging() error {
lasttime, _ := f.GetInt("lasttime")
userId, _ := f.GetSession("userId").(string)
res := map[string]interface{}{}
res["success"] = false
if userId != "" && lasttime > 0 {
if lasttime == 1 {
lasttime = time.Now().Local().Unix()
}
thistime, list := getHistorypush(lasttime, userId, nil, 0)
if list != nil && len(*list) > 0 {
res["success"] = true
res["data"] = &list
res["thistime"] = thistime
}
}
f.ServeJson(&res)
return nil
}
func getHistorypush(lasttime int64, sid string, res []map[string]interface{}, count int) (thistime int64, list *[]map[string]interface{}) {
thistime = lasttime
if res == nil {
res = make([]map[string]interface{}, 0)
}
list = &res
tmps, ok := mongodb.Find("wxpush", &map[string]interface{}{
"s_uid": sid,
"l_date": map[string]interface{}{
"$lt": lasttime,
},
}, `{"l_date":-1}`, nil, false, 0, 1)
if ok && (*tmps) != nil && len(*tmps) == 1 && (*tmps)[0] != nil {
tmp := (*tmps)[0]
at := tmp["o_pushinfo"]
if at != nil {
ats := at.(map[string]interface{})
thistime = tmp["l_date"].(int64)
count += len(ats)
tmp["count"] = len(ats)
res = append(res, tmp)
list = &res
if count >= wx_pageSize {
return
}
} else {
return
}
} else {
return
}
return getHistorypush(thistime, sid, res, count)
}
//电脑端招标订阅
func (m *Front) Subscribe() error {
var shareid = m.GetString("id")
if len(shareid) == 0 {
shareid = fmt.Sprintf("%s%d", config.Seoconfig["jydyy"].(string)+fmt.Sprintf("%d", time.Now().UnixNano())[8:14], rand.Intn(9))
}
m.T["logid"] = config.Seoconfig["jydyy"].(string)
m.T["noshareid"] = shareid
m.T["shareid"] = se.EncodeString(shareid)
myopenid, _ := m.Session().Get("s_m_openid").(string)
m.T["openid"] = se.EncodeString(myopenid)
mynickname, _ := m.Session().Get("s_nickname").(string)
myavatar, _ := m.Session().Get("s_avatar").(string)
m.T["nickname"] = mynickname
m.T["avatar"] = myavatar
m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
return m.Render("/pc/subscribe.html", &m.T)
}
/*
* 结果列表转换,目前只换行行业字段
* 所有的招标搜索都要调用此方法,列表中有展示行业的也可以用
* industry 搜索条件中的行业,默认为空
*/
func bidListConvert(industry string, list *[]map[string]interface{}) {
if list == nil {
return
}
commonSubstring := func(v string) (value string) {
bcs := strings.Split(v, "_")
if len(bcs) == 1 {
value = bcs[0]
} else if len(bcs) == 2 {
value = bcs[1]
if strings.TrimSpace(value) == "" {
value = bcs[0]
}
}
return
}
for _, v := range *list {
value := ""
biddingcontent, _ := v["biddingcontent"].([]interface{})
bct := util.ObjArrToStringArr(biddingcontent)
if bct == nil || len(bct) == 0 {
continue
}
//搜索条件中没有行业的话,取查询结果中第一个行业
if industry == "" {
value = commonSubstring(bct[0])
} else { //搜索条件中有行业的话,取行业中和搜索条件相对应的第一个
industrys := strings.Split(industry, ",")
L:
for _, bc := range bct {
for _, is := range industrys {
if bc == is {
value = commonSubstring(bc)
break L
}
}
}
}
if strings.TrimSpace(value) == "" {
continue
}
v["industry"] = value
}
}