userSessionLog.js 5.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/**
 * @class UserSessionLog 用户会话日志模型
 */
const BaseMod = require('./base')
const Platform = require('./platform')
const Channel = require('./channel')
const {
	DateTime
} = require('../lib')
module.exports = class UserSessionLog extends BaseMod {
	constructor() {
		super()
		this.tableName = 'user-session-logs'
	}

	/**
	 * 用户会话日志数据填充
	 * @param {Object} params 上报参数
	 */
	async fill(params) {

		if (!params.sid) {
			return {
				code: 200,
				msg: 'Not found session log'
			}
		}

		if (!params.uid) {
			return {
				code: 200,
				msg: 'Parameter "uid" not found'
			}
		}

		const dateTime = new DateTime()
		const platform = new Platform()
		const channel = new Channel()

		//获取当前页面信息
		if (!params.page_id) {
			const pageInfo = await page.getPageAndCreate(params.ak, params.url, params.ttpj)
			if (!pageInfo || pageInfo.length === 0) {
				return {
					code: 300,
					msg: 'Not found this entry page'
				}
			}
			params.page_id = pageInfo._id
		}

		const nowTime = dateTime.getTime()

		const fillParams = {
			appid: params.ak,
			version: params.v ? params.v : '',
			platform: platform.getPlatformCode(params.ut, params.p),
			channel: channel.getChannelCode(params),
			session_id: params.sid,
			uid: params.uid,
			last_visit_time: nowTime,
			entry_page_id: params.page_id,
			exit_page_id: params.page_id,
			page_count: 0,
			event_count: 0,
			duration: 1,
			is_finish: 0,
			create_time: nowTime,
		}

		const res = await this.insert(this.tableName, fillParams)

		if (res && res.id) {
			return {
				code: 0,
				msg: 'success'
			}
		} else {
			return {
				code: 500,
				msg: 'User session log filled error'
			}
		}
	}

	/**
	 * 检测用户会话是否有变化,并更新
	 * @param {Object} params 校验参数 - sid:基础会话编号 uid:用户编号 last_visit_user_id:基础会话中最近一个访问用户的编号
	 */
	async checkUserSession(params) {
		if (!params.sid) {
			return {
				code: 200,
				msg: 'Not found session log'
			}
		}

		if (!params.uid) {
			//用户已退出会话
			if (params.last_visit_user_id) {
				if (this.debug) {
					console.log('user "' + params.last_visit_user_id + '" is exit session :', params.sid)
				}
				await this.closeUserSession(params.sid)
			}
		} else {
			//添加用户日志
			if (!params.last_visit_user_id) {
				await this.fill(params)
			}
			//用户已切换
			else if (params.uid != params.last_visit_user_id) {
				if (this.debug) {
					console.log('user "' + params.last_visit_user_id + '" change to "' + params.uid +
						'" in the session :', params.sid)
				}
				//关闭原会话生成新用户对话
				await this.closeUserSession(params.sid)
				await this.fill(params)
			}
		}
		return {
			code: 0,
			msg: 'success'
		}
	}



	/**
	 * 关闭用户会话
	 * @param {String} sid 基础会话编号
	 */
	async closeUserSession(sid) {
		if (this.debug) {
			console.log('close user session log by sid:', sid)
		}
		return await this.update(this.tableName, {
			is_finish: 1
		}, {
			session_id: sid,
			is_finish: 0
		})
	}


	/**
	 * 更新会话信息
	 * @param {String} sid 基础会话编号
	 * @param {Object} data 更新数据
	 */
	async updateUserSession(sid, data) {

		const userSession = await this.getCollection(this.tableName).where({
			session_id: sid,
			uid: data.uid,
			is_finish: 0
		}).orderBy('create_time', 'desc').limit(1).get()

		if (userSession.data.length === 0) {
			console.log('Not found the user session', {
				session_id: sid,
				uid: data.uid,
				is_finish: 0
			})
			return {
				code: 300,
				msg: 'Not found the user session'
			}
		}

		let nowTime = data.nowTime ? data.nowTime : new DateTime().getTime()
		const accessTime = nowTime - userSession.data[0].createTime
		const accessSenconds = accessTime > 1000 ? parseInt(accessTime / 1000) : 1

		const updateData = {
			last_visit_time: nowTime,
			duration: accessSenconds,
		}

		//访问页面数量
		if (data.addPageCount) {
			updateData.page_count = userSession.data[0].page_count + data.addPageCount
		}
		//最终访问的页面编号
		if (data.pageId) {
			updateData.exit_page_id = data.pageId
		}
		//产生事件次数
		if (data.eventCount) {
			updateData.event_count = userSession.data[0].event_count + data.addEventCount
		}

		if (this.debug) {
			console.log('update user session log by sid-' + sid, updateData)
		}

		await this.update(this.tableName, updateData, {
			_id: userSession.data[0]._id
		})

		return {
			code: 0,
			msg: 'success'
		}
	}

	/**
	 * 清理用户会话日志数据
	 * @param {Object} days 保留天数, 留存统计需要计算30天后留存率,因此至少应保留31天的日志数据
	 */
	async clean(days = 31) {
		days = Math.max(parseInt(days), 1)
		console.log('clean user session logs - day:', days)

		const dateTime = new DateTime()
		const res = await this.delete(this.tableName, {
			create_time: {
				$lt: dateTime.getTimeBySetDays(0 - days)
			}
		})

		if (!res.code) {
			console.log('clean user session log:', res)
		}
		return res
	}

}