CommonFunc.lua 8.31 KB
local skynet = require "skynet"
local cjson = require "shared.json"
local md5 = require("md5")
local httpc = require("http.httpc")

local servId = tonumber(skynet.getenv("servId"))
function getRandomName()
	local nameCsv = csvdb["name_combCsv"]
	local part1 = nameCsv[1][math.random(1, #nameCsv[1])].name
	local part2 = nameCsv[2][math.random(1, #nameCsv[2])].name
	local part3 = nameCsv[3][math.random(1, #nameCsv[3])].name

	return table.concat({part1, part2, part3})
end

function getActionCode(role)
	if not role.uniqueCount then
		role.uniqueCount = 0
	end
	local action = {role:getProperty("id"), skynet.timex(), role.uniqueCount}
	role.uniqueCount = role.uniqueCount + 1
	return table.concat(action, "_")
end

-- begin 	数据库自增字段
function getNextRoleId()
	local roleId = redisproxy:hget("autoincrement_set", "role")
	if roleId - servId * MAX_ROLE_NUM >= MAX_ROLE_NUM - 1 then
		return
	end
	return redisproxy:hincrby("autoincrement_set", "role", 1)
end

function getNextTradeId()
	return redisproxy:hincrby("autoincrement_set", "trade", 1)
end

-- end 		数据库自增字段

-- 查找上限
-- [10, 20, 30, 40] 查找15, 返回指向10的元素
function lowerBoundSeach(data, searchKey)
	-- 先排序
	local lastKey = nil
	local keys = table.keys(data)
	table.sort(keys)
	for _, key in ipairs(keys) do
		if key > searchKey then
			break
		end
		lastKey = key
	end

	return lastKey and data[lastKey] or nil
end

-- 将201402021800或者20140202的格式转化成unixtime
function toUnixtime(timeStr)
	local strLength = string.len(timeStr)
	if strLength ~= 8 and strLength ~= 10 then return end
	local year = string.sub(timeStr, 1, 4)
	local month = string.sub(timeStr, 5, 6)
	local day = string.sub(timeStr, 7, 8)
	local hour, minute = 0, 0
	if strLength == 10 then
		hour = string.sub(timeStr, 9, 10)
		--minute = string.sub(timeStr, 11, 12)
	end
    return os.time{year=year, month=month, day=day, hour=hour, min=minute, sec=0}
end

-- 判断时间点是不是当天
function isToday(curTimestamp)
	local curTm = os.date("*t", curTimestamp)
	local nowTm = os.date("*t", skynet.timex())
	return curTm.year == nowTm.year and curTm.month == nowTm.month and curTm.day == nowTm.day
end

function withTimeHead(value, now)
	now = now or skynet.timex()
	return (2000000000-now) .. "." .. value
end

function cutTimeHead(value)
	return tonumber(value:match("%d+%.(%d+)"))
end

-- 判断是不是同一个星期
function isCrossWeek(target, now)
	now = now or skynet.timex()
	return specMonday(target) ~= specMonday(now - RESET_TIME * 3600)
end

-- 两个时间相隔多少星期
function crossWeek(target, now)
	now = now or skynet.timex()
	return math.floor((specMonday(target)-specMonday(now))/604800)
end

-- 判断是不是同一个月
function isCrossMonth(target, now)
	now = now or skynet.timex()
	local tarTm = os.date("*t", target)
	local nowTm = os.date("*t", now - RESET_TIME * 3600)
	if tarTm.year == nowTm.year and tarTm.month == nowTm.month then
		return false
	else
		return true
	end
end

function isCrossDay(lastTime, now, resetTime)
	resetTime = resetTime or RESET_TIME
	if lastTime == 0 then return true end
	now = now or skynet.timex()
	local todayResetH = specTime({hour = resetTime}, now - resetTime * 3600)
	return lastTime < todayResetH and now >= todayResetH
end

function crossDay(target, now)
	now = now or skynet.timex()

	local tarTime = specTime({hour = RESET_TIME}, target)
	--local nowTime = specTime({hour = RESET_TIME}, now) --当前时间有没有过一天而不是当前天四点
	return math.floor((now - tarTime)/ 86400)	
end

function crossWeekFromOpen(now)
	now = now or skynet.timex()
	local openTime = os.time{
		year = tonum(SERV_OPEN:sub(1,4)),
		month = tonum(SERV_OPEN:sub(5,6)),
		day = tonum(SERV_OPEN:sub(7,8)),
	}
	return crossWeek(openTime, now)
end

function crossDayFromOpen(now)
	now = now or skynet.timex()
	local openTime = os.time{
		year = tonum(SERV_OPEN:sub(1,4)),
		month = tonum(SERV_OPEN:sub(5,6)),
		day = tonum(SERV_OPEN:sub(7,8)),
		hour = RESET_TIME,
	}
	return crossDay(openTime, now)
end

-- 30*86400 = 2592000
function monthLater(now)
	now = now or skynet.timex()
	now = now - RESET_TIME * 3600  -- 排除0-4点钟 影响 
	return specTime({hour = RESET_TIME}, now) + 2592000
end
-- 一天以后
function dayLater(now)
	now = now or skynet.timex()
	now = now - RESET_TIME * 3600  -- 排除0-4点钟 影响 
	return specTime({hour = RESET_TIME}, now) + 86400
end
-- 到下一个时间点的秒数差和下一个时间点的unixtime
function diffTime(params)
	params = params or {}
	local currentTime = skynet.timex()

	local curTm = os.date("*t", currentTime)
	local nextYear = params.year or curTm.year
	local nextMonth = params.month or curTm.month
	local nextDay = params.day or curTm.day + 1
	local nextHour = params.hour or 0
	local nextMinute = params.min or 0
	local nextSecond = params.sec or 0

	local nextUnixTime = os.time({ year = nextYear, month = nextMonth, day = nextDay, hour = nextHour, min = nextMinute, sec = nextSecond})
	return os.difftime(nextUnixTime, currentTime), nextUnixTime
end

-- 取今天特殊时刻时间戳
function specTime(pms, now)
	now = now or skynet.timex()
	local tm = os.date("*t", now)
	local year = pms.year or tm.year
	local month = pms.month or tm.month
	local day = pms.day or tm.day
	local hour = pms.hour or 0
	local min = pms.min or 0
	local sec = pms.sec or 0
	return os.time({year = year, month = month, day = day, hour = hour, min = min, sec = sec})
end

function specMonday(now)
	now = now or skynet.timex()
	local tm = os.date("*t", now)
	local wday = (tm.wday + 6) % 7
	if wday == 0 then wday = 7 end

	local time = os.time({year = tm.year, month = tm.month, day = tm.day})
	return time - (wday - 1) * 86400
end

function isSpecTime(startHour, endHour, specday)
	local tm = os.date("*t", skynet.timex())
	if specday then
		local day = (tm.wday+6)%7
		if day == 0 then day = 7 end
		return specday == day and tm.hour >= startHour and tm.hour < endHour
	end
	return tm.hour >= startHour and tm.hour < endHour
end

function getSecond(timeStr)
	timeStr = timeStr or "0000"
	local hour = tonumber(string.sub(timeStr, 1, 2))
	local min  = tonumber(string.sub(timeStr, 3, 4))
	return hour * 3600 + min * 60
end

function urlencode(str)
   if (str) then
      str = string.gsub (str, "\n", "\r\n")
      str = string.gsub (str, "([^%w ])",
         function (c) return string.format ("%%%02X", string.byte(c)) end)
      str = string.gsub (str, " ", "+")
   end
   return str
end

function isnan(value)
	return value ~= value
end

-- 推送通知
local serverid = skynet.getenv "serverid"
local secretKey = "467C2221D3A20FE69D23A33E8940C2C5"

-- 推送该服务器的所有用户
-- tag都是交集处理
function notifyClients(msg, otherTags)
	local tags = { serverid }
	for _, tag in ipairs(otherTags or {}) do
		table.insert(tags, tag)
	end

	local content = {
		["appid"] = "1000013239",
		["audience"] = {
			[otherTags and "tag_and" or "tag"] = tags,
		},
		-- ["audience"] = "all",
		["notification"] = {
			["alert"] = msg,
		},
		["options"] = {
     		["ttl"] = 60 * 120
   		}
	}

	local contentJson = cjson.encode(content)
	local header = {
		["content-type"] = "application/x-www-form-urlencoded",
		["X-MJPUSH-SIGNATURE"] = md5.sumhexa(urlencode(contentJson .. "&" .. secretKey))
	}

	local status, body = httpc.request("POST", "push.mjyun.com", "/api/push", {}, header, contentJson)
	if tonumber(status) ~= 200 then
		skynet.error(status, body)
	end
end

-- { uid, msg, scheduleTime}
function notifyClient(params)
	params = params or {}
	params.key = "zhaolugame20170831"

	local status, body = httpc.get(skynet.getenv("codeurl"), 
		"/mipush/notify_user?" .. httpGetFormatData(params), {}, {})
	if tonumber(status) ~= 200 then
		skynet.error(status, body)
		return
	end

	return body
end

-- { uid, msgId}
function deleteNotify(params)
	params = params or {}
	params.key = "zhaolugame20170831"

	local status, body = httpc.get(skynet.getenv("codeurl"), 
		"/mipush/delete_notify?" .. httpGetFormatData(params), {}, {})
	if tonumber(status) ~= 200 then
		skynet.error(status, body)
		return
	end

	return body
end

--http get数据
function httpGetFormatData(params)
	local function escape(s)
		return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
			return string.format("%%%02X", string.byte(c))
		end))
	end

	local body = {}
	for k, v in pairs(params) do
		table.insert(body, string.format("%s=%s", escape(k), escape(v)))
	end

	return table.concat(body, "&")
end