• 0
  • 0

Uniapp 统计用户在线时长

2019-09-03 68 0 admin 所属分类:Hbuilder

JS函数实现

check_online() {
    setTimeout(() = > {
        if (common.setting.check_online_second != undefined) {
            if (common.setting.check_online_timerid > 0) {
                return false;
            }
            common.setting.check_online_timerid = setInterval(() = > {
                this.updateOnline((res) = > {
                    console.log("res: " + JSON.stringify(res));
                    console.log("updateOnline callback:", res.msg);
                });
            }, common.setting.check_online_second * 1000);
        }
    }, 500);
}
updateOnline(callBack) {
    var data = {};
    this.post('rider', 'updateOnline', data, callBack);
}
/**
 * 网络请求,异步版
 */
web(url, method = 'GET', postData, callBack) {
    var that = this.token;
    // 当前客户端类型(0=微信,1=安卓, 2=IOS)
    var provider = 0;
    // #ifdef APP-PLUS
    if (common.sysinfo.platform == 'android') {
        provider = 1;
    } else {
        provider = 2;
    }
    // #endif
    if (common.userinfo.token == undefined) {
        common.userinfo.token = '';
    }
    uni.request({
        url: url,
        method,
        header: {
            'content-type': 'application/x-www-form-urlencoded',
            'ED-Token': common.userinfo.token,
            'ED-Source': common.client,
            'ED-Provider': provider,
            'ED-Version': common.localinfo.version,
        },
        data: postData,
        success(res) {
            callBack(res.data);
        }
    });
},
post(mod, ac, postData, callBack, repost = 0) {
    // iOS端
    var baseurl = this.SITE;
    var that = this;
    var url = baseurl + 'api/' + mod + '/' + ac;
    this.web(url, 'POST', postData, function(res) {
        if (repost == 1) {
            if (callBack != undefined) {
                return callBack(res);
            } else {
                return true;
            }
        }
        // 返回的非对象(JSON),可能是网络错误或数据错误
        if (typeof(res) != 'object') {
            if (common.setting.ap_debug == true) {
                console.log('object object object');
                console.log(mod, ac, postData);
                uni.showModal({
                    content: '错误(只有管理员显示):' + res.toString(),
                    showCancel: false,
                });
                uni.setClipboardData({
                    data: '错误(只有管理员显示):' + res.toString()
                })
            }
            if (typeof(callBack) != 'object') {
                return false;
            }
            if (res == '') {
                callBack({
                    status: 0,
                    msg: '操作失败,原因:网络错误,请重试1000'
                });
            } else {
                // 数据库错误、返回错误
                callBack({
                    status: 0,
                    msg: '操作失败,原因:网络错误,请重试1001'
                });
            }
            // 失效(无效token))
        } else if (res.status == -1) {
            if (common.has_logout == true) {
                return false;
            }
            fun.to_login_page();
            // token过期
        } else if (res.status == -2) {
            console.log("======2");
            that.refresh_token(common.userinfo.token, function(res) {
                // 换取token成功,重新赋值和保存
                if (res.status == 1) {
                    common.userinfo.login = true;
                    console.log('换取token成功,重新赋值和保存');
                    common.userinfo.token = res.data;
                    uni.setStorageSync("userinfo", common.userinfo);
                }
                that.post(mod, ac, postData, callBack, 1);
            });
        } else {
            if (res.status == undefined && res.msg == undefined) {
                res.msg = '网络错误,请重试';
            }
            if (callBack != undefined) {
                callBack(res);
            }
        }
    });
}

数据表结构

CREATE TABLE `user_online` (
`id`  int(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`uid`  int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'UID' ,
`dateline`  varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '日期 年月日 20191011' ,
`first_online`  int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '当天第一次在线时间' ,
`last_online`  int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '当天最后一次请求时间' ,
`online_time`  int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '在线时长   间隔' ,
PRIMARY KEY (`id`),
INDEX `uid` (`uid`) USING BTREE ,
INDEX `dateline` (`dateline`) USING BTREE 
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
COMMENT='骑手在线记录表'
;

PHP 相关方法

public function get($id)
{
    if (!$row = $this->fetch($id)) {
        return [];
    }

    return $row;
}

//获取某一天的骑手在线信息
public function getByDate($rider_id,$date) {
    return fetch_first("SELECT * FROM pre_wukong_rider_online WHERE `rider_id`='{$rider_id}' and `dateline`='{$date}'");
}

//更新当天骑手在线信息
public function updateOnline() {
    global $_USER,$setting;
    $date = date('Ymd',TIMESTAMP);
    $row = $this->getByDate($_USER['uid'],$date);
    if ($row) {
        if (TIMESTAMP - $row['last_online']<$setting['check_online_second']) {
            fail('请求太频繁了');
        }
        $data = [
            'last_online'=>TIMESTAMP,
            'online_time'=>$row['online_time'] + $setting['check_online_second'],
        ];
        $this->update($row['id'],$data);
    } else {
        $data = [
            'rider_id'=>$_USER['uid'],
            'dateline'=>$date,
            'first_online'=>TIMESTAMP,
            'last_online'=>TIMESTAMP,
            'online_time'=>$setting['check_online_second']
        ];
        $this->insert($data);
    }
    succ('更新成功');
}

public function getOnlineInfo() {
    global $_USER,$setting;
    $data = [];
    $rider = fetch_first("select * from pre_wukong_riders where user_id={$_USER['uid']}");
    $data['today'] = $this->getByDate($_USER['uid'],date('Ymd',TIMESTAMP));
    $data['day_online_time'] = $rider['day_online_time']>0?$rider['day_online_time']*3600:$setting['day_online_time']*3600;
    $data['list'] = $this->recent_online_data($_USER['uid']);
    succ($data);
}

//最近的在线数据
public function recent_online_data($rider_id,$limit=60) {
    $date = date('Ymd',TIMESTAMP);
    $sql = "SELECT * FROM pre_wukong_rider_online WHERE `rider_id`='{$rider_id}' and `dateline`<'{$date}' order by id desc limit {$limit}";
    return fetch_all($sql);
}


返回顶部