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
...@@ -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