Commit 5e5538e2 by 汤文兵

/data/ugenCloud/app/publicComponent

parent d168d1dd
...@@ -90,6 +90,7 @@ class WXSDK{ ...@@ -90,6 +90,7 @@ class WXSDK{
r(JSON.parse(data)); r(JSON.parse(data));
}) })
.on('error', (error) => { .on('error', (error) => {
console.log(error)
j(error); j(error);
}); });
}); });
......
const request = require('request');
const crypto = require('crypto');
const schedule = require('node-schedule');
const LOG = require('iot-cloud-core').LOG;
const wxRPC = require('../../grpc/WXPRC');
const url = 'https://api.weixin.qq.com/';
class WXSDK{
constructor(params,appid) {
checkKeyExists(params, "appid");
this.appid = appid;
this.wx_appid = params.appid;
this.wx_secret = params.secret;
this.isComponent = params.isComponent?true:false;
this.wxObj = this.isComponent?wxRPC:this;
this.refreshToken();
let j = schedule.scheduleJob("0 0 */1 * * *", ()=>{
this.refreshToken();
});
}
async refreshToken(){
this.wxInfo = await this.wxObj.getInfo(this.appid.toString());
LOG.info(this.wxInfo);
}
getWXToken(){
if (this.wxInfo) {
return this.wxInfo.access_token;
}else{
return false;
}
}
auth(params){
checkKeyExists(params, "code");
if(this.isComponent){
return this.authComponent(params);
}
return this.send({ url: 'sns/oauth2/access_token?appid=' + this.wx_appid + '&secret=' + this.wx_secret + '&code=' + params.code + '&grant_type=authorization_code' });
}
authComponent(params){
checkKeyExists(params, "code");
return this.send({ url: 'sns/oauth2/component/access_token?appid=' + this.wx_appid + '&code=' + params.code + '&grant_type=authorization_code&component_appid=' + this.wxInfo.component_appid + '&component_access_token=' + this.wxInfo.component_access_token });
}
getUserinfo(params) {
checkKeyExists(params, "openid");
return this.send({ url: 'sns/userinfo?access_token=' + params.access_token + '&openid=' + params.openid + '&lang=zh_CN' });
}
model(parmas){
checkKeyExists(parmas,"data");
return this.send({url:'cgi-bin/message/template/send?access_token='+this.wxInfo.access_token,type:'post',data:parmas.data});
}
// unBind(parmas){
// checkKeyExists(parmas,"data");
// return this.send({url:'device/unbind?access_token='+this.accessToken,type:'post',data:parmas.data});
// }
getAccessToken() {
return this.send({ url: 'cgi-bin/token?grant_type=client_credential&appid=' + this.wx_appid + '&secret=' + this.wx_secret });
}
getJsToken(params) {
checkKeyExists(params,"access_token");
return this.send({ url: 'cgi-bin/ticket/getticket?access_token=' + params.access_token + '&type=jsapi' });
}
async getInfo(){
let access_token = await this.getAccessToken();
let jsapi_ticket = await this.getJsToken(access_token);
return {
access_token:access_token.access_token,
js_ticket:jsapi_ticket.ticket
};
}
send(params) {
checkKeyExists(params, "url");
return new Promise((r,j)=>{
let data;
let p;
if (params.type == 'post') {
p = request.post(url + params.url);
if (params, "data")
p.json(params.data);
}else{
p = request.get(url + params.url);
}
p.on('response', (response) => {
if (response.statusCode !== 200)
j(response);
}).on('data', (data) => {
r(JSON.parse(data));
})
.on('error', (error) => {
j(error);
});
});
}
createNonceStr() {
return Math.random().toString(36).substr(2, 15);
};
createTimestamp() {
return parseInt(new Date().getTime() / 1000) + '';
};
raw(args) {
var keys = Object.keys(args);
keys = keys.sort()
var newArgs = {};
keys.forEach(function (key) {
newArgs[key.toLowerCase()] = args[key];
});
var string = '';
for (var k in newArgs) {
string += '&' + k + '=' + newArgs[k];
}
string = string.substr(1);
return string;
};
getSign(params) {
checkKeyExists(params, "url");
var ret = {
jsapi_ticket: this.wxInfo.js_ticket,
nonceStr: this.createNonceStr(),
timestamp: this.createTimestamp(),
url: params.url
};
var string = this.raw(ret);
var sha1 = crypto.createHash('sha1');
sha1.update(string);
ret.signature = sha1.digest('hex');
delete ret.jsapi_ticket;
return ret;
};
}
function checkKeyExists(map, ...keys) {
for(let key of keys){
if (!(key in map))
throw new ParamsError(key + " is undefined");
}
}
module.exports = WXSDK;
\ No newline at end of file
...@@ -127,7 +127,8 @@ class DeviceController extends ControllerBase{ ...@@ -127,7 +127,8 @@ class DeviceController extends ControllerBase{
* @param {number} device_id - 设备id * @param {number} device_id - 设备id
*/ */
async getUsersAction(data){ async getUsersAction(data){
let res = await this.dao.get('device').findUsers(data.params); let params=data.params;
let res = await this.dao.get('device').findUsers(params);
return res; return res;
} }
...@@ -145,8 +146,9 @@ class DeviceController extends ControllerBase{ ...@@ -145,8 +146,9 @@ class DeviceController extends ControllerBase{
if(!await this.public.core.checkRole({user_id:data.user.uid,device_id:data.params.device_id},"admin")){ if(!await this.public.core.checkRole({user_id:data.user.uid,device_id:data.params.device_id},"admin")){
this.error('Wrong role',10002); this.error('Wrong role',10002);
} }
data.params.user_id=data.user.uid; let params=data.params;
let res = await this.dao.get('device').updateName(data.params); params.user_id=data.user.uid;
let res = await this.dao.get('device').updateName(params);
if (res) { if (res) {
return {success:res}; return {success:res};
} }
...@@ -164,8 +166,9 @@ class DeviceController extends ControllerBase{ ...@@ -164,8 +166,9 @@ class DeviceController extends ControllerBase{
* @param {string} nickname - 设备昵称 * @param {string} nickname - 设备昵称
*/ */
async setNicknameAction(data){ async setNicknameAction(data){
data.params.user_id=data.user.uid; let params=data.params;
let res = await this.dao.get('device').updateNickname(data.params); params.user_id=data.user.uid;
let res = await this.dao.get('device').updateNickname(params);
if (res) { if (res) {
return {success:res}; return {success:res};
} }
...@@ -187,8 +190,9 @@ class DeviceController extends ControllerBase{ ...@@ -187,8 +190,9 @@ class DeviceController extends ControllerBase{
* @param {string} nickname - 设备昵称 * @param {string} nickname - 设备昵称
*/ */
async bindAction(data){ async bindAction(data){
data.params.user=data.user; let params=data.params;
let bind = await this.public.core.bindDevice(data.params,true); params.user=data.user;
let bind = await this.public.core.bindDevice(params,true);
if (bind) { if (bind) {
return {success:true}; return {success:true};
} }
...@@ -211,8 +215,9 @@ class DeviceController extends ControllerBase{ ...@@ -211,8 +215,9 @@ class DeviceController extends ControllerBase{
* @param {string} nickname - 设备昵称 * @param {string} nickname - 设备昵称
*/ */
async newBindAction(data){ async newBindAction(data){
data.params.user=data.user; let params=data.params;
let bind = await this.public.core.bindDevice(data.params,false); params.user=data.user;
let bind = await this.public.core.bindDevice(params,false);
if (bind) { if (bind) {
return {success:true}; return {success:true};
} }
...@@ -228,8 +233,9 @@ class DeviceController extends ControllerBase{ ...@@ -228,8 +233,9 @@ class DeviceController extends ControllerBase{
* @param {number} device_id - 设备编号 * @param {number} device_id - 设备编号
*/ */
async unbindAction(data){ async unbindAction(data){
data.params.user_id=data.user.uid; let params=data.params;
let bind = await this.public.core.delBindByDeviceIdAndUserId(data.params); params.user_id=data.user.uid;
let bind = await this.public.core.delBindByDeviceIdAndUserId(params);
if (bind) { if (bind) {
return bind; return bind;
} }
...@@ -247,13 +253,14 @@ class DeviceController extends ControllerBase{ ...@@ -247,13 +253,14 @@ class DeviceController extends ControllerBase{
if(!await this.public.core.checkRole({user_id:data.user.uid,device_id:data.params.device_id},"admin")){ if(!await this.public.core.checkRole({user_id:data.user.uid,device_id:data.params.device_id},"admin")){
this.error('Wrong role',10002); this.error('Wrong role',10002);
} }
let res = await this.public.core.delBindByDeviceIdAndUserId(data.params); let params=data.params;
let res = await this.public.core.delBindByDeviceIdAndUserId(params);
if (res) { if (res) {
return res; return res;
} }
this.error("fail to update",30500); this.error("fail to update",30500);
} }
@NoAuth @NoAuth
async getVersionAction(data){ async getVersionAction(data){
switch(data.params.type){ switch(data.params.type){
...@@ -288,12 +295,12 @@ class DeviceController extends ControllerBase{ ...@@ -288,12 +295,12 @@ class DeviceController extends ControllerBase{
} }
break; break;
} }
console.log()
if (!params.key) { if (!params.key) {
this.error('type is undefined',30010) this.error('type is undefined',30010)
} }
let res = await this.public.core.setVersion(params); let res = await this.public.core.setVersion(params);
return res; return res;
} }
} }
module.exports = DeviceController; module.exports = DeviceController;
\ No newline at end of file
/** /**
* DeviceDao.js * DeviceDao.js
* Version: 0.1 * Version: 0.1
* User: zym * User: zym
...@@ -603,6 +603,23 @@ class DeviceDao extends DaoBase { ...@@ -603,6 +603,23 @@ class DeviceDao extends DaoBase {
} }
return res.role return res.role
} }
//查找用户与设备直接是否有关系
async findStatusByDeviceIdAndUserId(data) {
this.checkKeyExists(data, "user_id","device_id")
let res = await this.models.mysql.user_device.findAll({
attributes: ['id'],
raw: true,
where: {
status:1,
user_id: data.user_id,
device_id: data.device_id
}
});
if (res.length>0) {
return true;
}
return false;
}
//根据user_id获取info字段 //根据user_id获取info字段
async findUserInfo(data) { async findUserInfo(data) {
this.checkKeyExists(data, "user_id", "Key") this.checkKeyExists(data, "user_id", "Key")
...@@ -910,7 +927,7 @@ class DeviceDao extends DaoBase { ...@@ -910,7 +927,7 @@ class DeviceDao extends DaoBase {
as: 'device', as: 'device',
attributes: [], attributes: [],
where: { where: {
device_id:data.mac mac:data.mac
} }
}] }]
} }
...@@ -930,7 +947,7 @@ class DeviceDao extends DaoBase { ...@@ -930,7 +947,7 @@ class DeviceDao extends DaoBase {
as: 'device', as: 'device',
attributes: [], attributes: [],
where: { where: {
mac:data.mac device_id:data.mac
} }
},{ },{
model: this.models.mysql.user, model: this.models.mysql.user,
......
const MongoBase = require('iot-cloud-core').DB.MongoBase;
class OptionsModel extends MongoBase {
init() {
let model = this.createTable('system_option', {
key: {type: String},
value: {},
expireAt: {type: Date},
updateTime:{type: Date}
});
model.index({expireAt: 1}, { expireAfterSeconds: 0 });
return model;
}
}
module.exports = OptionsModel;
\ No newline at end of file
...@@ -39,6 +39,13 @@ class Public extends PublicFunBase{ ...@@ -39,6 +39,13 @@ class Public extends PublicFunBase{
checkRole(role,...action){ checkRole(role,...action){
return this.role.checkRole(role,action); return this.role.checkRole(role,action);
} }
checkStatus(user,...device){
let params={
user_id:user,
device_id:device
}
return this.dao.get('device').findStatusByDeviceIdAndUserId(params);
}
async sendModel(data){ async sendModel(data){
ServiceManager.execute("wxpush","push_wx", {appid:this.getConfig().wxAppId,msg:data.data}); ServiceManager.execute("wxpush","push_wx", {appid:this.getConfig().wxAppId,msg:data.data});
...@@ -121,24 +128,28 @@ class Public extends PublicFunBase{ ...@@ -121,24 +128,28 @@ class Public extends PublicFunBase{
} }
//单独绑定一个设备 //单独绑定一个设备
async bindDevice(data,condition){ async bindDevice(data,condition){
if (!data.device_id&&!data.mac && !data.product_id) { console.log("product_id"+data.product_id);
this.error('缺少参数(device_id、mac、product_id)',30805) if (!data.device_id&&!data.mac) {
} this.error('没有设备mac或id',30805)
}
let tip=this.getConfig(); let tip=this.getConfig();
let product_id = tip[data.product_id]?tip[data.product_id]:data.product_id; console.log(tip);
console.log(tip[data.product_id]);
let auth; let auth;
if (condition) { if (condition) {
auth = await this.checkOrCreateDeviceAuth({'mac':data.mac?data.mac:data.device_id,'product_id':product_id}); auth = await ServiceManager.execute("devices","deviceAuth", {'mac':data.mac?data.mac:data.device_id,'product_id':tip[data.product_id]});
}else{ }else{
auth = await ServiceManager.execute("devices","cloudDeviceAuth", {'mac':data.mac?data.mac:data.device_id,'product_id':product_id}); auth = await ServiceManager.execute("devices","cloudDeviceAuth", {'mac':data.mac?data.mac:data.device_id,'product_id':tip[data.product_id]});
} }
console.log("res")
console.log(auth)
if (!auth) { if (!auth) {
this.error('没有权限注册设备',30806); this.error('没有权限注册设备',30806);
} }
let res = await this.dao.get('device').findDevice(data);//查询绑定设备是否存在 let res = await this.dao.get('device').findDevice(data);//查询绑定设备是否存在
let device_date={ let device_date={
device_id:data.device_id?data.device_id:data.mac, device_id:data.device_id?data.device_id:data.mac,
product_id:product_id, product_id:tip[data.product_id],
mac:data.mac?data.mac:data.device_id, mac:data.mac?data.mac:data.device_id,
device_name: data.nickname?data.nickname:"我的设备", device_name: data.nickname?data.nickname:"我的设备",
parent_id: 0, parent_id: 0,
...@@ -354,7 +365,7 @@ class Public extends PublicFunBase{ ...@@ -354,7 +365,7 @@ class Public extends PublicFunBase{
//注册设备 //注册设备
async regDevice(data){ async regDevice(data){
let tip=this.getConfig(); let tip=this.getConfig();
data.product_id = tip[data.product_id]?tip[data.product_id]:data.product_id; data.product_id=tip[data.product_id];
return await this.dao.get('device').createDevice(data); return await this.dao.get('device').createDevice(data);
} }
//设置权限 //设置权限
...@@ -481,5 +492,16 @@ class Public extends PublicFunBase{ ...@@ -481,5 +492,16 @@ class Public extends PublicFunBase{
newUser.utoken = data.auth.sign(Calculation.signParams(newUser.id)); newUser.utoken = data.auth.sign(Calculation.signParams(newUser.id));
return newUser; return newUser;
} }
async findDeviceUser(data){
let params=data;
params.status=1;
let res={};
res.count = await this.dao.get('device').countDeviceUser(params);
console.log(params)
res.info = await this.dao.get('device').findDeviceUserByMac(params);
return res;
}
} }
module.exports = Public; module.exports = Public;
\ No newline at end of file
/**
* Public.js
* Version: 0.2
* User: zym
* Date: 2017-09-05
* Copyright(c) 2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* public
*/
const PublicFunBase = require('iot-cloud-core').BASE.PublicFunBase;
const Role = require('../Util/Role');
// const SDSSDK = require('../Util/SDSTopSDK');
const ServiceManager = require('iot-cloud-fs');
const LOG = require('iot-cloud-core').LOG;
const UAformater = require('ua-format-js').UAFormat();
const Calculation = require('../controller/public/Calculation');
const WXSDK = require('../Util/WXSDK');
class Public extends PublicFunBase{
/*
* 设置系统参数
*/
constructor(){
super();
this.role = new Role();
}
async afterInit(){
// this.SDSSDK= new SDSSDK();
this.role.setDao(this.dao);
//实例微信sdk
this.WXSDK = new WXSDK({appid:this.getConfig().wxAppId});
}
addRole(action,...roles){
this.role.addRole(action,...roles);
}
checkRole(role,...action){
return this.role.checkRole(role,action);
}
checkStatus(user,...device){
let params={
user_id:user,
device_id:device
}
return this.dao.get('device').findStatusByDeviceIdAndUserId(params);
}
async sendModel(data){
ServiceManager.execute("wxpush","push_wx", {appid:this.getConfig().wxAppId,msg:data.data});
}
//获取版本号
async getVersion(data){
let res = await ServiceManager.execute("version","getVersion", {appid:this.getConfig().wxAppId,type:data.type});
if (res) {
return res.value;
}
return false
}
//修改版本号
async setVersion(data){
return await ServiceManager.execute("version","setVersion", {key:data.key,msg:data});
}
//绑定设备
async bind(data){
let params=[{}];
let update={};
if (data.id&&data.device_name&&data.role) {
update={
info:[{
id:null,
device_name:data.device_name,//设备昵称
device_id:data.id,//绑定设备id
}],
user_id:data.user_id,
role:data.role,//用户权限
status:1
};
let device_binder=await this.dao.get('device').findBindInfo({//查询绑定设备是否绑定
user_id:data.user_id,
device_id:data.id
});
if (device_binder) {//判断绑定设备是否曾经有过关系
if (device_binder.status==1) {//已绑定
this.error('user is already bind',30803);
}
if (device_binder.status==0||device_binder.status==2) {//设备绑定过但已逻辑删除
update.info[0].id=device_binder.id;//已绑定过但逻辑删除的关系id
}
}
if (data.parent_id){//是否需要绑定父设备
let binder=await this.dao.get('device').findDeviceInfoByDeviceIdAndUserId({//查询父设备名称及父设备是否绑定
user_id:data.user_id,
device_id:data.parent_id
});
if (binder.id) {
if (!binder.user_device_id) {
update.info[1]={
id:null,
device_id:data.parent_id,
device_name:binder.device_name//父设备昵称
};
}
if (binder.user_device_id) {//判断父设备是否绑定过 如绑定过但已逻辑删除 则更新
update.info[1]={
id:binder.user_device_id,
device_id:data.parent_id,
device_name:binder.status==0?binder.device_name:binder.nickname//父设备昵称
};
}
}else{
return false;
}
}
let add = await this.dao.get('device').createOrUpdateDevice(update);//将参数传入 绑定
if (add) {
return update;
}else{
return add;
}
}else{
return false;
// this.error('device is undefined',30804);
}
}
//单独绑定一个设备
async bindDevice(data,condition){
if (!data.device_id&&!data.mac) {
this.error('没有设备mac或id',30805)
}
let tip=this.getConfig();
let auth;
if (condition) {
auth = await ServiceManager.execute("devices","deviceAuth", {'mac':data.mac?data.mac:data.device_id,'product_id':tip[data.product_id]});
}else{
auth = await ServiceManager.execute("devices","cloudDeviceAuth", {'mac':data.mac?data.mac:data.device_id,'product_id':tip[data.product_id]});
}
if (!auth) {
this.error('没有权限注册设备',30806);
}
let res = await this.dao.get('device').findDevice(data);//查询绑定设备是否存在
let device_date={
device_id:data.device_id?data.device_id:data.mac,
product_id:tip[data.product_id],
mac:data.mac?data.mac:data.device_id,
device_name: data.nickname?data.nickname:"我的设备",
parent_id: 0,
status:1,
device_state:1,
info: data.info?data.info:{}
};
if (res) {
var device_binder=await this.dao.get('device').findBindInfo({//查询用户是否绑定过此设备
user_id:data.user.uid,
device_id:res.id
});
if (device_binder) {//判断绑定设备是否曾经有过关系
if (device_binder.status==1) {//已绑定
this.error('user is already bind',30803);
}
}
device_date.id=res.id;//更新用id
}
res=await this.dao.get('device').createDevice(device_date);//如果曾经绑定过此设备则更新没有则创建
let update={
info:[{
id:null,
device_id:res.id,//绑定设备id
device_name:data.nickname?data.nickname:"我的设备"//设备昵称
}],
user_id:data.user.uid,//用户id
role:data.role?data.role:"SA",//是否管理员
status:1//将状态设置为绑定
};
if (device_binder){
if(device_binder.status==2||device_binder.status==0) {//设备绑定过但已逻辑删除
update.info[0].id=device_binder.id;//已绑定过但逻辑删除的关系id
}
}
let add = await this.dao.get('device').createOrUpdateDevice(update);//将参数传入 绑定
if(add){
return true;
}else{
return false;
}
}
//批量绑定更新设备
async createOrUpdateDevice(data){
return await this.dao.get('device').createOrUpdateDevice(data);
}
//sds推送绑定设备
// async sdsBind(data){
// let info={
// device_id:data.sn,
// }
// }
//查找用户绑定设备
async findDeviceByUserId(data){
return await this.dao.get('device').findDeviceByUserId(data);
}
async userReg(data,username,pwd,cid) {
try{
let salt = Calculation.getSalt();
let salt_pwd = Calculation.generatePassword(pwd,salt);
let ua = UAformater.setUA(data.header['user-agent']).getResult();
let user = {
username:username,
pwd:salt_pwd,
salt:salt,
info:{
mobiletype:ua.os.name?ua.os.name:'null',
version:ua.os.version?ua.os.version:'null',
useragent:ua?ua:'null'
}
};
if (cid) {
user.info.clienId=cid
}
let res = await this.dao.get('user').createUser(user);
let token = data.auth.sign(Calculation.signParams(res.id));
return {
"username":res.username,
"nickname":res.nickname,
"head":res.head,
"utoken":token
};
}catch(e){
console.log(e)
this.error("username is exists",20101);
}
}
//根据id来查找设备是否绑定过
async findUserDeviceByDeviceId(data){
return await this.dao.get('device').findUserDeviceByDeviceId(data);
}
//查询用户某网关下所有设备
async findUserDevice(data){
return await this.dao.get('device').findUserDevice(data);
}
//查询子设备
async findDeviceListWithParent(data){
return await this.dao.get('device').findDeviceListWithParent(data);
}
//查找用户所有子设备
async findAllDevice(data){
return await this.dao.get('device').findAllDevice(data);
}
//查找用户下特定父设备下所有子设备
async findDeviceByUserIdAndParentId(data){
return await this.dao.get('device').findDeviceByUserIdAndParentId(data);
}
//根据deviceId查找所有设备用户
async findDeviceUserByDeviceId(data){
return await this.dao.get('device').findDeviceUserByDeviceId(data);
}
//查询设备
async getList(data){
return await this.dao.get('device').findList(data);
}
//查询用户所有父设备
async findParentList(data){
return await this.dao.get('device').findParentList(data);
}
//查询用户已绑定的设备
async findBindInfo(data){
data.status=1;
return await this.dao.get('device').findBindInfo(data);
}
//根据id查询设备详情
async findinfo(data){
return await this.dao.get('device').findInfo(data);
}
//根据deviceid查找绑定关系
async findBindUserByDeviceId(data){
return await this.dao.get('device').findBindUserByDeviceId(data);
}
//根据id mac deviceid来查找设备
async findDevice(data){
return await this.dao.get('device').findDevice(data);
}
//根据id查找设备
async findDeviceById(data){
return await this.dao.get('device').findDeviceById(data);
}
//根据mac查找设备
async findDeviceByMac(data){
return await this.dao.get('device').findDeviceByMac(data);
}
//根据DeviceId查找设备
async findDeviceByDeviceId(data){
return await this.dao.get('device').findDeviceByDeviceId(data);
}
//根据Info参数查找设备
async findDeviceByInfo(data){
return await this.dao.get('device').findDeviceByInfo(data);
}
//根据设备id查找设备详情
async getDevice(data){
return await this.dao.get('device').findDeviceAndParent(data);
}
//根据时间查找最新一条设备详情
async getDeviceByTime(data){
return await this.dao.get('device').findDeviceAndParentByTime(data);
}
//获取userinfo
async findUserInfo(data){
return await this.dao.get('device').findUserInfo(data);
}
//获取多个用户的info信息
async findUserInfoById(data){
return await this.dao.get('user').findUserInfoById(data);
}
//获取设备info 根据设备id
async getDeviceInfoById(data){
return await this.dao.get('device').findDeviceInfoById(data);
}
//获取设备info 根据父设备id
async getDeviceInfoByPid(data){
return await this.dao.get('device').findDeviceInfoByPid(data);
}
//删除指定用户的设备
async delBindByDeviceIdAndUserId(data){
return await this.dao.get('device').delBind(data);
}
async delBindByParentId(data){
return await this.dao.get('device').delBindByParentId(data);
}
//删除设备关系
async delBindByDeviceId(data){
return await this.dao.get('device').delBindByDeviceId(data);
}
//根据id删除设备信息
async delDevice(data){
return await this.dao.get('device').delDeviceById(data);
}
//根据父设备id删除设备信息
async delDeviceByParent(data){
return await this.dao.get('device').delDeviceByParent(data);
}
//根据device_id和mac查找父子设备
async findDeviceByDeviceIdAndMac(data){
return await this.dao.get('device').findDeviceByDeviceIdAndMac(data);
}
//注册设备
async regDevice(data){
let tip=this.getConfig();
data.product_id=tip[data.product_id];
return await this.dao.get('device').createDevice(data);
}
//设置权限
async setRole(data){
return await this.dao.get('device').setRole(data);
}
//根据自增id设置权限
async setRoleById(data){
return await this.dao.get('device').setRoleById(data);
}
//设置userinfo
async setUserInfo(data){
return await this.dao.get('device').setUserInfo(data);
}
//修改个推cid
async updateCidById(data){
return await this.dao.get('user').updateCidById(data);
}
async setUserNameAndHeadAndInfo(data){
return await this.dao.get('user').setUserNameAndHeadAndInfo(data);
}
//登出时清楚特定的用户数据
async logout(data){
return await this.dao.get('user').logout(data);
}
//设置deviceinfo
async setDeviceState(data){
return await this.dao.get('device').setDeviceInfo(data);
}
async setUserDeviceInfoCover(data){
return await this.dao.get('device').setUserDeviceInfoCover(data)
}
//根据username查询用户
async searchByName(data){
return await this.dao.get('user').searchByName(data);
}
//根据id查询用户
async searchById(data){
return await this.dao.get('user').findUserById(data);
}
//获取utoken
async getUToken(data){
return data.auth.sign({"uid":data.user.id});
}
//检查设备注册权限
async checkDeviceAuth(data){
return await ServiceManager.execute("devices","deviceAuth", {'mac':data.mac,'product_id':data.product_id});
}
async checkOrCreateDeviceAuth(data){
return await ServiceManager.execute("devices","deviceAuthAndCreate", {'mac':data.mac,'product_id':data.product_id});
}
async auth(data){
return await this.WXSDK.auth(data);
}
//获取wx用户信息
async getUserinfo(data){
return this.WXSDK.getUserinfo(data);
}
//wx解绑设备
async wxUnbind(data){
return this.WXSDK.unBind(data);
}
//微信绑定设备
async wxBindDevice(data){
return this.WXSDK.bindDevice(data);
}
//微信强制解绑设备
async wxCompelUnbind(data){
return this.WXSDK.compelUnbind(data)
}
// async sdsFindList(data){
// return this.SDSSDK.findList();
// }
//获取签名
async getSign(data){
return this.WXSDK.getSign(data);
}
//根据username查找或创建用户
async findOrCreateUser(data){
let update={
username:data.username,
info:{},
condition:true,
salt:Math.random().toString(36).substr(2, 6)
}
return await this.dao.get("user").createWXUser(update);
}
//自定义登录
async wxLogin(data){
let wxParams = {
code:data.params.code,
appid:data.appid
}
let auth = await this.WXSDK.auth(wxParams);
if (auth.errcode) {
LOG.error(auth)
return auth;
}
let uParams = {
appid:data.appid,
access_token:auth.access_token,
openid:auth.openid
};
let wxUserInfo =await this.WXSDK.getUserinfo(uParams);
let userParams = {
username: auth.openid,
nickname: wxUserInfo.nickname,
head: wxUserInfo.headimgurl,
salt:Math.random().toString(36).substr(2, 6)
}
let ua = UAformater.setUA(data.header['user-agent']).getResult();
userParams.info = {
mobiletype:ua.os.name,
version:ua.os.version,
useragent:ua
};
//注册新用户,有的话就更新
let newUser = await this.dao.get("user").createWXUser(userParams);
newUser.utoken = data.auth.sign(Calculation.signParams(newUser.id));
return newUser;
}
}
module.exports = Public;
\ No newline at end of file
...@@ -181,6 +181,9 @@ class DataPublicDao extends DaoBase{ ...@@ -181,6 +181,9 @@ class DataPublicDao extends DaoBase{
} }
async getHistoryByAggregaate(data){ async getHistoryByAggregaate(data){
if(data[0].$match._id){
data[0].$match._id = {$lt:mongoose.Types.ObjectId(data[0].$match._id)};
}
let getHistoryList = await this.models.mongo.data_history.aggregate(data); let getHistoryList = await this.models.mongo.data_history.aggregate(data);
//返回getHistoryList //返回getHistoryList
return getHistoryList; return getHistoryList;
......
const DaoBase = require('iot-cloud-core').BASE.DaoBase;
const mongoose = require('mongoose');
class DataPublicDao extends DaoBase{
//添加历史数据
//data接收Public中返回的data数据
async addHistory(params){
// this.checkKeyExists(data, "action");
// this.checkKeyExists(data, "data");
// //判断user_id或者device_id是否存在
let update={};
if(!params.user_id && !params.device_id){
return false;
}
if (!params.arr&&!params.action&&params.action!=0) {
return false;
}
if (params.device_id) {
update.device_id=params.device_id;
}
if (params.user_id) {
update.user_id=params.user_id;
}
if (params.type) {
update.type=params.type;
}
if (params.action>=0) {
update.action=params.action;
}
if (params.data) {
update.data=params.data;
}
if (params.arr) {
update=[];
for (let i=0;i<params.arr.length;i++) {
update[i]=params.arr[i];
if (params.device_id) {
update[i].device_id=params.device_id;
}
if (params.user_id) {
update[i].user_id=params.user_id;
}
}
}
//变量接收addHistory
try{
console.log(update)
let addHistory = await this.models.mongo.data_history.create(update);
//返回addHistory
return addHistory;
}catch(e){
console.log(e)
return false;
}
}
//获得历史数据
async getHistoryList(data){
// param.user_id和param.device_id存在一个或者两个都存在
// param.user_id
// param.device_id
// param.start_id
// param.page_size
// param.action
// param.start_time
// param.end_time
//用变量接收一个空的map
let HistoryProgram = {};
//判断user_id或者device_id是否存在一个
//若不存在则返回false
if (data.where) {
HistoryProgram=data.where;
}else{
if(! data.user_id && ! data.device_id){
return {'false':30000};
}
if (! data.type) {
return false;
}
HistoryProgram.type=data.type
if(data.user_id){
HistoryProgram.user_id = data.user_id;
}
if(data.device_id){
HistoryProgram.device_id = data.device_id;
}
if (data.action) {
HistoryProgram.action = data.action;
}
if(data.start_id&&data.start_id!=''){
HistoryProgram._id = {$lt:mongoose.Types.ObjectId(data.start_id)};
}
if(data.start_time){
HistoryProgram.create_time = {$gt:data.start_time};
}
if(data.end_time){
HistoryProgram.create_time = {$lt:data.end_time};
}
if(data.start_time && data.end_time){
HistoryProgram.create_time = {$gt:data.start_time,$lt:data.end_time}
}
}
if(! data.page_size){
data.page_size = 10;
}
if(data.order == 1 ){
data.order = parseInt(-1);
}
else if(data.order == 0){
data.order = parseInt(1);
}
else if(! data.order){
data.order = parseInt(-1);
}
//设置查询 POST需得到的值
// get.create_time = {$gt:data.start_time};
// get.create_time = {$lt:data.end_time};
// get._id = {$gt:data.start_id};
// get.action = data.action;
//变量接收getHistoryList
let getHistoryList = await this.models.mongo.data_history.find(HistoryProgram).limit(parseInt(data.page_size)).sort({create_time:data.order});
//返回getHistoryList
return getHistoryList;
}
//删除历史数据
async delHistory(data){
//变量接收delHistory
let delHistory = await this.models.mongo.data_history.findOneAndUpdate({"_id":data._id},{"status":2},{'new':true});
//返回delHistory
return {'code':0,'data':delHistory};
}
//设置Option
async setOption(data){
//设置表的参数
// await this.models.mongo.data_option.collection.createIndex({"expire_time":1},{expireAfterSeconds:8});
let params = {
key:data.key,
value:data.value
}
//判断数据是否有存活时间
if(data.expire_time != null){
params.expire_time = data.expire_time;
}
//变量接收setOption
let setOption = await this.models.mongo.data_option.findOneAndUpdate({"key":params.key},params,{'new':true,upsert:true});
//返回setOpion
return {'code':0,'data':setOption};
}
//获得Option
async getOption(data){
//变量接收getOption
let getOption = await this.models.mongo.data_option.findOne({"key":data.key});
//返回getOption
return {'code':0,'data':getOption};
}
}
module.exports = DataPublicDao;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment